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