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