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