AsmPrinter.h revision 263508
1//===-- llvm/CodeGen/AsmPrinter.h - AsmPrinter Framework --------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains a class to be used as the base class for target specific
11// asm writers.  This class primarily handles common functionality used by
12// all asm writers.
13//
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_CODEGEN_ASMPRINTER_H
17#define LLVM_CODEGEN_ASMPRINTER_H
18
19#include "llvm/CodeGen/MachineFunctionPass.h"
20#include "llvm/IR/InlineAsm.h"
21#include "llvm/Support/DataTypes.h"
22#include "llvm/Support/ErrorHandling.h"
23
24namespace llvm {
25  class BlockAddress;
26  class GCStrategy;
27  class Constant;
28  class ConstantArray;
29  class GCMetadataPrinter;
30  class GlobalValue;
31  class GlobalVariable;
32  class MachineBasicBlock;
33  class MachineFunction;
34  class MachineInstr;
35  class MachineLocation;
36  class MachineLoopInfo;
37  class MachineLoop;
38  class MachineConstantPoolValue;
39  class MachineJumpTableInfo;
40  class MachineModuleInfo;
41  class MCAsmInfo;
42  class MCCFIInstruction;
43  class MCContext;
44  class MCInstrInfo;
45  class MCSection;
46  class MCStreamer;
47  class MCSymbol;
48  class MDNode;
49  class DwarfDebug;
50  class DwarfException;
51  class Mangler;
52  class TargetLoweringObjectFile;
53  class DataLayout;
54  class TargetMachine;
55
56  /// AsmPrinter - This class is intended to be used as a driving class for all
57  /// asm writers.
58  class AsmPrinter : public MachineFunctionPass {
59  public:
60    /// Target machine description.
61    ///
62    TargetMachine &TM;
63
64    /// Target Asm Printer information.
65    ///
66    const MCAsmInfo *MAI;
67
68    const MCInstrInfo *MII;
69    /// OutContext - This is the context for the output file that we are
70    /// streaming.  This owns all of the global MC-related objects for the
71    /// generated translation unit.
72    MCContext &OutContext;
73
74    /// OutStreamer - This is the MCStreamer object for the file we are
75    /// generating.  This contains the transient state for the current
76    /// translation unit that we are generating (such as the current section
77    /// etc).
78    MCStreamer &OutStreamer;
79
80    /// The current machine function.
81    const MachineFunction *MF;
82
83    /// MMI - This is a pointer to the current MachineModuleInfo.
84    MachineModuleInfo *MMI;
85
86    /// Name-mangler for global names.
87    ///
88    Mangler *Mang;
89
90    /// The symbol for the current function. This is recalculated at the
91    /// beginning of each call to runOnMachineFunction().
92    ///
93    MCSymbol *CurrentFnSym;
94
95    /// The symbol used to represent the start of the current function for the
96    /// purpose of calculating its size (e.g. using the .size directive). By
97    /// default, this is equal to CurrentFnSym.
98    MCSymbol *CurrentFnSymForSize;
99
100  private:
101    // GCMetadataPrinters - The garbage collection metadata printer table.
102    void *GCMetadataPrinters;  // Really a DenseMap.
103
104    /// VerboseAsm - Emit comments in assembly output if this is true.
105    ///
106    bool VerboseAsm;
107    static char ID;
108
109    /// If VerboseAsm is set, a pointer to the loop info for this
110    /// function.
111    MachineLoopInfo *LI;
112
113    /// DD - If the target supports dwarf debug info, this pointer is non-null.
114    DwarfDebug *DD;
115
116    /// DE - If the target supports dwarf exception info, this pointer is
117    /// non-null.
118    DwarfException *DE;
119
120  protected:
121    explicit AsmPrinter(TargetMachine &TM, MCStreamer &Streamer);
122
123  public:
124    virtual ~AsmPrinter();
125
126    const DwarfDebug *getDwarfDebug() const { return DD; }
127
128    /// isVerbose - Return true if assembly output should contain comments.
129    ///
130    bool isVerbose() const { return VerboseAsm; }
131
132    /// getFunctionNumber - Return a unique ID for the current function.
133    ///
134    unsigned getFunctionNumber() const;
135
136    /// getObjFileLowering - Return information about object file lowering.
137    const TargetLoweringObjectFile &getObjFileLowering() const;
138
139    /// getDataLayout - Return information about data layout.
140    const DataLayout &getDataLayout() const;
141
142    /// getTargetTriple - Return the target triple string.
143    StringRef getTargetTriple() const;
144
145    /// getCurrentSection() - Return the current section we are emitting to.
146    const MCSection *getCurrentSection() const;
147
148    MCSymbol *getSymbol(const GlobalValue *GV) const;
149
150    //===------------------------------------------------------------------===//
151    // MachineFunctionPass Implementation.
152    //===------------------------------------------------------------------===//
153
154    /// getAnalysisUsage - Record analysis usage.
155    ///
156    void getAnalysisUsage(AnalysisUsage &AU) const;
157
158    /// doInitialization - Set up the AsmPrinter when we are working on a new
159    /// module.  If your pass overrides this, it must make sure to explicitly
160    /// call this implementation.
161    bool doInitialization(Module &M);
162
163    /// doFinalization - Shut down the asmprinter.  If you override this in your
164    /// pass, you must make sure to call it explicitly.
165    bool doFinalization(Module &M);
166
167    /// runOnMachineFunction - Emit the specified function out to the
168    /// OutStreamer.
169    virtual bool runOnMachineFunction(MachineFunction &MF) {
170      SetupMachineFunction(MF);
171      EmitFunctionHeader();
172      EmitFunctionBody();
173      return false;
174    }
175
176    //===------------------------------------------------------------------===//
177    // Coarse grained IR lowering routines.
178    //===------------------------------------------------------------------===//
179
180    /// SetupMachineFunction - This should be called when a new MachineFunction
181    /// is being processed from runOnMachineFunction.
182    void SetupMachineFunction(MachineFunction &MF);
183
184    /// EmitFunctionHeader - This method emits the header for the current
185    /// function.
186    void EmitFunctionHeader();
187
188    /// EmitFunctionBody - This method emits the body and trailer for a
189    /// function.
190    void EmitFunctionBody();
191
192    void emitPrologLabel(const MachineInstr &MI);
193
194    enum CFIMoveType {
195      CFI_M_None,
196      CFI_M_EH,
197      CFI_M_Debug
198    };
199    CFIMoveType needsCFIMoves();
200
201    bool needsSEHMoves();
202
203    /// needsRelocationsForDwarfStringPool - Specifies whether the object format
204    /// expects to use relocations to refer to debug entries. Alternatively we
205    /// emit section offsets in bytes from the start of the string pool.
206    bool needsRelocationsForDwarfStringPool() const;
207
208    /// EmitConstantPool - Print to the current output stream assembly
209    /// representations of the constants in the constant pool MCP. This is
210    /// used to print out constants which have been "spilled to memory" by
211    /// the code generator.
212    ///
213    virtual void EmitConstantPool();
214
215    /// EmitJumpTableInfo - Print assembly representations of the jump tables
216    /// used by the current function to the current output stream.
217    ///
218    void EmitJumpTableInfo();
219
220    /// EmitGlobalVariable - Emit the specified global variable to the .s file.
221    virtual void EmitGlobalVariable(const GlobalVariable *GV);
222
223    /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
224    /// special global used by LLVM.  If so, emit it and return true, otherwise
225    /// do nothing and return false.
226    bool EmitSpecialLLVMGlobal(const GlobalVariable *GV);
227
228    /// EmitAlignment - Emit an alignment directive to the specified power of
229    /// two boundary.  For example, if you pass in 3 here, you will get an 8
230    /// byte alignment.  If a global value is specified, and if that global has
231    /// an explicit alignment requested, it will override the alignment request
232    /// if required for correctness.
233    ///
234    void EmitAlignment(unsigned NumBits, const GlobalValue *GV = 0) const;
235
236    /// EmitBasicBlockStart - This method prints the label for the specified
237    /// MachineBasicBlock, an alignment (if present) and a comment describing
238    /// it if appropriate.
239    void EmitBasicBlockStart(const MachineBasicBlock *MBB) const;
240
241    /// \brief Print a general LLVM constant to the .s file.
242    void EmitGlobalConstant(const Constant *CV);
243
244
245    //===------------------------------------------------------------------===//
246    // Overridable Hooks
247    //===------------------------------------------------------------------===//
248
249    // Targets can, or in the case of EmitInstruction, must implement these to
250    // customize output.
251
252    /// EmitStartOfAsmFile - This virtual method can be overridden by targets
253    /// that want to emit something at the start of their file.
254    virtual void EmitStartOfAsmFile(Module &) {}
255
256    /// EmitEndOfAsmFile - This virtual method can be overridden by targets that
257    /// want to emit something at the end of their file.
258    virtual void EmitEndOfAsmFile(Module &) {}
259
260    /// EmitFunctionBodyStart - Targets can override this to emit stuff before
261    /// the first basic block in the function.
262    virtual void EmitFunctionBodyStart() {}
263
264    /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
265    /// the last basic block in the function.
266    virtual void EmitFunctionBodyEnd() {}
267
268    /// EmitInstruction - Targets should implement this to emit instructions.
269    virtual void EmitInstruction(const MachineInstr *) {
270      llvm_unreachable("EmitInstruction not implemented");
271    }
272
273    virtual void EmitFunctionEntryLabel();
274
275    virtual void EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV);
276
277    /// EmitXXStructor - Targets can override this to change how global
278    /// constants that are part of a C++ static/global constructor list are
279    /// emitted.
280    virtual void EmitXXStructor(const Constant *CV) {
281      EmitGlobalConstant(CV);
282    }
283
284    /// isBlockOnlyReachableByFallthough - Return true if the basic block has
285    /// exactly one predecessor and the control transfer mechanism between
286    /// the predecessor and this block is a fall-through.
287    virtual bool
288    isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const;
289
290    /// emitImplicitDef - Targets can override this to customize the output of
291    /// IMPLICIT_DEF instructions in verbose mode.
292    virtual void emitImplicitDef(const MachineInstr *MI) const;
293
294    //===------------------------------------------------------------------===//
295    // Symbol Lowering Routines.
296    //===------------------------------------------------------------------===//
297  public:
298
299    /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
300    /// temporary label with the specified stem and unique ID.
301    MCSymbol *GetTempSymbol(StringRef Name, unsigned ID) const;
302
303    /// GetTempSymbol - Return an assembler temporary label with the specified
304    /// stem.
305    MCSymbol *GetTempSymbol(StringRef Name) const;
306
307
308    /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
309    /// global value name as its base, with the specified suffix, and where the
310    /// symbol is forced to have private linkage if ForcePrivate is true.
311    MCSymbol *GetSymbolWithGlobalValueBase(const GlobalValue *GV,
312                                           StringRef Suffix,
313                                           bool ForcePrivate = true) const;
314
315    /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
316    /// ExternalSymbol.
317    MCSymbol *GetExternalSymbolSymbol(StringRef Sym) const;
318
319    /// GetCPISymbol - Return the symbol for the specified constant pool entry.
320    MCSymbol *GetCPISymbol(unsigned CPID) const;
321
322    /// GetJTISymbol - Return the symbol for the specified jump table entry.
323    MCSymbol *GetJTISymbol(unsigned JTID, bool isLinkerPrivate = false) const;
324
325    /// GetJTSetSymbol - Return the symbol for the specified jump table .set
326    /// FIXME: privatize to AsmPrinter.
327    MCSymbol *GetJTSetSymbol(unsigned UID, unsigned MBBID) const;
328
329    /// GetBlockAddressSymbol - Return the MCSymbol used to satisfy BlockAddress
330    /// uses of the specified basic block.
331    MCSymbol *GetBlockAddressSymbol(const BlockAddress *BA) const;
332    MCSymbol *GetBlockAddressSymbol(const BasicBlock *BB) const;
333
334    //===------------------------------------------------------------------===//
335    // Emission Helper Routines.
336    //===------------------------------------------------------------------===//
337  public:
338    /// printOffset - This is just convenient handler for printing offsets.
339    void printOffset(int64_t Offset, raw_ostream &OS) const;
340
341    /// EmitInt8 - Emit a byte directive and value.
342    ///
343    void EmitInt8(int Value) const;
344
345    /// EmitInt16 - Emit a short directive and value.
346    ///
347    void EmitInt16(int Value) const;
348
349    /// EmitInt32 - Emit a long directive and value.
350    ///
351    void EmitInt32(int Value) const;
352
353    /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
354    /// in bytes of the directive is specified by Size and Hi/Lo specify the
355    /// labels.  This implicitly uses .set if it is available.
356    void EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
357                             unsigned Size) const;
358
359    /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
360    /// where the size in bytes of the directive is specified by Size and Hi/Lo
361    /// specify the labels.  This implicitly uses .set if it is available.
362    void EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
363                                   const MCSymbol *Lo, unsigned Size) const;
364
365    /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
366    /// where the size in bytes of the directive is specified by Size and Label
367    /// specifies the label.  This implicitly uses .set if it is available.
368    void EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
369                             unsigned Size,
370                             bool IsSectionRelative = false) const;
371
372    /// EmitLabelReference - Emit something like ".long Label"
373    /// where the size in bytes of the directive is specified by Size and Label
374    /// specifies the label.
375    void EmitLabelReference(const MCSymbol *Label, unsigned Size,
376                            bool IsSectionRelative = false) const {
377      EmitLabelPlusOffset(Label, 0, Size, IsSectionRelative);
378    }
379
380    //===------------------------------------------------------------------===//
381    // Dwarf Emission Helper Routines
382    //===------------------------------------------------------------------===//
383
384    /// EmitSLEB128 - emit the specified signed leb128 value.
385    void EmitSLEB128(int64_t Value, const char *Desc = 0) const;
386
387    /// EmitULEB128 - emit the specified unsigned leb128 value.
388    void EmitULEB128(uint64_t Value, const char *Desc = 0,
389                     unsigned PadTo = 0) const;
390
391    /// EmitCFAByte - Emit a .byte 42 directive for a DW_CFA_xxx value.
392    void EmitCFAByte(unsigned Val) const;
393
394    /// EmitEncodingByte - Emit a .byte 42 directive that corresponds to an
395    /// encoding.  If verbose assembly output is enabled, we output comments
396    /// describing the encoding.  Desc is a string saying what the encoding is
397    /// specifying (e.g. "LSDA").
398    void EmitEncodingByte(unsigned Val, const char *Desc = 0) const;
399
400    /// GetSizeOfEncodedValue - Return the size of the encoding in bytes.
401    unsigned GetSizeOfEncodedValue(unsigned Encoding) const;
402
403    /// EmitReference - Emit reference to a ttype global with a specified encoding.
404    void EmitTTypeReference(const GlobalValue *GV, unsigned Encoding) const;
405
406    /// EmitSectionOffset - Emit the 4-byte offset of Label from the start of
407    /// its section.  This can be done with a special directive if the target
408    /// supports it (e.g. cygwin) or by emitting it as an offset from a label at
409    /// the start of the section.
410    ///
411    /// SectionLabel is a temporary label emitted at the start of the section
412    /// that Label lives in.
413    void EmitSectionOffset(const MCSymbol *Label,
414                           const MCSymbol *SectionLabel) const;
415
416    /// getISAEncoding - Get the value for DW_AT_APPLE_isa. Zero if no isa
417    /// encoding specified.
418    virtual unsigned getISAEncoding() { return 0; }
419
420    /// EmitDwarfRegOp - Emit dwarf register operation.
421    virtual void EmitDwarfRegOp(const MachineLocation &MLoc,
422                                bool Indirect) const;
423
424    //===------------------------------------------------------------------===//
425    // Dwarf Lowering Routines
426    //===------------------------------------------------------------------===//
427
428    /// \brief Emit frame instruction to describe the layout of the frame.
429    void emitCFIInstruction(const MCCFIInstruction &Inst) const;
430
431    //===------------------------------------------------------------------===//
432    // Inline Asm Support
433    //===------------------------------------------------------------------===//
434  public:
435    // These are hooks that targets can override to implement inline asm
436    // support.  These should probably be moved out of AsmPrinter someday.
437
438    /// PrintSpecial - Print information related to the specified machine instr
439    /// that is independent of the operand, and may be independent of the instr
440    /// itself.  This can be useful for portably encoding the comment character
441    /// or other bits of target-specific knowledge into the asmstrings.  The
442    /// syntax used is ${:comment}.  Targets can override this to add support
443    /// for their own strange codes.
444    virtual void PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
445                              const char *Code) const;
446
447    /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
448    /// instruction, using the specified assembler variant.  Targets should
449    /// override this to format as appropriate.  This method can return true if
450    /// the operand is erroneous.
451    virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
452                                 unsigned AsmVariant, const char *ExtraCode,
453                                 raw_ostream &OS);
454
455    /// PrintAsmMemoryOperand - Print the specified operand of MI, an INLINEASM
456    /// instruction, using the specified assembler variant as an address.
457    /// Targets should override this to format as appropriate.  This method can
458    /// return true if the operand is erroneous.
459    virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
460                                       unsigned AsmVariant,
461                                       const char *ExtraCode, raw_ostream &OS);
462
463  private:
464    /// Private state for PrintSpecial()
465    // Assign a unique ID to this machine instruction.
466    mutable const MachineInstr *LastMI;
467    mutable unsigned LastFn;
468    mutable unsigned Counter;
469    mutable unsigned SetCounter;
470
471    /// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
472    void EmitInlineAsm(StringRef Str, const MDNode *LocMDNode = 0,
473                       InlineAsm::AsmDialect AsmDialect =
474                           InlineAsm::AD_ATT) const;
475
476    /// EmitInlineAsm - This method formats and emits the specified machine
477    /// instruction that is an inline asm.
478    void EmitInlineAsm(const MachineInstr *MI) const;
479
480    //===------------------------------------------------------------------===//
481    // Internal Implementation Details
482    //===------------------------------------------------------------------===//
483
484    /// EmitVisibility - This emits visibility information about symbol, if
485    /// this is suported by the target.
486    void EmitVisibility(MCSymbol *Sym, unsigned Visibility,
487                        bool IsDefinition = true) const;
488
489    void EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const;
490
491    void EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
492                            const MachineBasicBlock *MBB, unsigned uid) const;
493    void EmitLLVMUsedList(const ConstantArray *InitList);
494    /// Emit llvm.ident metadata in an '.ident' directive.
495    void EmitModuleIdents(Module &M);
496    void EmitXXStructorList(const Constant *List, bool isCtor);
497    GCMetadataPrinter *GetOrCreateGCPrinter(GCStrategy *C);
498  };
499}
500
501#endif
502