8a46d331711b9660737883c5ea6742470591bfcb
[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     void getNameWithPrefix(SmallVectorImpl<char> &Name,
165                            const GlobalValue *GV) const;
166
167     MCSymbol *getSymbol(const GlobalValue *GV) const;
168
169     //===------------------------------------------------------------------===//
170     // MachineFunctionPass Implementation.
171     //===------------------------------------------------------------------===//
172
173     /// getAnalysisUsage - Record analysis usage.
174     ///
175     void getAnalysisUsage(AnalysisUsage &AU) const;
176
177     /// doInitialization - Set up the AsmPrinter when we are working on a new
178     /// module.  If your pass overrides this, it must make sure to explicitly
179     /// call this implementation.
180     bool doInitialization(Module &M);
181
182     /// doFinalization - Shut down the asmprinter.  If you override this in your
183     /// pass, you must make sure to call it explicitly.
184     bool doFinalization(Module &M);
185
186     /// runOnMachineFunction - Emit the specified function out to the
187     /// OutStreamer.
188     virtual bool runOnMachineFunction(MachineFunction &MF) {
189       SetupMachineFunction(MF);
190       EmitFunctionHeader();
191       EmitFunctionBody();
192       return false;
193     }
194
195     //===------------------------------------------------------------------===//
196     // Coarse grained IR lowering routines.
197     //===------------------------------------------------------------------===//
198
199     /// SetupMachineFunction - This should be called when a new MachineFunction
200     /// is being processed from runOnMachineFunction.
201     void SetupMachineFunction(MachineFunction &MF);
202
203     /// EmitFunctionHeader - This method emits the header for the current
204     /// function.
205     void EmitFunctionHeader();
206
207     /// EmitFunctionBody - This method emits the body and trailer for a
208     /// function.
209     void EmitFunctionBody();
210
211     void emitPrologLabel(const MachineInstr &MI);
212
213     enum CFIMoveType {
214       CFI_M_None,
215       CFI_M_EH,
216       CFI_M_Debug
217     };
218     CFIMoveType needsCFIMoves();
219
220     bool needsSEHMoves();
221
222     /// EmitConstantPool - Print to the current output stream assembly
223     /// representations of the constants in the constant pool MCP. This is
224     /// used to print out constants which have been "spilled to memory" by
225     /// the code generator.
226     ///
227     virtual void EmitConstantPool();
228
229     /// EmitJumpTableInfo - Print assembly representations of the jump tables
230     /// used by the current function to the current output stream.
231     ///
232     void EmitJumpTableInfo();
233
234     /// EmitGlobalVariable - Emit the specified global variable to the .s file.
235     virtual void EmitGlobalVariable(const GlobalVariable *GV);
236
237     /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
238     /// special global used by LLVM.  If so, emit it and return true, otherwise
239     /// do nothing and return false.
240     bool EmitSpecialLLVMGlobal(const GlobalVariable *GV);
241
242     /// EmitAlignment - Emit an alignment directive to the specified power of
243     /// two boundary.  For example, if you pass in 3 here, you will get an 8
244     /// byte alignment.  If a global value is specified, and if that global has
245     /// an explicit alignment requested, it will override the alignment request
246     /// if required for correctness.
247     ///
248     void EmitAlignment(unsigned NumBits, const GlobalValue *GV = 0) const;
249
250     /// EmitBasicBlockStart - This method prints the label for the specified
251     /// MachineBasicBlock, an alignment (if present) and a comment describing
252     /// it if appropriate.
253     void EmitBasicBlockStart(const MachineBasicBlock *MBB) const;
254
255     /// \brief Print a general LLVM constant to the .s file.
256     void EmitGlobalConstant(const Constant *CV);
257
258
259     //===------------------------------------------------------------------===//
260     // Overridable Hooks
261     //===------------------------------------------------------------------===//
262
263     // Targets can, or in the case of EmitInstruction, must implement these to
264     // customize output.
265
266     /// EmitStartOfAsmFile - This virtual method can be overridden by targets
267     /// that want to emit something at the start of their file.
268     virtual void EmitStartOfAsmFile(Module &) {}
269
270     /// EmitEndOfAsmFile - This virtual method can be overridden by targets that
271     /// want to emit something at the end of their file.
272     virtual void EmitEndOfAsmFile(Module &) {}
273
274     /// EmitFunctionBodyStart - Targets can override this to emit stuff before
275     /// the first basic block in the function.
276     virtual void EmitFunctionBodyStart() {}
277
278     /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
279     /// the last basic block in the function.
280     virtual void EmitFunctionBodyEnd() {}
281
282     /// EmitInstruction - Targets should implement this to emit instructions.
283     virtual void EmitInstruction(const MachineInstr *) {
284       llvm_unreachable("EmitInstruction not implemented");
285     }
286
287     virtual void EmitFunctionEntryLabel();
288
289     virtual void EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV);
290
291     /// EmitXXStructor - Targets can override this to change how global
292     /// constants that are part of a C++ static/global constructor list are
293     /// emitted.
294     virtual void EmitXXStructor(const Constant *CV) {
295       EmitGlobalConstant(CV);
296     }
297
298     /// isBlockOnlyReachableByFallthough - Return true if the basic block has
299     /// exactly one predecessor and the control transfer mechanism between
300     /// the predecessor and this block is a fall-through.
301     virtual bool
302     isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const;
303
304     /// emitImplicitDef - Targets can override this to customize the output of
305     /// IMPLICIT_DEF instructions in verbose mode.
306     virtual void emitImplicitDef(const MachineInstr *MI) const;
307
308     //===------------------------------------------------------------------===//
309     // Symbol Lowering Routines.
310     //===------------------------------------------------------------------===//
311   public:
312
313     /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
314     /// temporary label with the specified stem and unique ID.
315     MCSymbol *GetTempSymbol(StringRef Name, unsigned ID) const;
316
317     /// GetTempSymbol - Return an assembler temporary label with the specified
318     /// stem.
319     MCSymbol *GetTempSymbol(StringRef Name) const;
320
321     /// Return the MCSymbol for a private symbol with global value name as its
322     /// base, with the specified suffix.
323     MCSymbol *getSymbolWithGlobalValueBase(const GlobalValue *GV,
324                                            StringRef Suffix) const;
325
326     /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
327     /// ExternalSymbol.
328     MCSymbol *GetExternalSymbolSymbol(StringRef Sym) const;
329
330     /// GetCPISymbol - Return the symbol for the specified constant pool entry.
331     MCSymbol *GetCPISymbol(unsigned CPID) const;
332
333     /// GetJTISymbol - Return the symbol for the specified jump table entry.
334     MCSymbol *GetJTISymbol(unsigned JTID, bool isLinkerPrivate = false) const;
335
336     /// GetJTSetSymbol - Return the symbol for the specified jump table .set
337     /// FIXME: privatize to AsmPrinter.
338     MCSymbol *GetJTSetSymbol(unsigned UID, unsigned MBBID) const;
339
340     /// GetBlockAddressSymbol - Return the MCSymbol used to satisfy BlockAddress
341     /// uses of the specified basic block.
342     MCSymbol *GetBlockAddressSymbol(const BlockAddress *BA) const;
343     MCSymbol *GetBlockAddressSymbol(const BasicBlock *BB) const;
344
345     //===------------------------------------------------------------------===//
346     // Emission Helper Routines.
347     //===------------------------------------------------------------------===//
348   public:
349     /// printOffset - This is just convenient handler for printing offsets.
350     void printOffset(int64_t Offset, raw_ostream &OS) const;
351
352     /// EmitInt8 - Emit a byte directive and value.
353     ///
354     void EmitInt8(int Value) const;
355
356     /// EmitInt16 - Emit a short directive and value.
357     ///
358     void EmitInt16(int Value) const;
359
360     /// EmitInt32 - Emit a long directive and value.
361     ///
362     void EmitInt32(int Value) const;
363
364     /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
365     /// in bytes of the directive is specified by Size and Hi/Lo specify the
366     /// labels.  This implicitly uses .set if it is available.
367     void EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
368                              unsigned Size) const;
369
370     /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
371     /// where the size in bytes of the directive is specified by Size and Hi/Lo
372     /// specify the labels.  This implicitly uses .set if it is available.
373     void EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
374                                    const MCSymbol *Lo, unsigned Size) const;
375
376     /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
377     /// where the size in bytes of the directive is specified by Size and Label
378     /// specifies the label.  This implicitly uses .set if it is available.
379     void EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
380                              unsigned Size,
381                              bool IsSectionRelative = false) const;
382
383     /// EmitLabelReference - Emit something like ".long Label"
384     /// where the size in bytes of the directive is specified by Size and Label
385     /// specifies the label.
386     void EmitLabelReference(const MCSymbol *Label, unsigned Size,
387                             bool IsSectionRelative = false) const {
388       EmitLabelPlusOffset(Label, 0, Size, IsSectionRelative);
389     }
390
391     //===------------------------------------------------------------------===//
392     // Dwarf Emission Helper Routines
393     //===------------------------------------------------------------------===//
394
395     /// EmitSLEB128 - emit the specified signed leb128 value.
396     void EmitSLEB128(int64_t Value, const char *Desc = 0) const;
397
398     /// EmitULEB128 - emit the specified unsigned leb128 value.
399     void EmitULEB128(uint64_t Value, const char *Desc = 0,
400                      unsigned PadTo = 0) const;
401
402     /// EmitCFAByte - Emit a .byte 42 directive for a DW_CFA_xxx value.
403     void EmitCFAByte(unsigned Val) const;
404
405     /// EmitEncodingByte - Emit a .byte 42 directive that corresponds to an
406     /// encoding.  If verbose assembly output is enabled, we output comments
407     /// describing the encoding.  Desc is a string saying what the encoding is
408     /// specifying (e.g. "LSDA").
409     void EmitEncodingByte(unsigned Val, const char *Desc = 0) const;
410
411     /// GetSizeOfEncodedValue - Return the size of the encoding in bytes.
412     unsigned GetSizeOfEncodedValue(unsigned Encoding) const;
413
414     /// EmitReference - Emit reference to a ttype global with a specified encoding.
415     void EmitTTypeReference(const GlobalValue *GV, unsigned Encoding) const;
416
417     /// EmitSectionOffset - Emit the 4-byte offset of Label from the start of
418     /// its section.  This can be done with a special directive if the target
419     /// supports it (e.g. cygwin) or by emitting it as an offset from a label at
420     /// the start of the section.
421     ///
422     /// SectionLabel is a temporary label emitted at the start of the section
423     /// that Label lives in.
424     void EmitSectionOffset(const MCSymbol *Label,
425                            const MCSymbol *SectionLabel) const;
426
427     /// getISAEncoding - Get the value for DW_AT_APPLE_isa. Zero if no isa
428     /// encoding specified.
429     virtual unsigned getISAEncoding() { return 0; }
430
431     /// EmitDwarfRegOp - Emit dwarf register operation.
432     virtual void EmitDwarfRegOp(const MachineLocation &MLoc,
433                                 bool Indirect) const;
434
435     //===------------------------------------------------------------------===//
436     // Dwarf Lowering Routines
437     //===------------------------------------------------------------------===//
438
439     /// \brief Emit frame instruction to describe the layout of the frame.
440     void emitCFIInstruction(const MCCFIInstruction &Inst) const;
441
442     //===------------------------------------------------------------------===//
443     // Inline Asm Support
444     //===------------------------------------------------------------------===//
445   public:
446     // These are hooks that targets can override to implement inline asm
447     // support.  These should probably be moved out of AsmPrinter someday.
448
449     /// PrintSpecial - Print information related to the specified machine instr
450     /// that is independent of the operand, and may be independent of the instr
451     /// itself.  This can be useful for portably encoding the comment character
452     /// or other bits of target-specific knowledge into the asmstrings.  The
453     /// syntax used is ${:comment}.  Targets can override this to add support
454     /// for their own strange codes.
455     virtual void PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
456                               const char *Code) const;
457
458     /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
459     /// instruction, using the specified assembler variant.  Targets should
460     /// override this to format as appropriate.  This method can return true if
461     /// the operand is erroneous.
462     virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
463                                  unsigned AsmVariant, const char *ExtraCode,
464                                  raw_ostream &OS);
465
466     /// PrintAsmMemoryOperand - Print the specified operand of MI, an INLINEASM
467     /// instruction, using the specified assembler variant as an address.
468     /// Targets should override this to format as appropriate.  This method can
469     /// return true if the operand is erroneous.
470     virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
471                                        unsigned AsmVariant,
472                                        const char *ExtraCode, raw_ostream &OS);
473
474     /// Let the target do anything it needs to do after emitting inlineasm.
475     /// This callback can be used restore the original mode in case the
476     /// inlineasm contains directives to switch modes.
477     /// \p StartInfo - the original subtarget info before inline asm
478     /// \p EndInfo   - the final subtarget info after parsing the inline asm,
479     ///                or NULL if the value is unknown.
480     virtual void emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
481                                   const MCSubtargetInfo *EndInfo) const;
482
483   private:
484     /// Private state for PrintSpecial()
485     // Assign a unique ID to this machine instruction.
486     mutable const MachineInstr *LastMI;
487     mutable unsigned LastFn;
488     mutable unsigned Counter;
489     mutable unsigned SetCounter;
490
491     /// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
492     void EmitInlineAsm(StringRef Str, const MDNode *LocMDNode = 0,
493                        InlineAsm::AsmDialect AsmDialect =
494                            InlineAsm::AD_ATT) const;
495
496     /// EmitInlineAsm - This method formats and emits the specified machine
497     /// instruction that is an inline asm.
498     void EmitInlineAsm(const MachineInstr *MI) const;
499
500     //===------------------------------------------------------------------===//
501     // Internal Implementation Details
502     //===------------------------------------------------------------------===//
503
504     /// EmitVisibility - This emits visibility information about symbol, if
505     /// this is suported by the target.
506     void EmitVisibility(MCSymbol *Sym, unsigned Visibility,
507                         bool IsDefinition = true) const;
508
509     void EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const;
510
511     void EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
512                             const MachineBasicBlock *MBB, unsigned uid) const;
513     void EmitLLVMUsedList(const ConstantArray *InitList);
514     /// Emit llvm.ident metadata in an '.ident' directive.
515     void EmitModuleIdents(Module &M);
516     void EmitXXStructorList(const Constant *List, bool isCtor);
517     GCMetadataPrinter *GetOrCreateGCPrinter(GCStrategy *C);
518   };
519 }
520
521 #endif