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