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