1 //===- llvm/CodeGen/AsmPrinter.h - AsmPrinter Framework ---------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains a class to be used as the base class for target specific 10 // asm writers. This class primarily handles common functionality used by 11 // all asm writers. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #ifndef LLVM_CODEGEN_ASMPRINTER_H 16 #define LLVM_CODEGEN_ASMPRINTER_H 17 18 #include "llvm/ADT/DenseMap.h" 19 #include "llvm/ADT/MapVector.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/BinaryFormat/Dwarf.h" 22 #include "llvm/CodeGen/AsmPrinterHandler.h" 23 #include "llvm/CodeGen/DwarfStringPoolEntry.h" 24 #include "llvm/CodeGen/MachineFunctionPass.h" 25 #include "llvm/CodeGen/StackMaps.h" 26 #include "llvm/DebugInfo/CodeView/CodeView.h" 27 #include "llvm/IR/InlineAsm.h" 28 #include "llvm/Support/ErrorHandling.h" 29 #include <cstdint> 30 #include <memory> 31 #include <utility> 32 #include <vector> 33 34 namespace llvm { 35 36 class AddrLabelMap; 37 class BasicBlock; 38 class BlockAddress; 39 class Constant; 40 class ConstantArray; 41 class DataLayout; 42 class DIE; 43 class DIEAbbrev; 44 class DwarfDebug; 45 class GCMetadataPrinter; 46 class GCStrategy; 47 class GlobalAlias; 48 class GlobalObject; 49 class GlobalValue; 50 class GlobalVariable; 51 class MachineBasicBlock; 52 class MachineConstantPoolValue; 53 class MachineDominatorTree; 54 class MachineFunction; 55 class MachineInstr; 56 class MachineJumpTableInfo; 57 class MachineLoopInfo; 58 class MachineModuleInfo; 59 class MachineOptimizationRemarkEmitter; 60 class MCAsmInfo; 61 class MCCFIInstruction; 62 class MCContext; 63 class MCExpr; 64 class MCInst; 65 class MCSection; 66 class MCStreamer; 67 class MCSubtargetInfo; 68 class MCSymbol; 69 class MCTargetOptions; 70 class MDNode; 71 class Module; 72 class PseudoProbeHandler; 73 class raw_ostream; 74 class StringRef; 75 class TargetLoweringObjectFile; 76 class TargetMachine; 77 class Twine; 78 79 namespace remarks { 80 class RemarkStreamer; 81 } 82 83 /// This class is intended to be used as a driving class for all asm writers. 84 class AsmPrinter : public MachineFunctionPass { 85 public: 86 /// Target machine description. 87 TargetMachine &TM; 88 89 /// Target Asm Printer information. 90 const MCAsmInfo *MAI = nullptr; 91 92 /// This is the context for the output file that we are streaming. This owns 93 /// all of the global MC-related objects for the generated translation unit. 94 MCContext &OutContext; 95 96 /// This is the MCStreamer object for the file we are generating. This 97 /// contains the transient state for the current translation unit that we are 98 /// generating (such as the current section etc). 99 std::unique_ptr<MCStreamer> OutStreamer; 100 101 /// The current machine function. 102 MachineFunction *MF = nullptr; 103 104 /// This is a pointer to the current MachineModuleInfo. 105 MachineModuleInfo *MMI = nullptr; 106 107 /// This is a pointer to the current MachineDominatorTree. 108 MachineDominatorTree *MDT = nullptr; 109 110 /// This is a pointer to the current MachineLoopInfo. 111 MachineLoopInfo *MLI = nullptr; 112 113 /// Optimization remark emitter. 114 MachineOptimizationRemarkEmitter *ORE = nullptr; 115 116 /// The symbol for the entry in __patchable_function_entires. 117 MCSymbol *CurrentPatchableFunctionEntrySym = nullptr; 118 119 /// The symbol for the current function. This is recalculated at the beginning 120 /// of each call to runOnMachineFunction(). 121 MCSymbol *CurrentFnSym = nullptr; 122 123 /// The symbol for the current function descriptor on AIX. This is created 124 /// at the beginning of each call to SetupMachineFunction(). 125 MCSymbol *CurrentFnDescSym = nullptr; 126 127 /// The symbol used to represent the start of the current function for the 128 /// purpose of calculating its size (e.g. using the .size directive). By 129 /// default, this is equal to CurrentFnSym. 130 MCSymbol *CurrentFnSymForSize = nullptr; 131 132 /// Map a basic block section ID to the begin and end symbols of that section 133 /// which determine the section's range. 134 struct MBBSectionRange { 135 MCSymbol *BeginLabel, *EndLabel; 136 }; 137 138 MapVector<unsigned, MBBSectionRange> MBBSectionRanges; 139 140 /// Map global GOT equivalent MCSymbols to GlobalVariables and keep track of 141 /// its number of uses by other globals. 142 using GOTEquivUsePair = std::pair<const GlobalVariable *, unsigned>; 143 MapVector<const MCSymbol *, GOTEquivUsePair> GlobalGOTEquivs; 144 145 /// struct HandlerInfo and Handlers permit users or target extended 146 /// AsmPrinter to add their own handlers. 147 struct HandlerInfo { 148 std::unique_ptr<AsmPrinterHandler> Handler; 149 StringRef TimerName; 150 StringRef TimerDescription; 151 StringRef TimerGroupName; 152 StringRef TimerGroupDescription; 153 HandlerInfoHandlerInfo154 HandlerInfo(std::unique_ptr<AsmPrinterHandler> Handler, StringRef TimerName, 155 StringRef TimerDescription, StringRef TimerGroupName, 156 StringRef TimerGroupDescription) 157 : Handler(std::move(Handler)), TimerName(TimerName), 158 TimerDescription(TimerDescription), TimerGroupName(TimerGroupName), 159 TimerGroupDescription(TimerGroupDescription) {} 160 }; 161 162 // Flags representing which CFI section is required for a function/module. 163 enum class CFISection : unsigned { 164 None = 0, ///< Do not emit either .eh_frame or .debug_frame 165 EH = 1, ///< Emit .eh_frame 166 Debug = 2 ///< Emit .debug_frame 167 }; 168 169 private: 170 MCSymbol *CurrentFnEnd = nullptr; 171 172 /// Map a basic block section ID to the exception symbol associated with that 173 /// section. Map entries are assigned and looked up via 174 /// AsmPrinter::getMBBExceptionSym. 175 DenseMap<unsigned, MCSymbol *> MBBSectionExceptionSyms; 176 177 // The symbol used to represent the start of the current BB section of the 178 // function. This is used to calculate the size of the BB section. 179 MCSymbol *CurrentSectionBeginSym = nullptr; 180 181 /// This map keeps track of which symbol is being used for the specified basic 182 /// block's address of label. 183 std::unique_ptr<AddrLabelMap> AddrLabelSymbols; 184 185 /// The garbage collection metadata printer table. 186 DenseMap<GCStrategy *, std::unique_ptr<GCMetadataPrinter>> GCMetadataPrinters; 187 188 /// Emit comments in assembly output if this is true. 189 bool VerboseAsm; 190 191 /// Output stream for the stack usage file (i.e., .su file). 192 std::unique_ptr<raw_fd_ostream> StackUsageStream; 193 194 /// List of symbols to be inserted into PC sections. 195 DenseMap<const MDNode *, SmallVector<const MCSymbol *>> PCSectionsSymbols; 196 197 static char ID; 198 199 protected: 200 MCSymbol *CurrentFnBegin = nullptr; 201 202 /// For dso_local functions, the current $local alias for the function. 203 MCSymbol *CurrentFnBeginLocal = nullptr; 204 205 /// A vector of all debug/EH info emitters we should use. This vector 206 /// maintains ownership of the emitters. 207 std::vector<HandlerInfo> Handlers; 208 size_t NumUserHandlers = 0; 209 210 StackMaps SM; 211 212 private: 213 /// If generated on the fly this own the instance. 214 std::unique_ptr<MachineDominatorTree> OwnedMDT; 215 216 /// If generated on the fly this own the instance. 217 std::unique_ptr<MachineLoopInfo> OwnedMLI; 218 219 /// If the target supports dwarf debug info, this pointer is non-null. 220 DwarfDebug *DD = nullptr; 221 222 /// A handler that supports pseudo probe emission with embedded inline 223 /// context. 224 PseudoProbeHandler *PP = nullptr; 225 226 /// CFISection type the module needs i.e. either .eh_frame or .debug_frame. 227 CFISection ModuleCFISection = CFISection::None; 228 229 /// True if the module contains split-stack functions. This is used to 230 /// emit .note.GNU-split-stack section as required by the linker for 231 /// special handling split-stack function calling no-split-stack function. 232 bool HasSplitStack = false; 233 234 /// True if the module contains no-split-stack functions. This is used to emit 235 /// .note.GNU-no-split-stack section when it also contains functions without a 236 /// split stack prologue. 237 bool HasNoSplitStack = false; 238 239 /// Raw FDOstream for outputting machine basic block frequncies if the 240 /// --mbb-profile-dump flag is set for downstream cost modelling applications 241 std::unique_ptr<raw_fd_ostream> MBBProfileDumpFileOutput; 242 243 protected: 244 explicit AsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer); 245 246 public: 247 ~AsmPrinter() override; 248 getDwarfDebug()249 DwarfDebug *getDwarfDebug() { return DD; } getDwarfDebug()250 DwarfDebug *getDwarfDebug() const { return DD; } 251 252 uint16_t getDwarfVersion() const; 253 void setDwarfVersion(uint16_t Version); 254 255 bool isDwarf64() const; 256 257 /// Returns 4 for DWARF32 and 8 for DWARF64. 258 unsigned int getDwarfOffsetByteSize() const; 259 260 /// Returns 4 for DWARF32 and 12 for DWARF64. 261 unsigned int getUnitLengthFieldByteSize() const; 262 263 /// Returns information about the byte size of DW_FORM values. 264 dwarf::FormParams getDwarfFormParams() const; 265 266 bool isPositionIndependent() const; 267 268 /// Return true if assembly output should contain comments. isVerbose()269 bool isVerbose() const { return VerboseAsm; } 270 271 /// Return a unique ID for the current function. 272 unsigned getFunctionNumber() const; 273 274 /// Return symbol for the function pseudo stack if the stack frame is not a 275 /// register based. getFunctionFrameSymbol()276 virtual const MCSymbol *getFunctionFrameSymbol() const { return nullptr; } 277 getFunctionBegin()278 MCSymbol *getFunctionBegin() const { return CurrentFnBegin; } getFunctionEnd()279 MCSymbol *getFunctionEnd() const { return CurrentFnEnd; } 280 281 // Return the exception symbol associated with the MBB section containing a 282 // given basic block. 283 MCSymbol *getMBBExceptionSym(const MachineBasicBlock &MBB); 284 285 /// Return the symbol to be used for the specified basic block when its 286 /// address is taken. This cannot be its normal LBB label because the block 287 /// may be accessed outside its containing function. getAddrLabelSymbol(const BasicBlock * BB)288 MCSymbol *getAddrLabelSymbol(const BasicBlock *BB) { 289 return getAddrLabelSymbolToEmit(BB).front(); 290 } 291 292 /// Return the symbol to be used for the specified basic block when its 293 /// address is taken. If other blocks were RAUW'd to this one, we may have 294 /// to emit them as well, return the whole set. 295 ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(const BasicBlock *BB); 296 297 /// If the specified function has had any references to address-taken blocks 298 /// generated, but the block got deleted, return the symbol now so we can 299 /// emit it. This prevents emitting a reference to a symbol that has no 300 /// definition. 301 void takeDeletedSymbolsForFunction(const Function *F, 302 std::vector<MCSymbol *> &Result); 303 304 /// Return information about object file lowering. 305 const TargetLoweringObjectFile &getObjFileLowering() const; 306 307 /// Return information about data layout. 308 const DataLayout &getDataLayout() const; 309 310 /// Return the pointer size from the TargetMachine 311 unsigned getPointerSize() const; 312 313 /// Return information about subtarget. 314 const MCSubtargetInfo &getSubtargetInfo() const; 315 316 void EmitToStreamer(MCStreamer &S, const MCInst &Inst); 317 318 /// Emits inital debug location directive. 319 void emitInitialRawDwarfLocDirective(const MachineFunction &MF); 320 321 /// Return the current section we are emitting to. 322 const MCSection *getCurrentSection() const; 323 324 void getNameWithPrefix(SmallVectorImpl<char> &Name, 325 const GlobalValue *GV) const; 326 327 MCSymbol *getSymbol(const GlobalValue *GV) const; 328 329 /// Similar to getSymbol() but preferred for references. On ELF, this uses a 330 /// local symbol if a reference to GV is guaranteed to be resolved to the 331 /// definition in the same module. 332 MCSymbol *getSymbolPreferLocal(const GlobalValue &GV) const; 333 doesDwarfUseRelocationsAcrossSections()334 bool doesDwarfUseRelocationsAcrossSections() const { 335 return DwarfUsesRelocationsAcrossSections; 336 } 337 setDwarfUsesRelocationsAcrossSections(bool Enable)338 void setDwarfUsesRelocationsAcrossSections(bool Enable) { 339 DwarfUsesRelocationsAcrossSections = Enable; 340 } 341 342 //===------------------------------------------------------------------===// 343 // XRay instrumentation implementation. 344 //===------------------------------------------------------------------===// 345 public: 346 // This describes the kind of sled we're storing in the XRay table. 347 enum class SledKind : uint8_t { 348 FUNCTION_ENTER = 0, 349 FUNCTION_EXIT = 1, 350 TAIL_CALL = 2, 351 LOG_ARGS_ENTER = 3, 352 CUSTOM_EVENT = 4, 353 TYPED_EVENT = 5, 354 }; 355 356 // The table will contain these structs that point to the sled, the function 357 // containing the sled, and what kind of sled (and whether they should always 358 // be instrumented). We also use a version identifier that the runtime can use 359 // to decide what to do with the sled, depending on the version of the sled. 360 struct XRayFunctionEntry { 361 const MCSymbol *Sled; 362 const MCSymbol *Function; 363 SledKind Kind; 364 bool AlwaysInstrument; 365 const class Function *Fn; 366 uint8_t Version; 367 368 void emit(int, MCStreamer *) const; 369 }; 370 371 // All the sleds to be emitted. 372 SmallVector<XRayFunctionEntry, 4> Sleds; 373 374 // Helper function to record a given XRay sled. 375 void recordSled(MCSymbol *Sled, const MachineInstr &MI, SledKind Kind, 376 uint8_t Version = 0); 377 378 /// Emit a table with all XRay instrumentation points. 379 void emitXRayTable(); 380 381 void emitPatchableFunctionEntries(); 382 383 //===------------------------------------------------------------------===// 384 // MachineFunctionPass Implementation. 385 //===------------------------------------------------------------------===// 386 387 /// Record analysis usage. 388 void getAnalysisUsage(AnalysisUsage &AU) const override; 389 390 /// Set up the AsmPrinter when we are working on a new module. If your pass 391 /// overrides this, it must make sure to explicitly call this implementation. 392 bool doInitialization(Module &M) override; 393 394 /// Shut down the asmprinter. If you override this in your pass, you must make 395 /// sure to call it explicitly. 396 bool doFinalization(Module &M) override; 397 398 /// Emit the specified function out to the OutStreamer. runOnMachineFunction(MachineFunction & MF)399 bool runOnMachineFunction(MachineFunction &MF) override { 400 SetupMachineFunction(MF); 401 emitFunctionBody(); 402 return false; 403 } 404 405 //===------------------------------------------------------------------===// 406 // Coarse grained IR lowering routines. 407 //===------------------------------------------------------------------===// 408 409 /// This should be called when a new MachineFunction is being processed from 410 /// runOnMachineFunction. 411 virtual void SetupMachineFunction(MachineFunction &MF); 412 413 /// This method emits the body and trailer for a function. 414 void emitFunctionBody(); 415 416 void emitCFIInstruction(const MachineInstr &MI); 417 418 void emitFrameAlloc(const MachineInstr &MI); 419 420 void emitStackSizeSection(const MachineFunction &MF); 421 422 void emitStackUsage(const MachineFunction &MF); 423 424 void emitBBAddrMapSection(const MachineFunction &MF); 425 426 void emitKCFITrapEntry(const MachineFunction &MF, const MCSymbol *Symbol); 427 virtual void emitKCFITypeId(const MachineFunction &MF); 428 429 void emitPseudoProbe(const MachineInstr &MI); 430 431 void emitRemarksSection(remarks::RemarkStreamer &RS); 432 433 /// Emits a label as reference for PC sections. 434 void emitPCSectionsLabel(const MachineFunction &MF, const MDNode &MD); 435 436 /// Emits the PC sections collected from instructions. 437 void emitPCSections(const MachineFunction &MF); 438 439 /// Get the CFISection type for a function. 440 CFISection getFunctionCFISectionType(const Function &F) const; 441 442 /// Get the CFISection type for a function. 443 CFISection getFunctionCFISectionType(const MachineFunction &MF) const; 444 445 /// Get the CFISection type for the module. getModuleCFISectionType()446 CFISection getModuleCFISectionType() const { return ModuleCFISection; } 447 448 bool needsSEHMoves(); 449 450 /// Since emitting CFI unwind information is entangled with supporting the 451 /// exceptions, this returns true for platforms which use CFI unwind 452 /// information for other purposes (debugging, sanitizers, ...) when 453 /// `MCAsmInfo::ExceptionsType == ExceptionHandling::None`. 454 bool usesCFIWithoutEH() const; 455 456 /// Print to the current output stream assembly representations of the 457 /// constants in the constant pool MCP. This is used to print out constants 458 /// which have been "spilled to memory" by the code generator. 459 virtual void emitConstantPool(); 460 461 /// Print assembly representations of the jump tables used by the current 462 /// function to the current output stream. 463 virtual void emitJumpTableInfo(); 464 465 /// Emit the specified global variable to the .s file. 466 virtual void emitGlobalVariable(const GlobalVariable *GV); 467 468 /// Check to see if the specified global is a special global used by LLVM. If 469 /// so, emit it and return true, otherwise do nothing and return false. 470 bool emitSpecialLLVMGlobal(const GlobalVariable *GV); 471 472 /// `llvm.global_ctors` and `llvm.global_dtors` are arrays of Structor 473 /// structs. 474 /// 475 /// Priority - init priority 476 /// Func - global initialization or global clean-up function 477 /// ComdatKey - associated data 478 struct Structor { 479 int Priority = 0; 480 Constant *Func = nullptr; 481 GlobalValue *ComdatKey = nullptr; 482 483 Structor() = default; 484 }; 485 486 /// This method gathers an array of Structors and then sorts them out by 487 /// Priority. 488 /// @param List The initializer of `llvm.global_ctors` or `llvm.global_dtors` 489 /// array. 490 /// @param[out] Structors Sorted Structor structs by Priority. 491 void preprocessXXStructorList(const DataLayout &DL, const Constant *List, 492 SmallVector<Structor, 8> &Structors); 493 494 /// This method emits `llvm.global_ctors` or `llvm.global_dtors` list. 495 virtual void emitXXStructorList(const DataLayout &DL, const Constant *List, 496 bool IsCtor); 497 498 /// Emit an alignment directive to the specified power of two boundary. If a 499 /// global value is specified, and if that global has an explicit alignment 500 /// requested, it will override the alignment request if required for 501 /// correctness. 502 void emitAlignment(Align Alignment, const GlobalObject *GV = nullptr, 503 unsigned MaxBytesToEmit = 0) const; 504 505 /// Lower the specified LLVM Constant to an MCExpr. 506 virtual const MCExpr *lowerConstant(const Constant *CV); 507 508 /// Print a general LLVM constant to the .s file. 509 /// On AIX, when an alias refers to a sub-element of a global variable, the 510 /// label of that alias needs to be emitted before the corresponding element. 511 using AliasMapTy = DenseMap<uint64_t, SmallVector<const GlobalAlias *, 1>>; 512 void emitGlobalConstant(const DataLayout &DL, const Constant *CV, 513 AliasMapTy *AliasList = nullptr); 514 515 /// Unnamed constant global variables solely contaning a pointer to 516 /// another globals variable act like a global variable "proxy", or GOT 517 /// equivalents, i.e., it's only used to hold the address of the latter. One 518 /// optimization is to replace accesses to these proxies by using the GOT 519 /// entry for the final global instead. Hence, we select GOT equivalent 520 /// candidates among all the module global variables, avoid emitting them 521 /// unnecessarily and finally replace references to them by pc relative 522 /// accesses to GOT entries. 523 void computeGlobalGOTEquivs(Module &M); 524 525 /// Constant expressions using GOT equivalent globals may not be 526 /// eligible for PC relative GOT entry conversion, in such cases we need to 527 /// emit the proxies we previously omitted in EmitGlobalVariable. 528 void emitGlobalGOTEquivs(); 529 530 /// Emit the stack maps. 531 void emitStackMaps(); 532 533 //===------------------------------------------------------------------===// 534 // Overridable Hooks 535 //===------------------------------------------------------------------===// 536 addAsmPrinterHandler(HandlerInfo Handler)537 void addAsmPrinterHandler(HandlerInfo Handler) { 538 Handlers.insert(Handlers.begin(), std::move(Handler)); 539 NumUserHandlers++; 540 } 541 542 // Targets can, or in the case of EmitInstruction, must implement these to 543 // customize output. 544 545 /// This virtual method can be overridden by targets that want to emit 546 /// something at the start of their file. emitStartOfAsmFile(Module &)547 virtual void emitStartOfAsmFile(Module &) {} 548 549 /// This virtual method can be overridden by targets that want to emit 550 /// something at the end of their file. emitEndOfAsmFile(Module &)551 virtual void emitEndOfAsmFile(Module &) {} 552 553 /// Targets can override this to emit stuff before the first basic block in 554 /// the function. emitFunctionBodyStart()555 virtual void emitFunctionBodyStart() {} 556 557 /// Targets can override this to emit stuff after the last basic block in the 558 /// function. emitFunctionBodyEnd()559 virtual void emitFunctionBodyEnd() {} 560 561 /// Targets can override this to emit stuff at the start of a basic block. 562 /// By default, this method prints the label for the specified 563 /// MachineBasicBlock, an alignment (if present) and a comment describing it 564 /// if appropriate. 565 virtual void emitBasicBlockStart(const MachineBasicBlock &MBB); 566 567 /// Targets can override this to emit stuff at the end of a basic block. 568 virtual void emitBasicBlockEnd(const MachineBasicBlock &MBB); 569 570 /// Targets should implement this to emit instructions. emitInstruction(const MachineInstr *)571 virtual void emitInstruction(const MachineInstr *) { 572 llvm_unreachable("EmitInstruction not implemented"); 573 } 574 575 /// Return the symbol for the specified constant pool entry. 576 virtual MCSymbol *GetCPISymbol(unsigned CPID) const; 577 578 virtual void emitFunctionEntryLabel(); 579 emitFunctionDescriptor()580 virtual void emitFunctionDescriptor() { 581 llvm_unreachable("Function descriptor is target-specific."); 582 } 583 584 virtual void emitMachineConstantPoolValue(MachineConstantPoolValue *MCPV); 585 586 /// Targets can override this to change how global constants that are part of 587 /// a C++ static/global constructor list are emitted. emitXXStructor(const DataLayout & DL,const Constant * CV)588 virtual void emitXXStructor(const DataLayout &DL, const Constant *CV) { 589 emitGlobalConstant(DL, CV); 590 } 591 592 /// Return true if the basic block has exactly one predecessor and the control 593 /// transfer mechanism between the predecessor and this block is a 594 /// fall-through. 595 virtual bool 596 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const; 597 598 /// Targets can override this to customize the output of IMPLICIT_DEF 599 /// instructions in verbose mode. 600 virtual void emitImplicitDef(const MachineInstr *MI) const; 601 602 /// getSubtargetInfo() cannot be used where this is needed because we don't 603 /// have a MachineFunction when we're lowering a GlobalIFunc, and 604 /// getSubtargetInfo requires one. Override the implementation in targets 605 /// that support the Mach-O IFunc lowering. getIFuncMCSubtargetInfo()606 virtual const MCSubtargetInfo *getIFuncMCSubtargetInfo() const { 607 return nullptr; 608 } 609 emitMachOIFuncStubBody(Module & M,const GlobalIFunc & GI,MCSymbol * LazyPointer)610 virtual void emitMachOIFuncStubBody(Module &M, const GlobalIFunc &GI, 611 MCSymbol *LazyPointer) { 612 llvm_unreachable( 613 "Mach-O IFunc lowering is not yet supported on this target"); 614 } 615 emitMachOIFuncStubHelperBody(Module & M,const GlobalIFunc & GI,MCSymbol * LazyPointer)616 virtual void emitMachOIFuncStubHelperBody(Module &M, const GlobalIFunc &GI, 617 MCSymbol *LazyPointer) { 618 llvm_unreachable( 619 "Mach-O IFunc lowering is not yet supported on this target"); 620 } 621 622 /// Emit N NOP instructions. 623 void emitNops(unsigned N); 624 625 //===------------------------------------------------------------------===// 626 // Symbol Lowering Routines. 627 //===------------------------------------------------------------------===// 628 629 MCSymbol *createTempSymbol(const Twine &Name) const; 630 631 /// Return the MCSymbol for a private symbol with global value name as its 632 /// base, with the specified suffix. 633 MCSymbol *getSymbolWithGlobalValueBase(const GlobalValue *GV, 634 StringRef Suffix) const; 635 636 /// Return the MCSymbol for the specified ExternalSymbol. 637 MCSymbol *GetExternalSymbolSymbol(Twine Sym) const; 638 639 /// Return the symbol for the specified jump table entry. 640 MCSymbol *GetJTISymbol(unsigned JTID, bool isLinkerPrivate = false) const; 641 642 /// Return the symbol for the specified jump table .set 643 /// FIXME: privatize to AsmPrinter. 644 MCSymbol *GetJTSetSymbol(unsigned UID, unsigned MBBID) const; 645 646 /// Return the MCSymbol used to satisfy BlockAddress uses of the specified 647 /// basic block. 648 MCSymbol *GetBlockAddressSymbol(const BlockAddress *BA) const; 649 MCSymbol *GetBlockAddressSymbol(const BasicBlock *BB) const; 650 651 //===------------------------------------------------------------------===// 652 // Emission Helper Routines. 653 //===------------------------------------------------------------------===// 654 655 /// This is just convenient handler for printing offsets. 656 void printOffset(int64_t Offset, raw_ostream &OS) const; 657 658 /// Emit a byte directive and value. 659 void emitInt8(int Value) const; 660 661 /// Emit a short directive and value. 662 void emitInt16(int Value) const; 663 664 /// Emit a long directive and value. 665 void emitInt32(int Value) const; 666 667 /// Emit a long long directive and value. 668 void emitInt64(uint64_t Value) const; 669 670 /// Emit the specified signed leb128 value. 671 void emitSLEB128(int64_t Value, const char *Desc = nullptr) const; 672 673 /// Emit the specified unsigned leb128 value. 674 void emitULEB128(uint64_t Value, const char *Desc = nullptr, 675 unsigned PadTo = 0) const; 676 677 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive 678 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses 679 /// .set if it is available. 680 void emitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo, 681 unsigned Size) const; 682 683 /// Emit something like ".uleb128 Hi-Lo". 684 void emitLabelDifferenceAsULEB128(const MCSymbol *Hi, 685 const MCSymbol *Lo) const; 686 687 /// Emit something like ".long Label+Offset" where the size in bytes of the 688 /// directive is specified by Size and Label specifies the label. This 689 /// implicitly uses .set if it is available. 690 void emitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset, 691 unsigned Size, bool IsSectionRelative = false) const; 692 693 /// Emit something like ".long Label" where the size in bytes of the directive 694 /// is specified by Size and Label specifies the label. 695 void emitLabelReference(const MCSymbol *Label, unsigned Size, 696 bool IsSectionRelative = false) const { 697 emitLabelPlusOffset(Label, 0, Size, IsSectionRelative); 698 } 699 700 //===------------------------------------------------------------------===// 701 // Dwarf Emission Helper Routines 702 //===------------------------------------------------------------------===// 703 704 /// Emit a .byte 42 directive that corresponds to an encoding. If verbose 705 /// assembly output is enabled, we output comments describing the encoding. 706 /// Desc is a string saying what the encoding is specifying (e.g. "LSDA"). 707 void emitEncodingByte(unsigned Val, const char *Desc = nullptr) const; 708 709 /// Return the size of the encoding in bytes. 710 unsigned GetSizeOfEncodedValue(unsigned Encoding) const; 711 712 /// Emit reference to a ttype global with a specified encoding. 713 virtual void emitTTypeReference(const GlobalValue *GV, unsigned Encoding); 714 715 /// Emit a reference to a symbol for use in dwarf. Different object formats 716 /// represent this in different ways. Some use a relocation others encode 717 /// the label offset in its section. 718 void emitDwarfSymbolReference(const MCSymbol *Label, 719 bool ForceOffset = false) const; 720 721 /// Emit the 4- or 8-byte offset of a string from the start of its section. 722 /// 723 /// When possible, emit a DwarfStringPool section offset without any 724 /// relocations, and without using the symbol. Otherwise, defers to \a 725 /// emitDwarfSymbolReference(). 726 /// 727 /// The length of the emitted value depends on the DWARF format. 728 void emitDwarfStringOffset(DwarfStringPoolEntry S) const; 729 730 /// Emit the 4-or 8-byte offset of a string from the start of its section. emitDwarfStringOffset(DwarfStringPoolEntryRef S)731 void emitDwarfStringOffset(DwarfStringPoolEntryRef S) const { 732 emitDwarfStringOffset(S.getEntry()); 733 } 734 735 /// Emit something like ".long Label + Offset" or ".quad Label + Offset" 736 /// depending on the DWARF format. 737 void emitDwarfOffset(const MCSymbol *Label, uint64_t Offset) const; 738 739 /// Emit 32- or 64-bit value depending on the DWARF format. 740 void emitDwarfLengthOrOffset(uint64_t Value) const; 741 742 /// Emit a unit length field. The actual format, DWARF32 or DWARF64, is chosen 743 /// according to the settings. 744 void emitDwarfUnitLength(uint64_t Length, const Twine &Comment) const; 745 746 /// Emit a unit length field. The actual format, DWARF32 or DWARF64, is chosen 747 /// according to the settings. 748 /// Return the end symbol generated inside, the caller needs to emit it. 749 MCSymbol *emitDwarfUnitLength(const Twine &Prefix, 750 const Twine &Comment) const; 751 752 /// Emit reference to a call site with a specified encoding 753 void emitCallSiteOffset(const MCSymbol *Hi, const MCSymbol *Lo, 754 unsigned Encoding) const; 755 /// Emit an integer value corresponding to the call site encoding 756 void emitCallSiteValue(uint64_t Value, unsigned Encoding) const; 757 758 /// Get the value for DW_AT_APPLE_isa. Zero if no isa encoding specified. getISAEncoding()759 virtual unsigned getISAEncoding() { return 0; } 760 761 /// Emit the directive and value for debug thread local expression 762 /// 763 /// \p Value - The value to emit. 764 /// \p Size - The size of the integer (in bytes) to emit. 765 virtual void emitDebugValue(const MCExpr *Value, unsigned Size) const; 766 767 //===------------------------------------------------------------------===// 768 // Dwarf Lowering Routines 769 //===------------------------------------------------------------------===// 770 771 /// Emit frame instruction to describe the layout of the frame. 772 void emitCFIInstruction(const MCCFIInstruction &Inst) const; 773 774 /// Emit Dwarf abbreviation table. emitDwarfAbbrevs(const T & Abbrevs)775 template <typename T> void emitDwarfAbbrevs(const T &Abbrevs) const { 776 // For each abbreviation. 777 for (const auto &Abbrev : Abbrevs) 778 emitDwarfAbbrev(*Abbrev); 779 780 // Mark end of abbreviations. 781 emitULEB128(0, "EOM(3)"); 782 } 783 784 void emitDwarfAbbrev(const DIEAbbrev &Abbrev) const; 785 786 /// Recursively emit Dwarf DIE tree. 787 void emitDwarfDIE(const DIE &Die) const; 788 789 //===------------------------------------------------------------------===// 790 // CodeView Helper Routines 791 //===------------------------------------------------------------------===// 792 793 /// Gets information required to create a CodeView debug symbol for a jump 794 /// table. 795 /// Return value is <Base Address, Base Offset, Branch Address, Entry Size> 796 virtual std::tuple<const MCSymbol *, uint64_t, const MCSymbol *, 797 codeview::JumpTableEntrySize> 798 getCodeViewJumpTableInfo(int JTI, const MachineInstr *BranchInstr, 799 const MCSymbol *BranchLabel) const; 800 801 //===------------------------------------------------------------------===// 802 // Inline Asm Support 803 //===------------------------------------------------------------------===// 804 805 // These are hooks that targets can override to implement inline asm 806 // support. These should probably be moved out of AsmPrinter someday. 807 808 /// Print information related to the specified machine instr that is 809 /// independent of the operand, and may be independent of the instr itself. 810 /// This can be useful for portably encoding the comment character or other 811 /// bits of target-specific knowledge into the asmstrings. The syntax used is 812 /// ${:comment}. Targets can override this to add support for their own 813 /// strange codes. 814 virtual void PrintSpecial(const MachineInstr *MI, raw_ostream &OS, 815 StringRef Code) const; 816 817 /// Print the MachineOperand as a symbol. Targets with complex handling of 818 /// symbol references should override the base implementation. 819 virtual void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &OS); 820 821 /// Print the specified operand of MI, an INLINEASM instruction, using the 822 /// specified assembler variant. Targets should override this to format as 823 /// appropriate. This method can return true if the operand is erroneous. 824 virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 825 const char *ExtraCode, raw_ostream &OS); 826 827 /// Print the specified operand of MI, an INLINEASM instruction, using the 828 /// specified assembler variant as an address. Targets should override this to 829 /// format as appropriate. This method can return true if the operand is 830 /// erroneous. 831 virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, 832 const char *ExtraCode, raw_ostream &OS); 833 834 /// Let the target do anything it needs to do before emitting inlineasm. 835 /// \p StartInfo - the subtarget info before parsing inline asm 836 virtual void emitInlineAsmStart() const; 837 838 /// Let the target do anything it needs to do after emitting inlineasm. 839 /// This callback can be used restore the original mode in case the 840 /// inlineasm contains directives to switch modes. 841 /// \p StartInfo - the original subtarget info before inline asm 842 /// \p EndInfo - the final subtarget info after parsing the inline asm, 843 /// or NULL if the value is unknown. 844 virtual void emitInlineAsmEnd(const MCSubtargetInfo &StartInfo, 845 const MCSubtargetInfo *EndInfo) const; 846 847 /// This emits visibility information about symbol, if this is supported by 848 /// the target. 849 void emitVisibility(MCSymbol *Sym, unsigned Visibility, 850 bool IsDefinition = true) const; 851 852 /// This emits linkage information about \p GVSym based on \p GV, if this is 853 /// supported by the target. 854 virtual void emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const; 855 856 /// Return the alignment for the specified \p GV. 857 static Align getGVAlignment(const GlobalObject *GV, const DataLayout &DL, 858 Align InAlign = Align(1)); 859 860 private: 861 /// Private state for PrintSpecial() 862 // Assign a unique ID to this machine instruction. 863 mutable const MachineInstr *LastMI = nullptr; 864 mutable unsigned LastFn = 0; 865 mutable unsigned Counter = ~0U; 866 867 bool DwarfUsesRelocationsAcrossSections = false; 868 869 /// This method emits the header for the current function. 870 virtual void emitFunctionHeader(); 871 872 /// This method emits a comment next to header for the current function. 873 virtual void emitFunctionHeaderComment(); 874 875 /// Emit a blob of inline asm to the output streamer. 876 void 877 emitInlineAsm(StringRef Str, const MCSubtargetInfo &STI, 878 const MCTargetOptions &MCOptions, 879 const MDNode *LocMDNode = nullptr, 880 InlineAsm::AsmDialect AsmDialect = InlineAsm::AD_ATT) const; 881 882 /// This method formats and emits the specified machine instruction that is an 883 /// inline asm. 884 void emitInlineAsm(const MachineInstr *MI) const; 885 886 /// Add inline assembly info to the diagnostics machinery, so we can 887 /// emit file and position info. Returns SrcMgr memory buffer position. 888 unsigned addInlineAsmDiagBuffer(StringRef AsmStr, 889 const MDNode *LocMDNode) const; 890 891 //===------------------------------------------------------------------===// 892 // Internal Implementation Details 893 //===------------------------------------------------------------------===// 894 895 void emitJumpTableEntry(const MachineJumpTableInfo *MJTI, 896 const MachineBasicBlock *MBB, unsigned uid) const; 897 void emitLLVMUsedList(const ConstantArray *InitList); 898 /// Emit llvm.ident metadata in an '.ident' directive. 899 void emitModuleIdents(Module &M); 900 /// Emit bytes for llvm.commandline metadata. 901 virtual void emitModuleCommandLines(Module &M); 902 903 GCMetadataPrinter *getOrCreateGCPrinter(GCStrategy &S); 904 void emitGlobalAlias(Module &M, const GlobalAlias &GA); 905 void emitGlobalIFunc(Module &M, const GlobalIFunc &GI); 906 907 private: 908 /// This method decides whether the specified basic block requires a label. 909 bool shouldEmitLabelForBasicBlock(const MachineBasicBlock &MBB) const; 910 911 protected: shouldEmitWeakSwiftAsyncExtendedFramePointerFlags()912 virtual bool shouldEmitWeakSwiftAsyncExtendedFramePointerFlags() const { 913 return false; 914 } 915 }; 916 917 } // end namespace llvm 918 919 #endif // LLVM_CODEGEN_ASMPRINTER_H 920