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