1 //===- llvm/CodeGen/AsmPrinter.h - AsmPrinter Framework ---------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_CODEGEN_ASMPRINTER_H
17 #define LLVM_CODEGEN_ASMPRINTER_H
19 #include "llvm/ADT/MapVector.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/CodeGen/DwarfStringPoolEntry.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/IR/InlineAsm.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/SourceMgr.h"
36 class AsmPrinterHandler;
45 class GCMetadataPrinter;
46 class GlobalIndirectSymbol;
51 class MachineBasicBlock;
52 class MachineConstantPoolValue;
53 class MachineFunction;
55 class MachineJumpTableInfo;
56 class MachineLoopInfo;
57 class MachineModuleInfo;
58 class MachineOptimizationRemarkEmitter;
60 class MCCFIInstruction;
66 class MCSubtargetInfo;
68 class MCTargetOptions;
72 class TargetLoweringObjectFile;
75 /// This class is intended to be used as a driving class for all asm writers.
76 class AsmPrinter : public MachineFunctionPass {
78 /// Target machine description.
82 /// Target Asm Printer information.
86 /// This is the context for the output file that we are streaming. This owns
87 /// all of the global MC-related objects for the generated translation unit.
88 MCContext &OutContext;
90 /// This is the MCStreamer object for the file we are generating. This
91 /// contains the transient state for the current translation unit that we are
92 /// generating (such as the current section etc).
93 std::unique_ptr<MCStreamer> OutStreamer;
95 /// The current machine function.
96 const MachineFunction *MF = nullptr;
98 /// This is a pointer to the current MachineModuleInfo.
99 MachineModuleInfo *MMI = nullptr;
101 /// Optimization remark emitter.
102 MachineOptimizationRemarkEmitter *ORE;
104 /// The symbol for the current function. This is recalculated at the beginning
105 /// of each call to runOnMachineFunction().
107 MCSymbol *CurrentFnSym = nullptr;
109 /// The symbol used to represent the start of the current function for the
110 /// purpose of calculating its size (e.g. using the .size directive). By
111 /// default, this is equal to CurrentFnSym.
112 MCSymbol *CurrentFnSymForSize = nullptr;
114 /// Map global GOT equivalent MCSymbols to GlobalVariables and keep track of
115 /// its number of uses by other globals.
116 using GOTEquivUsePair = std::pair<const GlobalVariable *, unsigned>;
117 MapVector<const MCSymbol *, GOTEquivUsePair> GlobalGOTEquivs;
119 /// Enable print [latency:throughput] in output
120 bool EnablePrintSchedInfo = false;
123 MCSymbol *CurrentFnBegin = nullptr;
124 MCSymbol *CurrentFnEnd = nullptr;
125 MCSymbol *CurExceptionSym = nullptr;
127 // The garbage collection metadata printer table.
128 void *GCMetadataPrinters = nullptr; // Really a DenseMap.
130 /// Emit comments in assembly output if this is true.
135 /// If VerboseAsm is set, a pointer to the loop info for this function.
136 MachineLoopInfo *LI = nullptr;
139 AsmPrinterHandler *Handler;
140 const char *TimerName;
141 const char *TimerDescription;
142 const char *TimerGroupName;
143 const char *TimerGroupDescription;
145 HandlerInfo(AsmPrinterHandler *Handler, const char *TimerName,
146 const char *TimerDescription, const char *TimerGroupName,
147 const char *TimerGroupDescription)
148 : Handler(Handler), TimerName(TimerName),
149 TimerDescription(TimerDescription), TimerGroupName(TimerGroupName),
150 TimerGroupDescription(TimerGroupDescription) {}
152 /// A vector of all debug/EH info emitters we should use. This vector
153 /// maintains ownership of the emitters.
154 SmallVector<HandlerInfo, 1> Handlers;
157 struct SrcMgrDiagInfo {
159 std::vector<const MDNode *> LocInfos;
160 LLVMContext::InlineAsmDiagHandlerTy DiagHandler;
165 /// Structure for generating diagnostics for inline assembly. Only initialised
167 mutable std::unique_ptr<SrcMgrDiagInfo> DiagInfo;
169 /// If the target supports dwarf debug info, this pointer is non-null.
170 DwarfDebug *DD = nullptr;
172 /// If the current module uses dwarf CFI annotations strictly for debugging.
173 bool isCFIMoveForDebugging = false;
176 explicit AsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer);
179 ~AsmPrinter() override;
181 DwarfDebug *getDwarfDebug() { return DD; }
182 DwarfDebug *getDwarfDebug() const { return DD; }
184 uint16_t getDwarfVersion() const;
185 void setDwarfVersion(uint16_t Version);
187 bool isPositionIndependent() const;
189 /// Return true if assembly output should contain comments.
191 bool isVerbose() const { return VerboseAsm; }
193 /// Return a unique ID for the current function.
195 unsigned getFunctionNumber() const;
197 MCSymbol *getFunctionBegin() const { return CurrentFnBegin; }
198 MCSymbol *getFunctionEnd() const { return CurrentFnEnd; }
199 MCSymbol *getCurExceptionSym();
201 /// Return information about object file lowering.
202 const TargetLoweringObjectFile &getObjFileLowering() const;
204 /// Return information about data layout.
205 const DataLayout &getDataLayout() const;
207 /// Return the pointer size from the TargetMachine
208 unsigned getPointerSize() const;
210 /// Return information about subtarget.
211 const MCSubtargetInfo &getSubtargetInfo() const;
213 void EmitToStreamer(MCStreamer &S, const MCInst &Inst);
215 /// Return the current section we are emitting to.
216 const MCSection *getCurrentSection() const;
218 void getNameWithPrefix(SmallVectorImpl<char> &Name,
219 const GlobalValue *GV) const;
221 MCSymbol *getSymbol(const GlobalValue *GV) const;
223 //===------------------------------------------------------------------===//
224 // XRay instrumentation implementation.
225 //===------------------------------------------------------------------===//
227 // This describes the kind of sled we're storing in the XRay table.
228 enum class SledKind : uint8_t {
236 // The table will contain these structs that point to the sled, the function
237 // containing the sled, and what kind of sled (and whether they should always
239 struct XRayFunctionEntry {
240 const MCSymbol *Sled;
241 const MCSymbol *Function;
243 bool AlwaysInstrument;
244 const class Function *Fn;
246 void emit(int, MCStreamer *, const MCSymbol *) const;
249 // All the sleds to be emitted.
250 SmallVector<XRayFunctionEntry, 4> Sleds;
252 // Helper function to record a given XRay sled.
253 void recordSled(MCSymbol *Sled, const MachineInstr &MI, SledKind Kind);
255 /// Emit a table with all XRay instrumentation points.
256 void emitXRayTable();
258 //===------------------------------------------------------------------===//
259 // MachineFunctionPass Implementation.
260 //===------------------------------------------------------------------===//
262 /// Record analysis usage.
264 void getAnalysisUsage(AnalysisUsage &AU) const override;
266 /// Set up the AsmPrinter when we are working on a new module. If your pass
267 /// overrides this, it must make sure to explicitly call this implementation.
268 bool doInitialization(Module &M) override;
270 /// Shut down the asmprinter. If you override this in your pass, you must make
271 /// sure to call it explicitly.
272 bool doFinalization(Module &M) override;
274 /// Emit the specified function out to the OutStreamer.
275 bool runOnMachineFunction(MachineFunction &MF) override {
276 SetupMachineFunction(MF);
281 //===------------------------------------------------------------------===//
282 // Coarse grained IR lowering routines.
283 //===------------------------------------------------------------------===//
285 /// This should be called when a new MachineFunction is being processed from
286 /// runOnMachineFunction.
287 void SetupMachineFunction(MachineFunction &MF);
289 /// This method emits the body and trailer for a function.
290 void EmitFunctionBody();
292 void emitCFIInstruction(const MachineInstr &MI);
294 void emitFrameAlloc(const MachineInstr &MI);
296 enum CFIMoveType { CFI_M_None, CFI_M_EH, CFI_M_Debug };
297 CFIMoveType needsCFIMoves();
299 /// Returns false if needsCFIMoves() == CFI_M_EH for any function
301 bool needsOnlyDebugCFIMoves() const { return isCFIMoveForDebugging; }
303 bool needsSEHMoves();
305 /// Print to the current output stream assembly representations of the
306 /// constants in the constant pool MCP. This is used to print out constants
307 /// which have been "spilled to memory" by the code generator.
309 virtual void EmitConstantPool();
311 /// Print assembly representations of the jump tables used by the current
312 /// function to the current output stream.
314 virtual void EmitJumpTableInfo();
316 /// Emit the specified global variable to the .s file.
317 virtual void EmitGlobalVariable(const GlobalVariable *GV);
319 /// Check to see if the specified global is a special global used by LLVM. If
320 /// so, emit it and return true, otherwise do nothing and return false.
321 bool EmitSpecialLLVMGlobal(const GlobalVariable *GV);
323 /// Emit an alignment directive to the specified power of two boundary. For
324 /// example, if you pass in 3 here, you will get an 8 byte alignment. If a
325 /// global value is specified, and if that global has an explicit alignment
326 /// requested, it will override the alignment request if required for
329 void EmitAlignment(unsigned NumBits, const GlobalObject *GO = nullptr) const;
331 /// Lower the specified LLVM Constant to an MCExpr.
332 virtual const MCExpr *lowerConstant(const Constant *CV);
334 /// \brief Print a general LLVM constant to the .s file.
335 void EmitGlobalConstant(const DataLayout &DL, const Constant *CV);
337 /// \brief Unnamed constant global variables solely contaning a pointer to
338 /// another globals variable act like a global variable "proxy", or GOT
339 /// equivalents, i.e., it's only used to hold the address of the latter. One
340 /// optimization is to replace accesses to these proxies by using the GOT
341 /// entry for the final global instead. Hence, we select GOT equivalent
342 /// candidates among all the module global variables, avoid emitting them
343 /// unnecessarily and finally replace references to them by pc relative
344 /// accesses to GOT entries.
345 void computeGlobalGOTEquivs(Module &M);
347 /// \brief Constant expressions using GOT equivalent globals may not be
348 /// eligible for PC relative GOT entry conversion, in such cases we need to
349 /// emit the proxies we previously omitted in EmitGlobalVariable.
350 void emitGlobalGOTEquivs();
352 //===------------------------------------------------------------------===//
354 //===------------------------------------------------------------------===//
356 // Targets can, or in the case of EmitInstruction, must implement these to
359 /// This virtual method can be overridden by targets that want to emit
360 /// something at the start of their file.
361 virtual void EmitStartOfAsmFile(Module &) {}
363 /// This virtual method can be overridden by targets that want to emit
364 /// something at the end of their file.
365 virtual void EmitEndOfAsmFile(Module &) {}
367 /// Targets can override this to emit stuff before the first basic block in
369 virtual void EmitFunctionBodyStart() {}
371 /// Targets can override this to emit stuff after the last basic block in the
373 virtual void EmitFunctionBodyEnd() {}
375 /// Targets can override this to emit stuff at the start of a basic block.
376 /// By default, this method prints the label for the specified
377 /// MachineBasicBlock, an alignment (if present) and a comment describing it
379 virtual void EmitBasicBlockStart(const MachineBasicBlock &MBB) const;
381 /// Targets can override this to emit stuff at the end of a basic block.
382 virtual void EmitBasicBlockEnd(const MachineBasicBlock &MBB) {}
384 /// Targets should implement this to emit instructions.
385 virtual void EmitInstruction(const MachineInstr *) {
386 llvm_unreachable("EmitInstruction not implemented");
389 /// Return the symbol for the specified constant pool entry.
390 virtual MCSymbol *GetCPISymbol(unsigned CPID) const;
392 virtual void EmitFunctionEntryLabel();
394 virtual void EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV);
396 /// Targets can override this to change how global constants that are part of
397 /// a C++ static/global constructor list are emitted.
398 virtual void EmitXXStructor(const DataLayout &DL, const Constant *CV) {
399 EmitGlobalConstant(DL, CV);
402 /// Return true if the basic block has exactly one predecessor and the control
403 /// transfer mechanism between the predecessor and this block is a
406 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const;
408 /// Targets can override this to customize the output of IMPLICIT_DEF
409 /// instructions in verbose mode.
410 virtual void emitImplicitDef(const MachineInstr *MI) const;
412 //===------------------------------------------------------------------===//
413 // Symbol Lowering Routines.
414 //===------------------------------------------------------------------===//
416 MCSymbol *createTempSymbol(const Twine &Name) const;
418 /// Return the MCSymbol for a private symbol with global value name as its
419 /// base, with the specified suffix.
420 MCSymbol *getSymbolWithGlobalValueBase(const GlobalValue *GV,
421 StringRef Suffix) const;
423 /// Return the MCSymbol for the specified ExternalSymbol.
424 MCSymbol *GetExternalSymbolSymbol(StringRef Sym) const;
426 /// Return the symbol for the specified jump table entry.
427 MCSymbol *GetJTISymbol(unsigned JTID, bool isLinkerPrivate = false) const;
429 /// Return the symbol for the specified jump table .set
430 /// FIXME: privatize to AsmPrinter.
431 MCSymbol *GetJTSetSymbol(unsigned UID, unsigned MBBID) const;
433 /// Return the MCSymbol used to satisfy BlockAddress uses of the specified
435 MCSymbol *GetBlockAddressSymbol(const BlockAddress *BA) const;
436 MCSymbol *GetBlockAddressSymbol(const BasicBlock *BB) const;
438 //===------------------------------------------------------------------===//
439 // Emission Helper Routines.
440 //===------------------------------------------------------------------===//
442 /// This is just convenient handler for printing offsets.
443 void printOffset(int64_t Offset, raw_ostream &OS) const;
445 /// Emit a byte directive and value.
447 void EmitInt8(int Value) const;
449 /// Emit a short directive and value.
451 void EmitInt16(int Value) const;
453 /// Emit a long directive and value.
455 void EmitInt32(int Value) const;
457 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
458 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
459 /// .set if it is available.
460 void EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
461 unsigned Size) const;
463 /// Emit something like ".long Label+Offset" where the size in bytes of the
464 /// directive is specified by Size and Label specifies the label. This
465 /// implicitly uses .set if it is available.
466 void EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
467 unsigned Size, bool IsSectionRelative = false) const;
469 /// Emit something like ".long Label" where the size in bytes of the directive
470 /// is specified by Size and Label specifies the label.
471 void EmitLabelReference(const MCSymbol *Label, unsigned Size,
472 bool IsSectionRelative = false) const {
473 EmitLabelPlusOffset(Label, 0, Size, IsSectionRelative);
476 //===------------------------------------------------------------------===//
477 // Dwarf Emission Helper Routines
478 //===------------------------------------------------------------------===//
480 /// Emit the specified signed leb128 value.
481 void EmitSLEB128(int64_t Value, const char *Desc = nullptr) const;
483 /// Emit the specified unsigned leb128 value.
484 void EmitULEB128(uint64_t Value, const char *Desc = nullptr,
485 unsigned PadTo = 0) const;
487 /// Emit a .byte 42 directive that corresponds to an encoding. If verbose
488 /// assembly output is enabled, we output comments describing the encoding.
489 /// Desc is a string saying what the encoding is specifying (e.g. "LSDA").
490 void EmitEncodingByte(unsigned Val, const char *Desc = nullptr) const;
492 /// Return the size of the encoding in bytes.
493 unsigned GetSizeOfEncodedValue(unsigned Encoding) const;
495 /// Emit reference to a ttype global with a specified encoding.
496 void EmitTTypeReference(const GlobalValue *GV, unsigned Encoding) const;
498 /// Emit a reference to a symbol for use in dwarf. Different object formats
499 /// represent this in different ways. Some use a relocation others encode
500 /// the label offset in its section.
501 void emitDwarfSymbolReference(const MCSymbol *Label,
502 bool ForceOffset = false) const;
504 /// Emit the 4-byte offset of a string from the start of its section.
506 /// When possible, emit a DwarfStringPool section offset without any
507 /// relocations, and without using the symbol. Otherwise, defers to \a
508 /// emitDwarfSymbolReference().
509 void emitDwarfStringOffset(DwarfStringPoolEntryRef S) const;
511 /// Get the value for DW_AT_APPLE_isa. Zero if no isa encoding specified.
512 virtual unsigned getISAEncoding() { return 0; }
514 /// Emit the directive and value for debug thread local expression
516 /// \p Value - The value to emit.
517 /// \p Size - The size of the integer (in bytes) to emit.
518 virtual void EmitDebugThreadLocal(const MCExpr *Value, unsigned Size) const;
520 //===------------------------------------------------------------------===//
521 // Dwarf Lowering Routines
522 //===------------------------------------------------------------------===//
524 /// \brief Emit frame instruction to describe the layout of the frame.
525 void emitCFIInstruction(const MCCFIInstruction &Inst) const;
527 /// \brief Emit Dwarf abbreviation table.
528 template <typename T> void emitDwarfAbbrevs(const T &Abbrevs) const {
529 // For each abbreviation.
530 for (const auto &Abbrev : Abbrevs)
531 emitDwarfAbbrev(*Abbrev);
533 // Mark end of abbreviations.
534 EmitULEB128(0, "EOM(3)");
537 void emitDwarfAbbrev(const DIEAbbrev &Abbrev) const;
539 /// \brief Recursively emit Dwarf DIE tree.
540 void emitDwarfDIE(const DIE &Die) const;
542 //===------------------------------------------------------------------===//
543 // Inline Asm Support
544 //===------------------------------------------------------------------===//
546 // These are hooks that targets can override to implement inline asm
547 // support. These should probably be moved out of AsmPrinter someday.
549 /// Print information related to the specified machine instr that is
550 /// independent of the operand, and may be independent of the instr itself.
551 /// This can be useful for portably encoding the comment character or other
552 /// bits of target-specific knowledge into the asmstrings. The syntax used is
553 /// ${:comment}. Targets can override this to add support for their own
555 virtual void PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
556 const char *Code) const;
558 /// Print the specified operand of MI, an INLINEASM instruction, using the
559 /// specified assembler variant. Targets should override this to format as
560 /// appropriate. This method can return true if the operand is erroneous.
561 virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
562 unsigned AsmVariant, const char *ExtraCode,
565 /// Print the specified operand of MI, an INLINEASM instruction, using the
566 /// specified assembler variant as an address. Targets should override this to
567 /// format as appropriate. This method can return true if the operand is
569 virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
570 unsigned AsmVariant, const char *ExtraCode,
573 /// Let the target do anything it needs to do before emitting inlineasm.
574 /// \p StartInfo - the subtarget info before parsing inline asm
575 virtual void emitInlineAsmStart() const;
577 /// Let the target do anything it needs to do after emitting inlineasm.
578 /// This callback can be used restore the original mode in case the
579 /// inlineasm contains directives to switch modes.
580 /// \p StartInfo - the original subtarget info before inline asm
581 /// \p EndInfo - the final subtarget info after parsing the inline asm,
582 /// or NULL if the value is unknown.
583 virtual void emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
584 const MCSubtargetInfo *EndInfo) const;
587 /// Private state for PrintSpecial()
588 // Assign a unique ID to this machine instruction.
589 mutable const MachineInstr *LastMI = nullptr;
590 mutable unsigned LastFn = 0;
591 mutable unsigned Counter = ~0U;
593 /// This method emits the header for the current function.
594 virtual void EmitFunctionHeader();
596 /// Emit a blob of inline asm to the output streamer.
598 EmitInlineAsm(StringRef Str, const MCSubtargetInfo &STI,
599 const MCTargetOptions &MCOptions,
600 const MDNode *LocMDNode = nullptr,
601 InlineAsm::AsmDialect AsmDialect = InlineAsm::AD_ATT) const;
603 /// This method formats and emits the specified machine instruction that is an
605 void EmitInlineAsm(const MachineInstr *MI) const;
607 //===------------------------------------------------------------------===//
608 // Internal Implementation Details
609 //===------------------------------------------------------------------===//
611 /// This emits visibility information about symbol, if this is supported by
613 void EmitVisibility(MCSymbol *Sym, unsigned Visibility,
614 bool IsDefinition = true) const;
616 void EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const;
618 void EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
619 const MachineBasicBlock *MBB, unsigned uid) const;
620 void EmitLLVMUsedList(const ConstantArray *InitList);
621 /// Emit llvm.ident metadata in an '.ident' directive.
622 void EmitModuleIdents(Module &M);
623 void EmitXXStructorList(const DataLayout &DL, const Constant *List,
625 GCMetadataPrinter *GetOrCreateGCPrinter(GCStrategy &C);
626 /// Emit GlobalAlias or GlobalIFunc.
627 void emitGlobalIndirectSymbol(Module &M,
628 const GlobalIndirectSymbol& GIS);
631 } // end namespace llvm
633 #endif // LLVM_CODEGEN_ASMPRINTER_H