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