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