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