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