AsmPrinter.h 21 KB

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