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