1//===- AsmPrinter.cpp - Common AsmPrinter code ----------------------------===//
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 implements the AsmPrinter class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/CodeGen/AsmPrinter.h"
14#include "CodeViewDebug.h"
15#include "DwarfDebug.h"
16#include "DwarfException.h"
17#include "PseudoProbePrinter.h"
18#include "WasmException.h"
19#include "WinCFGuard.h"
20#include "WinException.h"
21#include "llvm/ADT/APFloat.h"
22#include "llvm/ADT/APInt.h"
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/SmallPtrSet.h"
26#include "llvm/ADT/SmallString.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/Statistic.h"
29#include "llvm/ADT/StringExtras.h"
30#include "llvm/ADT/StringRef.h"
31#include "llvm/ADT/TinyPtrVector.h"
32#include "llvm/ADT/Twine.h"
33#include "llvm/Analysis/ConstantFolding.h"
34#include "llvm/Analysis/MemoryLocation.h"
35#include "llvm/Analysis/OptimizationRemarkEmitter.h"
36#include "llvm/BinaryFormat/COFF.h"
37#include "llvm/BinaryFormat/Dwarf.h"
38#include "llvm/BinaryFormat/ELF.h"
39#include "llvm/CodeGen/GCMetadata.h"
40#include "llvm/CodeGen/GCMetadataPrinter.h"
41#include "llvm/CodeGen/LazyMachineBlockFrequencyInfo.h"
42#include "llvm/CodeGen/MachineBasicBlock.h"
43#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
44#include "llvm/CodeGen/MachineConstantPool.h"
45#include "llvm/CodeGen/MachineDominators.h"
46#include "llvm/CodeGen/MachineFrameInfo.h"
47#include "llvm/CodeGen/MachineFunction.h"
48#include "llvm/CodeGen/MachineFunctionPass.h"
49#include "llvm/CodeGen/MachineInstr.h"
50#include "llvm/CodeGen/MachineInstrBundle.h"
51#include "llvm/CodeGen/MachineJumpTableInfo.h"
52#include "llvm/CodeGen/MachineLoopInfo.h"
53#include "llvm/CodeGen/MachineModuleInfo.h"
54#include "llvm/CodeGen/MachineModuleInfoImpls.h"
55#include "llvm/CodeGen/MachineOperand.h"
56#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
57#include "llvm/CodeGen/StackMaps.h"
58#include "llvm/CodeGen/TargetFrameLowering.h"
59#include "llvm/CodeGen/TargetInstrInfo.h"
60#include "llvm/CodeGen/TargetLowering.h"
61#include "llvm/CodeGen/TargetOpcodes.h"
62#include "llvm/CodeGen/TargetRegisterInfo.h"
63#include "llvm/CodeGen/TargetSubtargetInfo.h"
64#include "llvm/Config/config.h"
65#include "llvm/IR/BasicBlock.h"
66#include "llvm/IR/Comdat.h"
67#include "llvm/IR/Constant.h"
68#include "llvm/IR/Constants.h"
69#include "llvm/IR/DataLayout.h"
70#include "llvm/IR/DebugInfoMetadata.h"
71#include "llvm/IR/DerivedTypes.h"
72#include "llvm/IR/EHPersonalities.h"
73#include "llvm/IR/Function.h"
74#include "llvm/IR/GCStrategy.h"
75#include "llvm/IR/GlobalAlias.h"
76#include "llvm/IR/GlobalIFunc.h"
77#include "llvm/IR/GlobalObject.h"
78#include "llvm/IR/GlobalValue.h"
79#include "llvm/IR/GlobalVariable.h"
80#include "llvm/IR/Instruction.h"
81#include "llvm/IR/Mangler.h"
82#include "llvm/IR/Metadata.h"
83#include "llvm/IR/Module.h"
84#include "llvm/IR/Operator.h"
85#include "llvm/IR/PseudoProbe.h"
86#include "llvm/IR/Type.h"
87#include "llvm/IR/Value.h"
88#include "llvm/IR/ValueHandle.h"
89#include "llvm/MC/MCAsmInfo.h"
90#include "llvm/MC/MCContext.h"
91#include "llvm/MC/MCDirectives.h"
92#include "llvm/MC/MCExpr.h"
93#include "llvm/MC/MCInst.h"
94#include "llvm/MC/MCSection.h"
95#include "llvm/MC/MCSectionCOFF.h"
96#include "llvm/MC/MCSectionELF.h"
97#include "llvm/MC/MCSectionMachO.h"
98#include "llvm/MC/MCSectionXCOFF.h"
99#include "llvm/MC/MCStreamer.h"
100#include "llvm/MC/MCSubtargetInfo.h"
101#include "llvm/MC/MCSymbol.h"
102#include "llvm/MC/MCSymbolELF.h"
103#include "llvm/MC/MCTargetOptions.h"
104#include "llvm/MC/MCValue.h"
105#include "llvm/MC/SectionKind.h"
106#include "llvm/Object/ELFTypes.h"
107#include "llvm/Pass.h"
108#include "llvm/Remarks/RemarkStreamer.h"
109#include "llvm/Support/Casting.h"
110#include "llvm/Support/Compiler.h"
111#include "llvm/Support/ErrorHandling.h"
112#include "llvm/Support/FileSystem.h"
113#include "llvm/Support/Format.h"
114#include "llvm/Support/MathExtras.h"
115#include "llvm/Support/Path.h"
116#include "llvm/Support/Timer.h"
117#include "llvm/Support/raw_ostream.h"
118#include "llvm/Target/TargetLoweringObjectFile.h"
119#include "llvm/Target/TargetMachine.h"
120#include "llvm/Target/TargetOptions.h"
121#include "llvm/TargetParser/Triple.h"
122#include <algorithm>
123#include <cassert>
124#include <cinttypes>
125#include <cstdint>
126#include <iterator>
127#include <memory>
128#include <optional>
129#include <string>
130#include <utility>
131#include <vector>
132
133using namespace llvm;
134
135#define DEBUG_TYPE "asm-printer"
136
137// This is a replication of fields of object::PGOAnalysisMap::Features. It
138// should match the order of the fields so that
139// `object::PGOAnalysisMap::Features::decode(PgoAnalysisMapFeatures.getBits())`
140// succeeds.
141enum class PGOMapFeaturesEnum {
142 FuncEntryCount,
143 BBFreq,
144 BrProb,
145};
146static cl::bits<PGOMapFeaturesEnum> PgoAnalysisMapFeatures(
147 "pgo-analysis-map", cl::Hidden, cl::CommaSeparated,
148 cl::values(clEnumValN(PGOMapFeaturesEnum::FuncEntryCount,
149 "func-entry-count", "Function Entry Count"),
150 clEnumValN(PGOMapFeaturesEnum::BBFreq, "bb-freq",
151 "Basic Block Frequency"),
152 clEnumValN(PGOMapFeaturesEnum::BrProb, "br-prob",
153 "Branch Probability")),
154 cl::desc(
155 "Enable extended information within the SHT_LLVM_BB_ADDR_MAP that is "
156 "extracted from PGO related analysis."));
157
158const char DWARFGroupName[] = "dwarf";
159const char DWARFGroupDescription[] = "DWARF Emission";
160const char DbgTimerName[] = "emit";
161const char DbgTimerDescription[] = "Debug Info Emission";
162const char EHTimerName[] = "write_exception";
163const char EHTimerDescription[] = "DWARF Exception Writer";
164const char CFGuardName[] = "Control Flow Guard";
165const char CFGuardDescription[] = "Control Flow Guard";
166const char CodeViewLineTablesGroupName[] = "linetables";
167const char CodeViewLineTablesGroupDescription[] = "CodeView Line Tables";
168const char PPTimerName[] = "emit";
169const char PPTimerDescription[] = "Pseudo Probe Emission";
170const char PPGroupName[] = "pseudo probe";
171const char PPGroupDescription[] = "Pseudo Probe Emission";
172
173STATISTIC(EmittedInsts, "Number of machine instrs printed");
174
175char AsmPrinter::ID = 0;
176
177namespace {
178class AddrLabelMapCallbackPtr final : CallbackVH {
179 AddrLabelMap *Map = nullptr;
180
181public:
182 AddrLabelMapCallbackPtr() = default;
183 AddrLabelMapCallbackPtr(Value *V) : CallbackVH(V) {}
184
185 void setPtr(BasicBlock *BB) {
186 ValueHandleBase::operator=(RHS: BB);
187 }
188
189 void setMap(AddrLabelMap *map) { Map = map; }
190
191 void deleted() override;
192 void allUsesReplacedWith(Value *V2) override;
193};
194} // namespace
195
196class llvm::AddrLabelMap {
197 MCContext &Context;
198 struct AddrLabelSymEntry {
199 /// The symbols for the label.
200 TinyPtrVector<MCSymbol *> Symbols;
201
202 Function *Fn; // The containing function of the BasicBlock.
203 unsigned Index; // The index in BBCallbacks for the BasicBlock.
204 };
205
206 DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols;
207
208 /// Callbacks for the BasicBlock's that we have entries for. We use this so
209 /// we get notified if a block is deleted or RAUWd.
210 std::vector<AddrLabelMapCallbackPtr> BBCallbacks;
211
212 /// This is a per-function list of symbols whose corresponding BasicBlock got
213 /// deleted. These symbols need to be emitted at some point in the file, so
214 /// AsmPrinter emits them after the function body.
215 DenseMap<AssertingVH<Function>, std::vector<MCSymbol *>>
216 DeletedAddrLabelsNeedingEmission;
217
218public:
219 AddrLabelMap(MCContext &context) : Context(context) {}
220
221 ~AddrLabelMap() {
222 assert(DeletedAddrLabelsNeedingEmission.empty() &&
223 "Some labels for deleted blocks never got emitted");
224 }
225
226 ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(BasicBlock *BB);
227
228 void takeDeletedSymbolsForFunction(Function *F,
229 std::vector<MCSymbol *> &Result);
230
231 void UpdateForDeletedBlock(BasicBlock *BB);
232 void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New);
233};
234
235ArrayRef<MCSymbol *> AddrLabelMap::getAddrLabelSymbolToEmit(BasicBlock *BB) {
236 assert(BB->hasAddressTaken() &&
237 "Shouldn't get label for block without address taken");
238 AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
239
240 // If we already had an entry for this block, just return it.
241 if (!Entry.Symbols.empty()) {
242 assert(BB->getParent() == Entry.Fn && "Parent changed");
243 return Entry.Symbols;
244 }
245
246 // Otherwise, this is a new entry, create a new symbol for it and add an
247 // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd.
248 BBCallbacks.emplace_back(args&: BB);
249 BBCallbacks.back().setMap(this);
250 Entry.Index = BBCallbacks.size() - 1;
251 Entry.Fn = BB->getParent();
252 MCSymbol *Sym = BB->hasAddressTaken() ? Context.createNamedTempSymbol()
253 : Context.createTempSymbol();
254 Entry.Symbols.push_back(NewVal: Sym);
255 return Entry.Symbols;
256}
257
258/// If we have any deleted symbols for F, return them.
259void AddrLabelMap::takeDeletedSymbolsForFunction(
260 Function *F, std::vector<MCSymbol *> &Result) {
261 DenseMap<AssertingVH<Function>, std::vector<MCSymbol *>>::iterator I =
262 DeletedAddrLabelsNeedingEmission.find(Val: F);
263
264 // If there are no entries for the function, just return.
265 if (I == DeletedAddrLabelsNeedingEmission.end())
266 return;
267
268 // Otherwise, take the list.
269 std::swap(x&: Result, y&: I->second);
270 DeletedAddrLabelsNeedingEmission.erase(I);
271}
272
273//===- Address of Block Management ----------------------------------------===//
274
275ArrayRef<MCSymbol *>
276AsmPrinter::getAddrLabelSymbolToEmit(const BasicBlock *BB) {
277 // Lazily create AddrLabelSymbols.
278 if (!AddrLabelSymbols)
279 AddrLabelSymbols = std::make_unique<AddrLabelMap>(args&: OutContext);
280 return AddrLabelSymbols->getAddrLabelSymbolToEmit(
281 BB: const_cast<BasicBlock *>(BB));
282}
283
284void AsmPrinter::takeDeletedSymbolsForFunction(
285 const Function *F, std::vector<MCSymbol *> &Result) {
286 // If no blocks have had their addresses taken, we're done.
287 if (!AddrLabelSymbols)
288 return;
289 return AddrLabelSymbols->takeDeletedSymbolsForFunction(
290 F: const_cast<Function *>(F), Result);
291}
292
293void AddrLabelMap::UpdateForDeletedBlock(BasicBlock *BB) {
294 // If the block got deleted, there is no need for the symbol. If the symbol
295 // was already emitted, we can just forget about it, otherwise we need to
296 // queue it up for later emission when the function is output.
297 AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]);
298 AddrLabelSymbols.erase(Val: BB);
299 assert(!Entry.Symbols.empty() && "Didn't have a symbol, why a callback?");
300 BBCallbacks[Entry.Index] = nullptr; // Clear the callback.
301
302#if !LLVM_MEMORY_SANITIZER_BUILD
303 // BasicBlock is destroyed already, so this access is UB detectable by msan.
304 assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) &&
305 "Block/parent mismatch");
306#endif
307
308 for (MCSymbol *Sym : Entry.Symbols) {
309 if (Sym->isDefined())
310 return;
311
312 // If the block is not yet defined, we need to emit it at the end of the
313 // function. Add the symbol to the DeletedAddrLabelsNeedingEmission list
314 // for the containing Function. Since the block is being deleted, its
315 // parent may already be removed, we have to get the function from 'Entry'.
316 DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(x: Sym);
317 }
318}
319
320void AddrLabelMap::UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New) {
321 // Get the entry for the RAUW'd block and remove it from our map.
322 AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]);
323 AddrLabelSymbols.erase(Val: Old);
324 assert(!OldEntry.Symbols.empty() && "Didn't have a symbol, why a callback?");
325
326 AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
327
328 // If New is not address taken, just move our symbol over to it.
329 if (NewEntry.Symbols.empty()) {
330 BBCallbacks[OldEntry.Index].setPtr(New); // Update the callback.
331 NewEntry = std::move(OldEntry); // Set New's entry.
332 return;
333 }
334
335 BBCallbacks[OldEntry.Index] = nullptr; // Update the callback.
336
337 // Otherwise, we need to add the old symbols to the new block's set.
338 llvm::append_range(C&: NewEntry.Symbols, R&: OldEntry.Symbols);
339}
340
341void AddrLabelMapCallbackPtr::deleted() {
342 Map->UpdateForDeletedBlock(BB: cast<BasicBlock>(Val: getValPtr()));
343}
344
345void AddrLabelMapCallbackPtr::allUsesReplacedWith(Value *V2) {
346 Map->UpdateForRAUWBlock(Old: cast<BasicBlock>(Val: getValPtr()), New: cast<BasicBlock>(Val: V2));
347}
348
349/// getGVAlignment - Return the alignment to use for the specified global
350/// value. This rounds up to the preferred alignment if possible and legal.
351Align AsmPrinter::getGVAlignment(const GlobalObject *GV, const DataLayout &DL,
352 Align InAlign) {
353 Align Alignment;
354 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(Val: GV))
355 Alignment = DL.getPreferredAlign(GV: GVar);
356
357 // If InAlign is specified, round it to it.
358 if (InAlign > Alignment)
359 Alignment = InAlign;
360
361 // If the GV has a specified alignment, take it into account.
362 const MaybeAlign GVAlign(GV->getAlign());
363 if (!GVAlign)
364 return Alignment;
365
366 assert(GVAlign && "GVAlign must be set");
367
368 // If the GVAlign is larger than NumBits, or if we are required to obey
369 // NumBits because the GV has an assigned section, obey it.
370 if (*GVAlign > Alignment || GV->hasSection())
371 Alignment = *GVAlign;
372 return Alignment;
373}
374
375AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer)
376 : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
377 OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)),
378 SM(*this) {
379 VerboseAsm = OutStreamer->isVerboseAsm();
380 DwarfUsesRelocationsAcrossSections =
381 MAI->doesDwarfUseRelocationsAcrossSections();
382}
383
384AsmPrinter::~AsmPrinter() {
385 assert(!DD && Handlers.size() == NumUserHandlers &&
386 "Debug/EH info didn't get finalized");
387}
388
389bool AsmPrinter::isPositionIndependent() const {
390 return TM.isPositionIndependent();
391}
392
393/// getFunctionNumber - Return a unique ID for the current function.
394unsigned AsmPrinter::getFunctionNumber() const {
395 return MF->getFunctionNumber();
396}
397
398const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
399 return *TM.getObjFileLowering();
400}
401
402const DataLayout &AsmPrinter::getDataLayout() const {
403 assert(MMI && "MMI could not be nullptr!");
404 return MMI->getModule()->getDataLayout();
405}
406
407// Do not use the cached DataLayout because some client use it without a Module
408// (dsymutil, llvm-dwarfdump).
409unsigned AsmPrinter::getPointerSize() const {
410 return TM.getPointerSize(AS: 0); // FIXME: Default address space
411}
412
413const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const {
414 assert(MF && "getSubtargetInfo requires a valid MachineFunction!");
415 return MF->getSubtarget<MCSubtargetInfo>();
416}
417
418void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
419 S.emitInstruction(Inst, STI: getSubtargetInfo());
420}
421
422void AsmPrinter::emitInitialRawDwarfLocDirective(const MachineFunction &MF) {
423 if (DD) {
424 assert(OutStreamer->hasRawTextSupport() &&
425 "Expected assembly output mode.");
426 // This is NVPTX specific and it's unclear why.
427 // PR51079: If we have code without debug information we need to give up.
428 DISubprogram *MFSP = MF.getFunction().getSubprogram();
429 if (!MFSP)
430 return;
431 (void)DD->emitInitialLocDirective(MF, /*CUID=*/0);
432 }
433}
434
435/// getCurrentSection() - Return the current section we are emitting to.
436const MCSection *AsmPrinter::getCurrentSection() const {
437 return OutStreamer->getCurrentSectionOnly();
438}
439
440void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
441 AU.setPreservesAll();
442 MachineFunctionPass::getAnalysisUsage(AU);
443 AU.addRequired<MachineOptimizationRemarkEmitterPass>();
444 AU.addRequired<GCModuleInfo>();
445 AU.addRequired<LazyMachineBlockFrequencyInfoPass>();
446 AU.addRequired<MachineBranchProbabilityInfo>();
447}
448
449bool AsmPrinter::doInitialization(Module &M) {
450 auto *MMIWP = getAnalysisIfAvailable<MachineModuleInfoWrapperPass>();
451 MMI = MMIWP ? &MMIWP->getMMI() : nullptr;
452 HasSplitStack = false;
453 HasNoSplitStack = false;
454
455 AddrLabelSymbols = nullptr;
456
457 // Initialize TargetLoweringObjectFile.
458 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
459 .Initialize(ctx&: OutContext, TM);
460
461 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
462 .getModuleMetadata(M);
463
464 // On AIX, we delay emitting any section information until
465 // after emitting the .file pseudo-op. This allows additional
466 // information (such as the embedded command line) to be associated
467 // with all sections in the object file rather than a single section.
468 if (!TM.getTargetTriple().isOSBinFormatXCOFF())
469 OutStreamer->initSections(NoExecStack: false, STI: *TM.getMCSubtargetInfo());
470
471 // Emit the version-min deployment target directive if needed.
472 //
473 // FIXME: If we end up with a collection of these sorts of Darwin-specific
474 // or ELF-specific things, it may make sense to have a platform helper class
475 // that will work with the target helper class. For now keep it here, as the
476 // alternative is duplicated code in each of the target asm printers that
477 // use the directive, where it would need the same conditionalization
478 // anyway.
479 const Triple &Target = TM.getTargetTriple();
480 Triple TVT(M.getDarwinTargetVariantTriple());
481 OutStreamer->emitVersionForTarget(
482 Target, SDKVersion: M.getSDKVersion(),
483 DarwinTargetVariantTriple: M.getDarwinTargetVariantTriple().empty() ? nullptr : &TVT,
484 DarwinTargetVariantSDKVersion: M.getDarwinTargetVariantSDKVersion());
485
486 // Allow the target to emit any magic that it wants at the start of the file.
487 emitStartOfAsmFile(M);
488
489 // Very minimal debug info. It is ignored if we emit actual debug info. If we
490 // don't, this at least helps the user find where a global came from.
491 if (MAI->hasSingleParameterDotFile()) {
492 // .file "foo.c"
493
494 SmallString<128> FileName;
495 if (MAI->hasBasenameOnlyForFileDirective())
496 FileName = llvm::sys::path::filename(path: M.getSourceFileName());
497 else
498 FileName = M.getSourceFileName();
499 if (MAI->hasFourStringsDotFile()) {
500#ifdef PACKAGE_VENDOR
501 const char VerStr[] =
502 PACKAGE_VENDOR " " PACKAGE_NAME " version " PACKAGE_VERSION;
503#else
504 const char VerStr[] = PACKAGE_NAME " version " PACKAGE_VERSION;
505#endif
506 // TODO: Add timestamp and description.
507 OutStreamer->emitFileDirective(Filename: FileName, CompilerVersion: VerStr, TimeStamp: "", Description: "");
508 } else {
509 OutStreamer->emitFileDirective(Filename: FileName);
510 }
511 }
512
513 // On AIX, emit bytes for llvm.commandline metadata after .file so that the
514 // C_INFO symbol is preserved if any csect is kept by the linker.
515 if (TM.getTargetTriple().isOSBinFormatXCOFF()) {
516 emitModuleCommandLines(M);
517 // Now we can generate section information.
518 OutStreamer->initSections(NoExecStack: false, STI: *TM.getMCSubtargetInfo());
519
520 // To work around an AIX assembler and/or linker bug, generate
521 // a rename for the default text-section symbol name. This call has
522 // no effect when generating object code directly.
523 MCSection *TextSection =
524 OutStreamer->getContext().getObjectFileInfo()->getTextSection();
525 MCSymbolXCOFF *XSym =
526 static_cast<MCSectionXCOFF *>(TextSection)->getQualNameSymbol();
527 if (XSym->hasRename())
528 OutStreamer->emitXCOFFRenameDirective(Name: XSym, Rename: XSym->getSymbolTableName());
529 }
530
531 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
532 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
533 for (const auto &I : *MI)
534 if (GCMetadataPrinter *MP = getOrCreateGCPrinter(S&: *I))
535 MP->beginAssembly(M, Info&: *MI, AP&: *this);
536
537 // Emit module-level inline asm if it exists.
538 if (!M.getModuleInlineAsm().empty()) {
539 OutStreamer->AddComment(T: "Start of file scope inline assembly");
540 OutStreamer->addBlankLine();
541 emitInlineAsm(Str: M.getModuleInlineAsm() + "\n", STI: *TM.getMCSubtargetInfo(),
542 MCOptions: TM.Options.MCOptions);
543 OutStreamer->AddComment(T: "End of file scope inline assembly");
544 OutStreamer->addBlankLine();
545 }
546
547 if (MAI->doesSupportDebugInformation()) {
548 bool EmitCodeView = M.getCodeViewFlag();
549 if (EmitCodeView && TM.getTargetTriple().isOSWindows()) {
550 Handlers.emplace_back(args: std::make_unique<CodeViewDebug>(args: this),
551 args: DbgTimerName, args: DbgTimerDescription,
552 args: CodeViewLineTablesGroupName,
553 args: CodeViewLineTablesGroupDescription);
554 }
555 if (!EmitCodeView || M.getDwarfVersion()) {
556 assert(MMI && "MMI could not be nullptr here!");
557 if (MMI->hasDebugInfo()) {
558 DD = new DwarfDebug(this);
559 Handlers.emplace_back(args: std::unique_ptr<DwarfDebug>(DD), args: DbgTimerName,
560 args: DbgTimerDescription, args: DWARFGroupName,
561 args: DWARFGroupDescription);
562 }
563 }
564 }
565
566 if (M.getNamedMetadata(Name: PseudoProbeDescMetadataName)) {
567 PP = new PseudoProbeHandler(this);
568 Handlers.emplace_back(args: std::unique_ptr<PseudoProbeHandler>(PP), args: PPTimerName,
569 args: PPTimerDescription, args: PPGroupName, args: PPGroupDescription);
570 }
571
572 switch (MAI->getExceptionHandlingType()) {
573 case ExceptionHandling::None:
574 // We may want to emit CFI for debug.
575 [[fallthrough]];
576 case ExceptionHandling::SjLj:
577 case ExceptionHandling::DwarfCFI:
578 case ExceptionHandling::ARM:
579 for (auto &F : M.getFunctionList()) {
580 if (getFunctionCFISectionType(F) != CFISection::None)
581 ModuleCFISection = getFunctionCFISectionType(F);
582 // If any function needsUnwindTableEntry(), it needs .eh_frame and hence
583 // the module needs .eh_frame. If we have found that case, we are done.
584 if (ModuleCFISection == CFISection::EH)
585 break;
586 }
587 assert(MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI ||
588 usesCFIWithoutEH() || ModuleCFISection != CFISection::EH);
589 break;
590 default:
591 break;
592 }
593
594 EHStreamer *ES = nullptr;
595 switch (MAI->getExceptionHandlingType()) {
596 case ExceptionHandling::None:
597 if (!usesCFIWithoutEH())
598 break;
599 [[fallthrough]];
600 case ExceptionHandling::SjLj:
601 case ExceptionHandling::DwarfCFI:
602 case ExceptionHandling::ZOS:
603 ES = new DwarfCFIException(this);
604 break;
605 case ExceptionHandling::ARM:
606 ES = new ARMException(this);
607 break;
608 case ExceptionHandling::WinEH:
609 switch (MAI->getWinEHEncodingType()) {
610 default: llvm_unreachable("unsupported unwinding information encoding");
611 case WinEH::EncodingType::Invalid:
612 break;
613 case WinEH::EncodingType::X86:
614 case WinEH::EncodingType::Itanium:
615 ES = new WinException(this);
616 break;
617 }
618 break;
619 case ExceptionHandling::Wasm:
620 ES = new WasmException(this);
621 break;
622 case ExceptionHandling::AIX:
623 ES = new AIXException(this);
624 break;
625 }
626 if (ES)
627 Handlers.emplace_back(args: std::unique_ptr<EHStreamer>(ES), args: EHTimerName,
628 args: EHTimerDescription, args: DWARFGroupName,
629 args: DWARFGroupDescription);
630
631 // Emit tables for any value of cfguard flag (i.e. cfguard=1 or cfguard=2).
632 if (mdconst::extract_or_null<ConstantInt>(MD: M.getModuleFlag(Key: "cfguard")))
633 Handlers.emplace_back(args: std::make_unique<WinCFGuard>(args: this), args: CFGuardName,
634 args: CFGuardDescription, args: DWARFGroupName,
635 args: DWARFGroupDescription);
636
637 for (const HandlerInfo &HI : Handlers) {
638 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
639 HI.TimerGroupDescription, TimePassesIsEnabled);
640 HI.Handler->beginModule(M: &M);
641 }
642
643 return false;
644}
645
646static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
647 if (!MAI.hasWeakDefCanBeHiddenDirective())
648 return false;
649
650 return GV->canBeOmittedFromSymbolTable();
651}
652
653void AsmPrinter::emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
654 GlobalValue::LinkageTypes Linkage = GV->getLinkage();
655 switch (Linkage) {
656 case GlobalValue::CommonLinkage:
657 case GlobalValue::LinkOnceAnyLinkage:
658 case GlobalValue::LinkOnceODRLinkage:
659 case GlobalValue::WeakAnyLinkage:
660 case GlobalValue::WeakODRLinkage:
661 if (MAI->hasWeakDefDirective()) {
662 // .globl _foo
663 OutStreamer->emitSymbolAttribute(Symbol: GVSym, Attribute: MCSA_Global);
664
665 if (!canBeHidden(GV, MAI: *MAI))
666 // .weak_definition _foo
667 OutStreamer->emitSymbolAttribute(Symbol: GVSym, Attribute: MCSA_WeakDefinition);
668 else
669 OutStreamer->emitSymbolAttribute(Symbol: GVSym, Attribute: MCSA_WeakDefAutoPrivate);
670 } else if (MAI->avoidWeakIfComdat() && GV->hasComdat()) {
671 // .globl _foo
672 OutStreamer->emitSymbolAttribute(Symbol: GVSym, Attribute: MCSA_Global);
673 //NOTE: linkonce is handled by the section the symbol was assigned to.
674 } else {
675 // .weak _foo
676 OutStreamer->emitSymbolAttribute(Symbol: GVSym, Attribute: MCSA_Weak);
677 }
678 return;
679 case GlobalValue::ExternalLinkage:
680 OutStreamer->emitSymbolAttribute(Symbol: GVSym, Attribute: MCSA_Global);
681 return;
682 case GlobalValue::PrivateLinkage:
683 case GlobalValue::InternalLinkage:
684 return;
685 case GlobalValue::ExternalWeakLinkage:
686 case GlobalValue::AvailableExternallyLinkage:
687 case GlobalValue::AppendingLinkage:
688 llvm_unreachable("Should never emit this");
689 }
690 llvm_unreachable("Unknown linkage type!");
691}
692
693void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name,
694 const GlobalValue *GV) const {
695 TM.getNameWithPrefix(Name, GV, Mang&: getObjFileLowering().getMangler());
696}
697
698MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
699 return TM.getSymbol(GV);
700}
701
702MCSymbol *AsmPrinter::getSymbolPreferLocal(const GlobalValue &GV) const {
703 // On ELF, use .Lfoo$local if GV is a non-interposable GlobalObject with an
704 // exact definion (intersection of GlobalValue::hasExactDefinition() and
705 // !isInterposable()). These linkages include: external, appending, internal,
706 // private. It may be profitable to use a local alias for external. The
707 // assembler would otherwise be conservative and assume a global default
708 // visibility symbol can be interposable, even if the code generator already
709 // assumed it.
710 if (TM.getTargetTriple().isOSBinFormatELF() && GV.canBenefitFromLocalAlias()) {
711 const Module &M = *GV.getParent();
712 if (TM.getRelocationModel() != Reloc::Static &&
713 M.getPIELevel() == PIELevel::Default && GV.isDSOLocal())
714 return getSymbolWithGlobalValueBase(GV: &GV, Suffix: "$local");
715 }
716 return TM.getSymbol(GV: &GV);
717}
718
719/// EmitGlobalVariable - Emit the specified global variable to the .s file.
720void AsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
721 bool IsEmuTLSVar = TM.useEmulatedTLS() && GV->isThreadLocal();
722 assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) &&
723 "No emulated TLS variables in the common section");
724
725 // Never emit TLS variable xyz in emulated TLS model.
726 // The initialization value is in __emutls_t.xyz instead of xyz.
727 if (IsEmuTLSVar)
728 return;
729
730 if (GV->hasInitializer()) {
731 // Check to see if this is a special global used by LLVM, if so, emit it.
732 if (emitSpecialLLVMGlobal(GV))
733 return;
734
735 // Skip the emission of global equivalents. The symbol can be emitted later
736 // on by emitGlobalGOTEquivs in case it turns out to be needed.
737 if (GlobalGOTEquivs.count(Key: getSymbol(GV)))
738 return;
739
740 if (isVerbose()) {
741 // When printing the control variable __emutls_v.*,
742 // we don't need to print the original TLS variable name.
743 GV->printAsOperand(O&: OutStreamer->getCommentOS(),
744 /*PrintType=*/false, M: GV->getParent());
745 OutStreamer->getCommentOS() << '\n';
746 }
747 }
748
749 MCSymbol *GVSym = getSymbol(GV);
750 MCSymbol *EmittedSym = GVSym;
751
752 // getOrCreateEmuTLSControlSym only creates the symbol with name and default
753 // attributes.
754 // GV's or GVSym's attributes will be used for the EmittedSym.
755 emitVisibility(Sym: EmittedSym, Visibility: GV->getVisibility(), IsDefinition: !GV->isDeclaration());
756
757 if (GV->isTagged()) {
758 Triple T = TM.getTargetTriple();
759
760 if (T.getArch() != Triple::aarch64 || !T.isAndroid())
761 OutContext.reportError(L: SMLoc(),
762 Msg: "tagged symbols (-fsanitize=memtag-globals) are "
763 "only supported on AArch64 Android");
764 OutStreamer->emitSymbolAttribute(Symbol: EmittedSym, Attribute: MAI->getMemtagAttr());
765 }
766
767 if (!GV->hasInitializer()) // External globals require no extra code.
768 return;
769
770 GVSym->redefineIfPossible();
771 if (GVSym->isDefined() || GVSym->isVariable())
772 OutContext.reportError(L: SMLoc(), Msg: "symbol '" + Twine(GVSym->getName()) +
773 "' is already defined");
774
775 if (MAI->hasDotTypeDotSizeDirective())
776 OutStreamer->emitSymbolAttribute(Symbol: EmittedSym, Attribute: MCSA_ELF_TypeObject);
777
778 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GO: GV, TM);
779
780 const DataLayout &DL = GV->getParent()->getDataLayout();
781 uint64_t Size = DL.getTypeAllocSize(Ty: GV->getValueType());
782
783 // If the alignment is specified, we *must* obey it. Overaligning a global
784 // with a specified alignment is a prompt way to break globals emitted to
785 // sections and expected to be contiguous (e.g. ObjC metadata).
786 const Align Alignment = getGVAlignment(GV, DL);
787
788 for (const HandlerInfo &HI : Handlers) {
789 NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
790 HI.TimerGroupName, HI.TimerGroupDescription,
791 TimePassesIsEnabled);
792 HI.Handler->setSymbolSize(Sym: GVSym, Size);
793 }
794
795 // Handle common symbols
796 if (GVKind.isCommon()) {
797 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
798 // .comm _foo, 42, 4
799 OutStreamer->emitCommonSymbol(Symbol: GVSym, Size, ByteAlignment: Alignment);
800 return;
801 }
802
803 // Determine to which section this global should be emitted.
804 MCSection *TheSection = getObjFileLowering().SectionForGlobal(GO: GV, Kind: GVKind, TM);
805
806 // If we have a bss global going to a section that supports the
807 // zerofill directive, do so here.
808 if (GVKind.isBSS() && MAI->hasMachoZeroFillDirective() &&
809 TheSection->isVirtualSection()) {
810 if (Size == 0)
811 Size = 1; // zerofill of 0 bytes is undefined.
812 emitLinkage(GV, GVSym);
813 // .zerofill __DATA, __bss, _foo, 400, 5
814 OutStreamer->emitZerofill(Section: TheSection, Symbol: GVSym, Size, ByteAlignment: Alignment);
815 return;
816 }
817
818 // If this is a BSS local symbol and we are emitting in the BSS
819 // section use .lcomm/.comm directive.
820 if (GVKind.isBSSLocal() &&
821 getObjFileLowering().getBSSSection() == TheSection) {
822 if (Size == 0)
823 Size = 1; // .comm Foo, 0 is undefined, avoid it.
824
825 // Use .lcomm only if it supports user-specified alignment.
826 // Otherwise, while it would still be correct to use .lcomm in some
827 // cases (e.g. when Align == 1), the external assembler might enfore
828 // some -unknown- default alignment behavior, which could cause
829 // spurious differences between external and integrated assembler.
830 // Prefer to simply fall back to .local / .comm in this case.
831 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
832 // .lcomm _foo, 42
833 OutStreamer->emitLocalCommonSymbol(Symbol: GVSym, Size, ByteAlignment: Alignment);
834 return;
835 }
836
837 // .local _foo
838 OutStreamer->emitSymbolAttribute(Symbol: GVSym, Attribute: MCSA_Local);
839 // .comm _foo, 42, 4
840 OutStreamer->emitCommonSymbol(Symbol: GVSym, Size, ByteAlignment: Alignment);
841 return;
842 }
843
844 // Handle thread local data for mach-o which requires us to output an
845 // additional structure of data and mangle the original symbol so that we
846 // can reference it later.
847 //
848 // TODO: This should become an "emit thread local global" method on TLOF.
849 // All of this macho specific stuff should be sunk down into TLOFMachO and
850 // stuff like "TLSExtraDataSection" should no longer be part of the parent
851 // TLOF class. This will also make it more obvious that stuff like
852 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
853 // specific code.
854 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
855 // Emit the .tbss symbol
856 MCSymbol *MangSym =
857 OutContext.getOrCreateSymbol(Name: GVSym->getName() + Twine("$tlv$init"));
858
859 if (GVKind.isThreadBSS()) {
860 TheSection = getObjFileLowering().getTLSBSSSection();
861 OutStreamer->emitTBSSSymbol(Section: TheSection, Symbol: MangSym, Size, ByteAlignment: Alignment);
862 } else if (GVKind.isThreadData()) {
863 OutStreamer->switchSection(Section: TheSection);
864
865 emitAlignment(Alignment, GV);
866 OutStreamer->emitLabel(Symbol: MangSym);
867
868 emitGlobalConstant(DL: GV->getParent()->getDataLayout(),
869 CV: GV->getInitializer());
870 }
871
872 OutStreamer->addBlankLine();
873
874 // Emit the variable struct for the runtime.
875 MCSection *TLVSect = getObjFileLowering().getTLSExtraDataSection();
876
877 OutStreamer->switchSection(Section: TLVSect);
878 // Emit the linkage here.
879 emitLinkage(GV, GVSym);
880 OutStreamer->emitLabel(Symbol: GVSym);
881
882 // Three pointers in size:
883 // - __tlv_bootstrap - used to make sure support exists
884 // - spare pointer, used when mapped by the runtime
885 // - pointer to mangled symbol above with initializer
886 unsigned PtrSize = DL.getPointerTypeSize(Ty: GV->getType());
887 OutStreamer->emitSymbolValue(Sym: GetExternalSymbolSymbol(Sym: "_tlv_bootstrap"),
888 Size: PtrSize);
889 OutStreamer->emitIntValue(Value: 0, Size: PtrSize);
890 OutStreamer->emitSymbolValue(Sym: MangSym, Size: PtrSize);
891
892 OutStreamer->addBlankLine();
893 return;
894 }
895
896 MCSymbol *EmittedInitSym = GVSym;
897
898 OutStreamer->switchSection(Section: TheSection);
899
900 emitLinkage(GV, GVSym: EmittedInitSym);
901 emitAlignment(Alignment, GV);
902
903 OutStreamer->emitLabel(Symbol: EmittedInitSym);
904 MCSymbol *LocalAlias = getSymbolPreferLocal(GV: *GV);
905 if (LocalAlias != EmittedInitSym)
906 OutStreamer->emitLabel(Symbol: LocalAlias);
907
908 emitGlobalConstant(DL: GV->getParent()->getDataLayout(), CV: GV->getInitializer());
909
910 if (MAI->hasDotTypeDotSizeDirective())
911 // .size foo, 42
912 OutStreamer->emitELFSize(Symbol: EmittedInitSym,
913 Value: MCConstantExpr::create(Value: Size, Ctx&: OutContext));
914
915 OutStreamer->addBlankLine();
916}
917
918/// Emit the directive and value for debug thread local expression
919///
920/// \p Value - The value to emit.
921/// \p Size - The size of the integer (in bytes) to emit.
922void AsmPrinter::emitDebugValue(const MCExpr *Value, unsigned Size) const {
923 OutStreamer->emitValue(Value, Size);
924}
925
926void AsmPrinter::emitFunctionHeaderComment() {}
927
928/// EmitFunctionHeader - This method emits the header for the current
929/// function.
930void AsmPrinter::emitFunctionHeader() {
931 const Function &F = MF->getFunction();
932
933 if (isVerbose())
934 OutStreamer->getCommentOS()
935 << "-- Begin function "
936 << GlobalValue::dropLLVMManglingEscape(Name: F.getName()) << '\n';
937
938 // Print out constants referenced by the function
939 emitConstantPool();
940
941 // Print the 'header' of function.
942 // If basic block sections are desired, explicitly request a unique section
943 // for this function's entry block.
944 if (MF->front().isBeginSection())
945 MF->setSection(getObjFileLowering().getUniqueSectionForFunction(F, TM));
946 else
947 MF->setSection(getObjFileLowering().SectionForGlobal(GO: &F, TM));
948 OutStreamer->switchSection(Section: MF->getSection());
949
950 if (!MAI->hasVisibilityOnlyWithLinkage())
951 emitVisibility(Sym: CurrentFnSym, Visibility: F.getVisibility());
952
953 if (MAI->needsFunctionDescriptors())
954 emitLinkage(GV: &F, GVSym: CurrentFnDescSym);
955
956 emitLinkage(GV: &F, GVSym: CurrentFnSym);
957 if (MAI->hasFunctionAlignment())
958 emitAlignment(Alignment: MF->getAlignment(), GV: &F);
959
960 if (MAI->hasDotTypeDotSizeDirective())
961 OutStreamer->emitSymbolAttribute(Symbol: CurrentFnSym, Attribute: MCSA_ELF_TypeFunction);
962
963 if (F.hasFnAttribute(Attribute::Cold))
964 OutStreamer->emitSymbolAttribute(Symbol: CurrentFnSym, Attribute: MCSA_Cold);
965
966 // Emit the prefix data.
967 if (F.hasPrefixData()) {
968 if (MAI->hasSubsectionsViaSymbols()) {
969 // Preserving prefix data on platforms which use subsections-via-symbols
970 // is a bit tricky. Here we introduce a symbol for the prefix data
971 // and use the .alt_entry attribute to mark the function's real entry point
972 // as an alternative entry point to the prefix-data symbol.
973 MCSymbol *PrefixSym = OutContext.createLinkerPrivateTempSymbol();
974 OutStreamer->emitLabel(Symbol: PrefixSym);
975
976 emitGlobalConstant(DL: F.getParent()->getDataLayout(), CV: F.getPrefixData());
977
978 // Emit an .alt_entry directive for the actual function symbol.
979 OutStreamer->emitSymbolAttribute(Symbol: CurrentFnSym, Attribute: MCSA_AltEntry);
980 } else {
981 emitGlobalConstant(DL: F.getParent()->getDataLayout(), CV: F.getPrefixData());
982 }
983 }
984
985 // Emit KCFI type information before patchable-function-prefix nops.
986 emitKCFITypeId(MF: *MF);
987
988 // Emit M NOPs for -fpatchable-function-entry=N,M where M>0. We arbitrarily
989 // place prefix data before NOPs.
990 unsigned PatchableFunctionPrefix = 0;
991 unsigned PatchableFunctionEntry = 0;
992 (void)F.getFnAttribute(Kind: "patchable-function-prefix")
993 .getValueAsString()
994 .getAsInteger(Radix: 10, Result&: PatchableFunctionPrefix);
995 (void)F.getFnAttribute(Kind: "patchable-function-entry")
996 .getValueAsString()
997 .getAsInteger(Radix: 10, Result&: PatchableFunctionEntry);
998 if (PatchableFunctionPrefix) {
999 CurrentPatchableFunctionEntrySym =
1000 OutContext.createLinkerPrivateTempSymbol();
1001 OutStreamer->emitLabel(Symbol: CurrentPatchableFunctionEntrySym);
1002 emitNops(N: PatchableFunctionPrefix);
1003 } else if (PatchableFunctionEntry) {
1004 // May be reassigned when emitting the body, to reference the label after
1005 // the initial BTI (AArch64) or endbr32/endbr64 (x86).
1006 CurrentPatchableFunctionEntrySym = CurrentFnBegin;
1007 }
1008
1009 // Emit the function prologue data for the indirect call sanitizer.
1010 if (const MDNode *MD = F.getMetadata(KindID: LLVMContext::MD_func_sanitize)) {
1011 assert(MD->getNumOperands() == 2);
1012
1013 auto *PrologueSig = mdconst::extract<Constant>(MD: MD->getOperand(I: 0));
1014 auto *TypeHash = mdconst::extract<Constant>(MD: MD->getOperand(I: 1));
1015 emitGlobalConstant(DL: F.getParent()->getDataLayout(), CV: PrologueSig);
1016 emitGlobalConstant(DL: F.getParent()->getDataLayout(), CV: TypeHash);
1017 }
1018
1019 if (isVerbose()) {
1020 F.printAsOperand(O&: OutStreamer->getCommentOS(),
1021 /*PrintType=*/false, M: F.getParent());
1022 emitFunctionHeaderComment();
1023 OutStreamer->getCommentOS() << '\n';
1024 }
1025
1026 // Emit the function descriptor. This is a virtual function to allow targets
1027 // to emit their specific function descriptor. Right now it is only used by
1028 // the AIX target. The PowerPC 64-bit V1 ELF target also uses function
1029 // descriptors and should be converted to use this hook as well.
1030 if (MAI->needsFunctionDescriptors())
1031 emitFunctionDescriptor();
1032
1033 // Emit the CurrentFnSym. This is a virtual function to allow targets to do
1034 // their wild and crazy things as required.
1035 emitFunctionEntryLabel();
1036
1037 // If the function had address-taken blocks that got deleted, then we have
1038 // references to the dangling symbols. Emit them at the start of the function
1039 // so that we don't get references to undefined symbols.
1040 std::vector<MCSymbol*> DeadBlockSyms;
1041 takeDeletedSymbolsForFunction(F: &F, Result&: DeadBlockSyms);
1042 for (MCSymbol *DeadBlockSym : DeadBlockSyms) {
1043 OutStreamer->AddComment(T: "Address taken block that was later removed");
1044 OutStreamer->emitLabel(Symbol: DeadBlockSym);
1045 }
1046
1047 if (CurrentFnBegin) {
1048 if (MAI->useAssignmentForEHBegin()) {
1049 MCSymbol *CurPos = OutContext.createTempSymbol();
1050 OutStreamer->emitLabel(Symbol: CurPos);
1051 OutStreamer->emitAssignment(Symbol: CurrentFnBegin,
1052 Value: MCSymbolRefExpr::create(Symbol: CurPos, Ctx&: OutContext));
1053 } else {
1054 OutStreamer->emitLabel(Symbol: CurrentFnBegin);
1055 }
1056 }
1057
1058 // Emit pre-function debug and/or EH information.
1059 for (const HandlerInfo &HI : Handlers) {
1060 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1061 HI.TimerGroupDescription, TimePassesIsEnabled);
1062 HI.Handler->beginFunction(MF);
1063 }
1064 for (const HandlerInfo &HI : Handlers) {
1065 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1066 HI.TimerGroupDescription, TimePassesIsEnabled);
1067 HI.Handler->beginBasicBlockSection(MBB: MF->front());
1068 }
1069
1070 // Emit the prologue data.
1071 if (F.hasPrologueData())
1072 emitGlobalConstant(DL: F.getParent()->getDataLayout(), CV: F.getPrologueData());
1073}
1074
1075/// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
1076/// function. This can be overridden by targets as required to do custom stuff.
1077void AsmPrinter::emitFunctionEntryLabel() {
1078 CurrentFnSym->redefineIfPossible();
1079
1080 // The function label could have already been emitted if two symbols end up
1081 // conflicting due to asm renaming. Detect this and emit an error.
1082 if (CurrentFnSym->isVariable())
1083 report_fatal_error(reason: "'" + Twine(CurrentFnSym->getName()) +
1084 "' is a protected alias");
1085
1086 OutStreamer->emitLabel(Symbol: CurrentFnSym);
1087
1088 if (TM.getTargetTriple().isOSBinFormatELF()) {
1089 MCSymbol *Sym = getSymbolPreferLocal(GV: MF->getFunction());
1090 if (Sym != CurrentFnSym) {
1091 cast<MCSymbolELF>(Val: Sym)->setType(ELF::STT_FUNC);
1092 CurrentFnBeginLocal = Sym;
1093 OutStreamer->emitLabel(Symbol: Sym);
1094 if (MAI->hasDotTypeDotSizeDirective())
1095 OutStreamer->emitSymbolAttribute(Symbol: Sym, Attribute: MCSA_ELF_TypeFunction);
1096 }
1097 }
1098}
1099
1100/// emitComments - Pretty-print comments for instructions.
1101static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
1102 const MachineFunction *MF = MI.getMF();
1103 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1104
1105 // Check for spills and reloads
1106
1107 // We assume a single instruction only has a spill or reload, not
1108 // both.
1109 std::optional<unsigned> Size;
1110 if ((Size = MI.getRestoreSize(TII))) {
1111 CommentOS << *Size << "-byte Reload\n";
1112 } else if ((Size = MI.getFoldedRestoreSize(TII))) {
1113 if (*Size) {
1114 if (*Size == unsigned(MemoryLocation::UnknownSize))
1115 CommentOS << "Unknown-size Folded Reload\n";
1116 else
1117 CommentOS << *Size << "-byte Folded Reload\n";
1118 }
1119 } else if ((Size = MI.getSpillSize(TII))) {
1120 CommentOS << *Size << "-byte Spill\n";
1121 } else if ((Size = MI.getFoldedSpillSize(TII))) {
1122 if (*Size) {
1123 if (*Size == unsigned(MemoryLocation::UnknownSize))
1124 CommentOS << "Unknown-size Folded Spill\n";
1125 else
1126 CommentOS << *Size << "-byte Folded Spill\n";
1127 }
1128 }
1129
1130 // Check for spill-induced copies
1131 if (MI.getAsmPrinterFlag(Flag: MachineInstr::ReloadReuse))
1132 CommentOS << " Reload Reuse\n";
1133}
1134
1135/// emitImplicitDef - This method emits the specified machine instruction
1136/// that is an implicit def.
1137void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
1138 Register RegNo = MI->getOperand(i: 0).getReg();
1139
1140 SmallString<128> Str;
1141 raw_svector_ostream OS(Str);
1142 OS << "implicit-def: "
1143 << printReg(Reg: RegNo, TRI: MF->getSubtarget().getRegisterInfo());
1144
1145 OutStreamer->AddComment(T: OS.str());
1146 OutStreamer->addBlankLine();
1147}
1148
1149static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
1150 std::string Str;
1151 raw_string_ostream OS(Str);
1152 OS << "kill:";
1153 for (const MachineOperand &Op : MI->operands()) {
1154 assert(Op.isReg() && "KILL instruction must have only register operands");
1155 OS << ' ' << (Op.isDef() ? "def " : "killed ")
1156 << printReg(Reg: Op.getReg(), TRI: AP.MF->getSubtarget().getRegisterInfo());
1157 }
1158 AP.OutStreamer->AddComment(T: OS.str());
1159 AP.OutStreamer->addBlankLine();
1160}
1161
1162/// emitDebugValueComment - This method handles the target-independent form
1163/// of DBG_VALUE, returning true if it was able to do so. A false return
1164/// means the target will need to handle MI in EmitInstruction.
1165static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
1166 // This code handles only the 4-operand target-independent form.
1167 if (MI->isNonListDebugValue() && MI->getNumOperands() != 4)
1168 return false;
1169
1170 SmallString<128> Str;
1171 raw_svector_ostream OS(Str);
1172 OS << "DEBUG_VALUE: ";
1173
1174 const DILocalVariable *V = MI->getDebugVariable();
1175 if (auto *SP = dyn_cast<DISubprogram>(Val: V->getScope())) {
1176 StringRef Name = SP->getName();
1177 if (!Name.empty())
1178 OS << Name << ":";
1179 }
1180 OS << V->getName();
1181 OS << " <- ";
1182
1183 const DIExpression *Expr = MI->getDebugExpression();
1184 // First convert this to a non-variadic expression if possible, to simplify
1185 // the output.
1186 if (auto NonVariadicExpr = DIExpression::convertToNonVariadicExpression(Expr))
1187 Expr = *NonVariadicExpr;
1188 // Then, output the possibly-simplified expression.
1189 if (Expr->getNumElements()) {
1190 OS << '[';
1191 ListSeparator LS;
1192 for (auto &Op : Expr->expr_ops()) {
1193 OS << LS << dwarf::OperationEncodingString(Encoding: Op.getOp());
1194 for (unsigned I = 0; I < Op.getNumArgs(); ++I)
1195 OS << ' ' << Op.getArg(I);
1196 }
1197 OS << "] ";
1198 }
1199
1200 // Register or immediate value. Register 0 means undef.
1201 for (const MachineOperand &Op : MI->debug_operands()) {
1202 if (&Op != MI->debug_operands().begin())
1203 OS << ", ";
1204 switch (Op.getType()) {
1205 case MachineOperand::MO_FPImmediate: {
1206 APFloat APF = APFloat(Op.getFPImm()->getValueAPF());
1207 Type *ImmTy = Op.getFPImm()->getType();
1208 if (ImmTy->isBFloatTy() || ImmTy->isHalfTy() || ImmTy->isFloatTy() ||
1209 ImmTy->isDoubleTy()) {
1210 OS << APF.convertToDouble();
1211 } else {
1212 // There is no good way to print long double. Convert a copy to
1213 // double. Ah well, it's only a comment.
1214 bool ignored;
1215 APF.convert(ToSemantics: APFloat::IEEEdouble(), RM: APFloat::rmNearestTiesToEven,
1216 losesInfo: &ignored);
1217 OS << "(long double) " << APF.convertToDouble();
1218 }
1219 break;
1220 }
1221 case MachineOperand::MO_Immediate: {
1222 OS << Op.getImm();
1223 break;
1224 }
1225 case MachineOperand::MO_CImmediate: {
1226 Op.getCImm()->getValue().print(OS, isSigned: false /*isSigned*/);
1227 break;
1228 }
1229 case MachineOperand::MO_TargetIndex: {
1230 OS << "!target-index(" << Op.getIndex() << "," << Op.getOffset() << ")";
1231 break;
1232 }
1233 case MachineOperand::MO_Register:
1234 case MachineOperand::MO_FrameIndex: {
1235 Register Reg;
1236 std::optional<StackOffset> Offset;
1237 if (Op.isReg()) {
1238 Reg = Op.getReg();
1239 } else {
1240 const TargetFrameLowering *TFI =
1241 AP.MF->getSubtarget().getFrameLowering();
1242 Offset = TFI->getFrameIndexReference(MF: *AP.MF, FI: Op.getIndex(), FrameReg&: Reg);
1243 }
1244 if (!Reg) {
1245 // Suppress offset, it is not meaningful here.
1246 OS << "undef";
1247 break;
1248 }
1249 // The second operand is only an offset if it's an immediate.
1250 if (MI->isIndirectDebugValue())
1251 Offset = StackOffset::getFixed(Fixed: MI->getDebugOffset().getImm());
1252 if (Offset)
1253 OS << '[';
1254 OS << printReg(Reg, TRI: AP.MF->getSubtarget().getRegisterInfo());
1255 if (Offset)
1256 OS << '+' << Offset->getFixed() << ']';
1257 break;
1258 }
1259 default:
1260 llvm_unreachable("Unknown operand type");
1261 }
1262 }
1263
1264 // NOTE: Want this comment at start of line, don't emit with AddComment.
1265 AP.OutStreamer->emitRawComment(T: OS.str());
1266 return true;
1267}
1268
1269/// This method handles the target-independent form of DBG_LABEL, returning
1270/// true if it was able to do so. A false return means the target will need
1271/// to handle MI in EmitInstruction.
1272static bool emitDebugLabelComment(const MachineInstr *MI, AsmPrinter &AP) {
1273 if (MI->getNumOperands() != 1)
1274 return false;
1275
1276 SmallString<128> Str;
1277 raw_svector_ostream OS(Str);
1278 OS << "DEBUG_LABEL: ";
1279
1280 const DILabel *V = MI->getDebugLabel();
1281 if (auto *SP = dyn_cast<DISubprogram>(
1282 Val: V->getScope()->getNonLexicalBlockFileScope())) {
1283 StringRef Name = SP->getName();
1284 if (!Name.empty())
1285 OS << Name << ":";
1286 }
1287 OS << V->getName();
1288
1289 // NOTE: Want this comment at start of line, don't emit with AddComment.
1290 AP.OutStreamer->emitRawComment(T: OS.str());
1291 return true;
1292}
1293
1294AsmPrinter::CFISection
1295AsmPrinter::getFunctionCFISectionType(const Function &F) const {
1296 // Ignore functions that won't get emitted.
1297 if (F.isDeclarationForLinker())
1298 return CFISection::None;
1299
1300 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
1301 F.needsUnwindTableEntry())
1302 return CFISection::EH;
1303
1304 if (MAI->usesCFIWithoutEH() && F.hasUWTable())
1305 return CFISection::EH;
1306
1307 assert(MMI != nullptr && "Invalid machine module info");
1308 if (MMI->hasDebugInfo() || TM.Options.ForceDwarfFrameSection)
1309 return CFISection::Debug;
1310
1311 return CFISection::None;
1312}
1313
1314AsmPrinter::CFISection
1315AsmPrinter::getFunctionCFISectionType(const MachineFunction &MF) const {
1316 return getFunctionCFISectionType(F: MF.getFunction());
1317}
1318
1319bool AsmPrinter::needsSEHMoves() {
1320 return MAI->usesWindowsCFI() && MF->getFunction().needsUnwindTableEntry();
1321}
1322
1323bool AsmPrinter::usesCFIWithoutEH() const {
1324 return MAI->usesCFIWithoutEH() && ModuleCFISection != CFISection::None;
1325}
1326
1327void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) {
1328 ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
1329 if (!usesCFIWithoutEH() &&
1330 ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
1331 ExceptionHandlingType != ExceptionHandling::ARM)
1332 return;
1333
1334 if (getFunctionCFISectionType(MF: *MF) == CFISection::None)
1335 return;
1336
1337 // If there is no "real" instruction following this CFI instruction, skip
1338 // emitting it; it would be beyond the end of the function's FDE range.
1339 auto *MBB = MI.getParent();
1340 auto I = std::next(x: MI.getIterator());
1341 while (I != MBB->end() && I->isTransient())
1342 ++I;
1343 if (I == MBB->instr_end() &&
1344 MBB->getReverseIterator() == MBB->getParent()->rbegin())
1345 return;
1346
1347 const std::vector<MCCFIInstruction> &Instrs = MF->getFrameInstructions();
1348 unsigned CFIIndex = MI.getOperand(i: 0).getCFIIndex();
1349 const MCCFIInstruction &CFI = Instrs[CFIIndex];
1350 emitCFIInstruction(Inst: CFI);
1351}
1352
1353void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) {
1354 // The operands are the MCSymbol and the frame offset of the allocation.
1355 MCSymbol *FrameAllocSym = MI.getOperand(i: 0).getMCSymbol();
1356 int FrameOffset = MI.getOperand(i: 1).getImm();
1357
1358 // Emit a symbol assignment.
1359 OutStreamer->emitAssignment(Symbol: FrameAllocSym,
1360 Value: MCConstantExpr::create(Value: FrameOffset, Ctx&: OutContext));
1361}
1362
1363/// Returns the BB metadata to be emitted in the SHT_LLVM_BB_ADDR_MAP section
1364/// for a given basic block. This can be used to capture more precise profile
1365/// information.
1366static uint32_t getBBAddrMapMetadata(const MachineBasicBlock &MBB) {
1367 const TargetInstrInfo *TII = MBB.getParent()->getSubtarget().getInstrInfo();
1368 return object::BBAddrMap::BBEntry::Metadata{
1369 .HasReturn: MBB.isReturnBlock(), .HasTailCall: !MBB.empty() && TII->isTailCall(Inst: MBB.back()),
1370 .IsEHPad: MBB.isEHPad(), .CanFallThrough: const_cast<MachineBasicBlock &>(MBB).canFallThrough(),
1371 .HasIndirectBranch: !MBB.empty() && MBB.rbegin()->isIndirectBranch()}
1372 .encode();
1373}
1374
1375static llvm::object::BBAddrMap::Features
1376getBBAddrMapFeature(const MachineFunction &MF, int NumMBBSectionRanges) {
1377 return {.FuncEntryCount: PgoAnalysisMapFeatures.isSet(V: PGOMapFeaturesEnum::FuncEntryCount),
1378 .BBFreq: PgoAnalysisMapFeatures.isSet(V: PGOMapFeaturesEnum::BBFreq),
1379 .BrProb: PgoAnalysisMapFeatures.isSet(V: PGOMapFeaturesEnum::BrProb),
1380 .MultiBBRange: MF.hasBBSections() && NumMBBSectionRanges > 1};
1381}
1382
1383void AsmPrinter::emitBBAddrMapSection(const MachineFunction &MF) {
1384 MCSection *BBAddrMapSection =
1385 getObjFileLowering().getBBAddrMapSection(TextSec: *MF.getSection());
1386 assert(BBAddrMapSection && ".llvm_bb_addr_map section is not initialized.");
1387
1388 const MCSymbol *FunctionSymbol = getFunctionBegin();
1389
1390 OutStreamer->pushSection();
1391 OutStreamer->switchSection(Section: BBAddrMapSection);
1392 OutStreamer->AddComment(T: "version");
1393 uint8_t BBAddrMapVersion = OutStreamer->getContext().getBBAddrMapVersion();
1394 OutStreamer->emitInt8(Value: BBAddrMapVersion);
1395 OutStreamer->AddComment(T: "feature");
1396 auto Features = getBBAddrMapFeature(MF, NumMBBSectionRanges: MBBSectionRanges.size());
1397 OutStreamer->emitInt8(Value: Features.encode());
1398 // Emit BB Information for each basic block in the function.
1399 if (Features.MultiBBRange) {
1400 OutStreamer->AddComment(T: "number of basic block ranges");
1401 OutStreamer->emitULEB128IntValue(Value: MBBSectionRanges.size());
1402 }
1403 // Number of blocks in each MBB section.
1404 MapVector<unsigned, unsigned> MBBSectionNumBlocks;
1405 const MCSymbol *PrevMBBEndSymbol = nullptr;
1406 if (!Features.MultiBBRange) {
1407 OutStreamer->AddComment(T: "function address");
1408 OutStreamer->emitSymbolValue(Sym: FunctionSymbol, Size: getPointerSize());
1409 OutStreamer->AddComment(T: "number of basic blocks");
1410 OutStreamer->emitULEB128IntValue(Value: MF.size());
1411 PrevMBBEndSymbol = FunctionSymbol;
1412 } else {
1413 unsigned BBCount = 0;
1414 for (const MachineBasicBlock &MBB : MF) {
1415 BBCount++;
1416 if (MBB.isEndSection()) {
1417 // Store each section's basic block count when it ends.
1418 MBBSectionNumBlocks[MBB.getSectionIDNum()] = BBCount;
1419 // Reset the count for the next section.
1420 BBCount = 0;
1421 }
1422 }
1423 }
1424 // Emit the BB entry for each basic block in the function.
1425 for (const MachineBasicBlock &MBB : MF) {
1426 const MCSymbol *MBBSymbol =
1427 MBB.isEntryBlock() ? FunctionSymbol : MBB.getSymbol();
1428 bool IsBeginSection =
1429 Features.MultiBBRange && (MBB.isBeginSection() || MBB.isEntryBlock());
1430 if (IsBeginSection) {
1431 OutStreamer->AddComment(T: "base address");
1432 OutStreamer->emitSymbolValue(Sym: MBBSymbol, Size: getPointerSize());
1433 OutStreamer->AddComment(T: "number of basic blocks");
1434 OutStreamer->emitULEB128IntValue(
1435 Value: MBBSectionNumBlocks[MBB.getSectionIDNum()]);
1436 PrevMBBEndSymbol = MBBSymbol;
1437 }
1438 // TODO: Remove this check when version 1 is deprecated.
1439 if (BBAddrMapVersion > 1) {
1440 OutStreamer->AddComment(T: "BB id");
1441 // Emit the BB ID for this basic block.
1442 // We only emit BaseID since CloneID is unset for
1443 // basic-block-sections=labels.
1444 // TODO: Emit the full BBID when labels and sections can be mixed
1445 // together.
1446 OutStreamer->emitULEB128IntValue(Value: MBB.getBBID()->BaseID);
1447 }
1448 // Emit the basic block offset relative to the end of the previous block.
1449 // This is zero unless the block is padded due to alignment.
1450 emitLabelDifferenceAsULEB128(Hi: MBBSymbol, Lo: PrevMBBEndSymbol);
1451 // Emit the basic block size. When BBs have alignments, their size cannot
1452 // always be computed from their offsets.
1453 emitLabelDifferenceAsULEB128(Hi: MBB.getEndSymbol(), Lo: MBBSymbol);
1454 // Emit the Metadata.
1455 OutStreamer->emitULEB128IntValue(Value: getBBAddrMapMetadata(MBB));
1456 PrevMBBEndSymbol = MBB.getEndSymbol();
1457 }
1458
1459 if (Features.hasPGOAnalysis()) {
1460 assert(BBAddrMapVersion >= 2 &&
1461 "PGOAnalysisMap only supports version 2 or later");
1462
1463 if (Features.FuncEntryCount) {
1464 OutStreamer->AddComment(T: "function entry count");
1465 auto MaybeEntryCount = MF.getFunction().getEntryCount();
1466 OutStreamer->emitULEB128IntValue(
1467 Value: MaybeEntryCount ? MaybeEntryCount->getCount() : 0);
1468 }
1469 const MachineBlockFrequencyInfo *MBFI =
1470 Features.BBFreq
1471 ? &getAnalysis<LazyMachineBlockFrequencyInfoPass>().getBFI()
1472 : nullptr;
1473 const MachineBranchProbabilityInfo *MBPI =
1474 Features.BrProb ? &getAnalysis<MachineBranchProbabilityInfo>()
1475 : nullptr;
1476
1477 if (Features.BBFreq || Features.BrProb) {
1478 for (const MachineBasicBlock &MBB : MF) {
1479 if (Features.BBFreq) {
1480 OutStreamer->AddComment(T: "basic block frequency");
1481 OutStreamer->emitULEB128IntValue(
1482 Value: MBFI->getBlockFreq(MBB: &MBB).getFrequency());
1483 }
1484 if (Features.BrProb) {
1485 unsigned SuccCount = MBB.succ_size();
1486 OutStreamer->AddComment(T: "basic block successor count");
1487 OutStreamer->emitULEB128IntValue(Value: SuccCount);
1488 for (const MachineBasicBlock *SuccMBB : MBB.successors()) {
1489 OutStreamer->AddComment(T: "successor BB ID");
1490 OutStreamer->emitULEB128IntValue(Value: SuccMBB->getBBID()->BaseID);
1491 OutStreamer->AddComment(T: "successor branch probability");
1492 OutStreamer->emitULEB128IntValue(
1493 Value: MBPI->getEdgeProbability(Src: &MBB, Dst: SuccMBB).getNumerator());
1494 }
1495 }
1496 }
1497 }
1498 }
1499
1500 OutStreamer->popSection();
1501}
1502
1503void AsmPrinter::emitKCFITrapEntry(const MachineFunction &MF,
1504 const MCSymbol *Symbol) {
1505 MCSection *Section =
1506 getObjFileLowering().getKCFITrapSection(TextSec: *MF.getSection());
1507 if (!Section)
1508 return;
1509
1510 OutStreamer->pushSection();
1511 OutStreamer->switchSection(Section);
1512
1513 MCSymbol *Loc = OutContext.createLinkerPrivateTempSymbol();
1514 OutStreamer->emitLabel(Symbol: Loc);
1515 OutStreamer->emitAbsoluteSymbolDiff(Hi: Symbol, Lo: Loc, Size: 4);
1516
1517 OutStreamer->popSection();
1518}
1519
1520void AsmPrinter::emitKCFITypeId(const MachineFunction &MF) {
1521 const Function &F = MF.getFunction();
1522 if (const MDNode *MD = F.getMetadata(KindID: LLVMContext::MD_kcfi_type))
1523 emitGlobalConstant(DL: F.getParent()->getDataLayout(),
1524 CV: mdconst::extract<ConstantInt>(MD: MD->getOperand(I: 0)));
1525}
1526
1527void AsmPrinter::emitPseudoProbe(const MachineInstr &MI) {
1528 if (PP) {
1529 auto GUID = MI.getOperand(i: 0).getImm();
1530 auto Index = MI.getOperand(i: 1).getImm();
1531 auto Type = MI.getOperand(i: 2).getImm();
1532 auto Attr = MI.getOperand(i: 3).getImm();
1533 DILocation *DebugLoc = MI.getDebugLoc();
1534 PP->emitPseudoProbe(Guid: GUID, Index, Type, Attr, DebugLoc);
1535 }
1536}
1537
1538void AsmPrinter::emitStackSizeSection(const MachineFunction &MF) {
1539 if (!MF.getTarget().Options.EmitStackSizeSection)
1540 return;
1541
1542 MCSection *StackSizeSection =
1543 getObjFileLowering().getStackSizesSection(TextSec: *getCurrentSection());
1544 if (!StackSizeSection)
1545 return;
1546
1547 const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1548 // Don't emit functions with dynamic stack allocations.
1549 if (FrameInfo.hasVarSizedObjects())
1550 return;
1551
1552 OutStreamer->pushSection();
1553 OutStreamer->switchSection(Section: StackSizeSection);
1554
1555 const MCSymbol *FunctionSymbol = getFunctionBegin();
1556 uint64_t StackSize =
1557 FrameInfo.getStackSize() + FrameInfo.getUnsafeStackSize();
1558 OutStreamer->emitSymbolValue(Sym: FunctionSymbol, Size: TM.getProgramPointerSize());
1559 OutStreamer->emitULEB128IntValue(Value: StackSize);
1560
1561 OutStreamer->popSection();
1562}
1563
1564void AsmPrinter::emitStackUsage(const MachineFunction &MF) {
1565 const std::string &OutputFilename = MF.getTarget().Options.StackUsageOutput;
1566
1567 // OutputFilename empty implies -fstack-usage is not passed.
1568 if (OutputFilename.empty())
1569 return;
1570
1571 const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1572 uint64_t StackSize =
1573 FrameInfo.getStackSize() + FrameInfo.getUnsafeStackSize();
1574
1575 if (StackUsageStream == nullptr) {
1576 std::error_code EC;
1577 StackUsageStream =
1578 std::make_unique<raw_fd_ostream>(args: OutputFilename, args&: EC, args: sys::fs::OF_Text);
1579 if (EC) {
1580 errs() << "Could not open file: " << EC.message();
1581 return;
1582 }
1583 }
1584
1585 if (const DISubprogram *DSP = MF.getFunction().getSubprogram())
1586 *StackUsageStream << DSP->getFilename() << ':' << DSP->getLine();
1587 else
1588 *StackUsageStream << MF.getFunction().getParent()->getName();
1589
1590 *StackUsageStream << ':' << MF.getName() << '\t' << StackSize << '\t';
1591 if (FrameInfo.hasVarSizedObjects())
1592 *StackUsageStream << "dynamic\n";
1593 else
1594 *StackUsageStream << "static\n";
1595}
1596
1597void AsmPrinter::emitPCSectionsLabel(const MachineFunction &MF,
1598 const MDNode &MD) {
1599 MCSymbol *S = MF.getContext().createTempSymbol(Name: "pcsection");
1600 OutStreamer->emitLabel(Symbol: S);
1601 PCSectionsSymbols[&MD].emplace_back(Args&: S);
1602}
1603
1604void AsmPrinter::emitPCSections(const MachineFunction &MF) {
1605 const Function &F = MF.getFunction();
1606 if (PCSectionsSymbols.empty() && !F.hasMetadata(KindID: LLVMContext::MD_pcsections))
1607 return;
1608
1609 const CodeModel::Model CM = MF.getTarget().getCodeModel();
1610 const unsigned RelativeRelocSize =
1611 (CM == CodeModel::Medium || CM == CodeModel::Large) ? getPointerSize()
1612 : 4;
1613
1614 // Switch to PCSection, short-circuiting the common case where the current
1615 // section is still valid (assume most MD_pcsections contain just 1 section).
1616 auto SwitchSection = [&, Prev = StringRef()](const StringRef &Sec) mutable {
1617 if (Sec == Prev)
1618 return;
1619 MCSection *S = getObjFileLowering().getPCSection(Name: Sec, TextSec: MF.getSection());
1620 assert(S && "PC section is not initialized");
1621 OutStreamer->switchSection(Section: S);
1622 Prev = Sec;
1623 };
1624 // Emit symbols into sections and data as specified in the pcsections MDNode.
1625 auto EmitForMD = [&](const MDNode &MD, ArrayRef<const MCSymbol *> Syms,
1626 bool Deltas) {
1627 // Expect the first operand to be a section name. After that, a tuple of
1628 // constants may appear, which will simply be emitted into the current
1629 // section (the user of MD_pcsections decides the format of encoded data).
1630 assert(isa<MDString>(MD.getOperand(0)) && "first operand not a string");
1631 bool ConstULEB128 = false;
1632 for (const MDOperand &MDO : MD.operands()) {
1633 if (auto *S = dyn_cast<MDString>(Val: MDO)) {
1634 // Found string, start of new section!
1635 // Find options for this section "<section>!<opts>" - supported options:
1636 // C = Compress constant integers of size 2-8 bytes as ULEB128.
1637 const StringRef SecWithOpt = S->getString();
1638 const size_t OptStart = SecWithOpt.find(C: '!'); // likely npos
1639 const StringRef Sec = SecWithOpt.substr(Start: 0, N: OptStart);
1640 const StringRef Opts = SecWithOpt.substr(Start: OptStart); // likely empty
1641 ConstULEB128 = Opts.contains(C: 'C');
1642#ifndef NDEBUG
1643 for (char O : Opts)
1644 assert((O == '!' || O == 'C') && "Invalid !pcsections options");
1645#endif
1646 SwitchSection(Sec);
1647 const MCSymbol *Prev = Syms.front();
1648 for (const MCSymbol *Sym : Syms) {
1649 if (Sym == Prev || !Deltas) {
1650 // Use the entry itself as the base of the relative offset.
1651 MCSymbol *Base = MF.getContext().createTempSymbol(Name: "pcsection_base");
1652 OutStreamer->emitLabel(Symbol: Base);
1653 // Emit relative relocation `addr - base`, which avoids a dynamic
1654 // relocation in the final binary. User will get the address with
1655 // `base + addr`.
1656 emitLabelDifference(Hi: Sym, Lo: Base, Size: RelativeRelocSize);
1657 } else {
1658 // Emit delta between symbol and previous symbol.
1659 if (ConstULEB128)
1660 emitLabelDifferenceAsULEB128(Hi: Sym, Lo: Prev);
1661 else
1662 emitLabelDifference(Hi: Sym, Lo: Prev, Size: 4);
1663 }
1664 Prev = Sym;
1665 }
1666 } else {
1667 // Emit auxiliary data after PC.
1668 assert(isa<MDNode>(MDO) && "expecting either string or tuple");
1669 const auto *AuxMDs = cast<MDNode>(Val: MDO);
1670 for (const MDOperand &AuxMDO : AuxMDs->operands()) {
1671 assert(isa<ConstantAsMetadata>(AuxMDO) && "expecting a constant");
1672 const Constant *C = cast<ConstantAsMetadata>(Val: AuxMDO)->getValue();
1673 const DataLayout &DL = F.getParent()->getDataLayout();
1674 const uint64_t Size = DL.getTypeStoreSize(Ty: C->getType());
1675
1676 if (auto *CI = dyn_cast<ConstantInt>(Val: C);
1677 CI && ConstULEB128 && Size > 1 && Size <= 8) {
1678 emitULEB128(Value: CI->getZExtValue());
1679 } else {
1680 emitGlobalConstant(DL, CV: C);
1681 }
1682 }
1683 }
1684 }
1685 };
1686
1687 OutStreamer->pushSection();
1688 // Emit PCs for function start and function size.
1689 if (const MDNode *MD = F.getMetadata(KindID: LLVMContext::MD_pcsections))
1690 EmitForMD(*MD, {getFunctionBegin(), getFunctionEnd()}, true);
1691 // Emit PCs for instructions collected.
1692 for (const auto &MS : PCSectionsSymbols)
1693 EmitForMD(*MS.first, MS.second, false);
1694 OutStreamer->popSection();
1695 PCSectionsSymbols.clear();
1696}
1697
1698/// Returns true if function begin and end labels should be emitted.
1699static bool needFuncLabels(const MachineFunction &MF) {
1700 MachineModuleInfo &MMI = MF.getMMI();
1701 if (!MF.getLandingPads().empty() || MF.hasEHFunclets() ||
1702 MMI.hasDebugInfo() ||
1703 MF.getFunction().hasMetadata(KindID: LLVMContext::MD_pcsections))
1704 return true;
1705
1706 // We might emit an EH table that uses function begin and end labels even if
1707 // we don't have any landingpads.
1708 if (!MF.getFunction().hasPersonalityFn())
1709 return false;
1710 return !isNoOpWithoutInvoke(
1711 Pers: classifyEHPersonality(Pers: MF.getFunction().getPersonalityFn()));
1712}
1713
1714/// EmitFunctionBody - This method emits the body and trailer for a
1715/// function.
1716void AsmPrinter::emitFunctionBody() {
1717 emitFunctionHeader();
1718
1719 // Emit target-specific gunk before the function body.
1720 emitFunctionBodyStart();
1721
1722 if (isVerbose()) {
1723 // Get MachineDominatorTree or compute it on the fly if it's unavailable
1724 MDT = getAnalysisIfAvailable<MachineDominatorTree>();
1725 if (!MDT) {
1726 OwnedMDT = std::make_unique<MachineDominatorTree>();
1727 OwnedMDT->getBase().recalculate(Func&: *MF);
1728 MDT = OwnedMDT.get();
1729 }
1730
1731 // Get MachineLoopInfo or compute it on the fly if it's unavailable
1732 MLI = getAnalysisIfAvailable<MachineLoopInfo>();
1733 if (!MLI) {
1734 OwnedMLI = std::make_unique<MachineLoopInfo>();
1735 OwnedMLI->getBase().analyze(DomTree: MDT->getBase());
1736 MLI = OwnedMLI.get();
1737 }
1738 }
1739
1740 // Print out code for the function.
1741 bool HasAnyRealCode = false;
1742 int NumInstsInFunction = 0;
1743 bool IsEHa = MMI->getModule()->getModuleFlag(Key: "eh-asynch");
1744
1745 bool CanDoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1746 for (auto &MBB : *MF) {
1747 // Print a label for the basic block.
1748 emitBasicBlockStart(MBB);
1749 DenseMap<StringRef, unsigned> MnemonicCounts;
1750 for (auto &MI : MBB) {
1751 // Print the assembly for the instruction.
1752 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
1753 !MI.isDebugInstr()) {
1754 HasAnyRealCode = true;
1755 ++NumInstsInFunction;
1756 }
1757
1758 // If there is a pre-instruction symbol, emit a label for it here.
1759 if (MCSymbol *S = MI.getPreInstrSymbol())
1760 OutStreamer->emitLabel(Symbol: S);
1761
1762 if (MDNode *MD = MI.getPCSections())
1763 emitPCSectionsLabel(MF: *MF, MD: *MD);
1764
1765 for (const HandlerInfo &HI : Handlers) {
1766 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1767 HI.TimerGroupDescription, TimePassesIsEnabled);
1768 HI.Handler->beginInstruction(MI: &MI);
1769 }
1770
1771 if (isVerbose())
1772 emitComments(MI, CommentOS&: OutStreamer->getCommentOS());
1773
1774 switch (MI.getOpcode()) {
1775 case TargetOpcode::CFI_INSTRUCTION:
1776 emitCFIInstruction(MI);
1777 break;
1778 case TargetOpcode::LOCAL_ESCAPE:
1779 emitFrameAlloc(MI);
1780 break;
1781 case TargetOpcode::ANNOTATION_LABEL:
1782 case TargetOpcode::GC_LABEL:
1783 OutStreamer->emitLabel(Symbol: MI.getOperand(i: 0).getMCSymbol());
1784 break;
1785 case TargetOpcode::EH_LABEL:
1786 OutStreamer->emitLabel(Symbol: MI.getOperand(i: 0).getMCSymbol());
1787 // For AsynchEH, insert a Nop if followed by a trap inst
1788 // Or the exception won't be caught.
1789 // (see MCConstantExpr::create(1,..) in WinException.cpp)
1790 // Ignore SDiv/UDiv because a DIV with Const-0 divisor
1791 // must have being turned into an UndefValue.
1792 // Div with variable opnds won't be the first instruction in
1793 // an EH region as it must be led by at least a Load
1794 {
1795 auto MI2 = std::next(x: MI.getIterator());
1796 if (IsEHa && MI2 != MBB.end() &&
1797 (MI2->mayLoadOrStore() || MI2->mayRaiseFPException()))
1798 emitNops(N: 1);
1799 }
1800 break;
1801 case TargetOpcode::INLINEASM:
1802 case TargetOpcode::INLINEASM_BR:
1803 emitInlineAsm(MI: &MI);
1804 break;
1805 case TargetOpcode::DBG_VALUE:
1806 case TargetOpcode::DBG_VALUE_LIST:
1807 if (isVerbose()) {
1808 if (!emitDebugValueComment(MI: &MI, AP&: *this))
1809 emitInstruction(&MI);
1810 }
1811 break;
1812 case TargetOpcode::DBG_INSTR_REF:
1813 // This instruction reference will have been resolved to a machine
1814 // location, and a nearby DBG_VALUE created. We can safely ignore
1815 // the instruction reference.
1816 break;
1817 case TargetOpcode::DBG_PHI:
1818 // This instruction is only used to label a program point, it's purely
1819 // meta information.
1820 break;
1821 case TargetOpcode::DBG_LABEL:
1822 if (isVerbose()) {
1823 if (!emitDebugLabelComment(MI: &MI, AP&: *this))
1824 emitInstruction(&MI);
1825 }
1826 break;
1827 case TargetOpcode::IMPLICIT_DEF:
1828 if (isVerbose()) emitImplicitDef(MI: &MI);
1829 break;
1830 case TargetOpcode::KILL:
1831 if (isVerbose()) emitKill(MI: &MI, AP&: *this);
1832 break;
1833 case TargetOpcode::PSEUDO_PROBE:
1834 emitPseudoProbe(MI);
1835 break;
1836 case TargetOpcode::ARITH_FENCE:
1837 if (isVerbose())
1838 OutStreamer->emitRawComment(T: "ARITH_FENCE");
1839 break;
1840 case TargetOpcode::MEMBARRIER:
1841 OutStreamer->emitRawComment(T: "MEMBARRIER");
1842 break;
1843 case TargetOpcode::JUMP_TABLE_DEBUG_INFO:
1844 // This instruction is only used to note jump table debug info, it's
1845 // purely meta information.
1846 break;
1847 default:
1848 emitInstruction(&MI);
1849 if (CanDoExtraAnalysis) {
1850 MCInst MCI;
1851 MCI.setOpcode(MI.getOpcode());
1852 auto Name = OutStreamer->getMnemonic(MI&: MCI);
1853 auto I = MnemonicCounts.insert(KV: {Name, 0u});
1854 I.first->second++;
1855 }
1856 break;
1857 }
1858
1859 // If there is a post-instruction symbol, emit a label for it here.
1860 if (MCSymbol *S = MI.getPostInstrSymbol())
1861 OutStreamer->emitLabel(Symbol: S);
1862
1863 for (const HandlerInfo &HI : Handlers) {
1864 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1865 HI.TimerGroupDescription, TimePassesIsEnabled);
1866 HI.Handler->endInstruction();
1867 }
1868 }
1869
1870 // We must emit temporary symbol for the end of this basic block, if either
1871 // we have BBLabels enabled or if this basic blocks marks the end of a
1872 // section.
1873 if (MF->hasBBLabels() || MF->getTarget().Options.BBAddrMap ||
1874 (MAI->hasDotTypeDotSizeDirective() && MBB.isEndSection()))
1875 OutStreamer->emitLabel(Symbol: MBB.getEndSymbol());
1876
1877 if (MBB.isEndSection()) {
1878 // The size directive for the section containing the entry block is
1879 // handled separately by the function section.
1880 if (!MBB.sameSection(MBB: &MF->front())) {
1881 if (MAI->hasDotTypeDotSizeDirective()) {
1882 // Emit the size directive for the basic block section.
1883 const MCExpr *SizeExp = MCBinaryExpr::createSub(
1884 LHS: MCSymbolRefExpr::create(Symbol: MBB.getEndSymbol(), Ctx&: OutContext),
1885 RHS: MCSymbolRefExpr::create(Symbol: CurrentSectionBeginSym, Ctx&: OutContext),
1886 Ctx&: OutContext);
1887 OutStreamer->emitELFSize(Symbol: CurrentSectionBeginSym, Value: SizeExp);
1888 }
1889 MBBSectionRanges[MBB.getSectionIDNum()] =
1890 MBBSectionRange{.BeginLabel: CurrentSectionBeginSym, .EndLabel: MBB.getEndSymbol()};
1891 }
1892 }
1893 emitBasicBlockEnd(MBB);
1894
1895 if (CanDoExtraAnalysis) {
1896 // Skip empty blocks.
1897 if (MBB.empty())
1898 continue;
1899
1900 MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionMix",
1901 MBB.begin()->getDebugLoc(), &MBB);
1902
1903 // Generate instruction mix remark. First, sort counts in descending order
1904 // by count and name.
1905 SmallVector<std::pair<StringRef, unsigned>, 128> MnemonicVec;
1906 for (auto &KV : MnemonicCounts)
1907 MnemonicVec.emplace_back(Args&: KV.first, Args&: KV.second);
1908
1909 sort(C&: MnemonicVec, Comp: [](const std::pair<StringRef, unsigned> &A,
1910 const std::pair<StringRef, unsigned> &B) {
1911 if (A.second > B.second)
1912 return true;
1913 if (A.second == B.second)
1914 return StringRef(A.first) < StringRef(B.first);
1915 return false;
1916 });
1917 R << "BasicBlock: " << ore::NV("BasicBlock", MBB.getName()) << "\n";
1918 for (auto &KV : MnemonicVec) {
1919 auto Name = (Twine("INST_") + getToken(Source: KV.first.trim()).first).str();
1920 R << KV.first << ": " << ore::NV(Name, KV.second) << "\n";
1921 }
1922 ORE->emit(OptDiag&: R);
1923 }
1924 }
1925
1926 EmittedInsts += NumInstsInFunction;
1927 MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionCount",
1928 MF->getFunction().getSubprogram(),
1929 &MF->front());
1930 R << ore::NV("NumInstructions", NumInstsInFunction)
1931 << " instructions in function";
1932 ORE->emit(OptDiag&: R);
1933
1934 // If the function is empty and the object file uses .subsections_via_symbols,
1935 // then we need to emit *something* to the function body to prevent the
1936 // labels from collapsing together. Just emit a noop.
1937 // Similarly, don't emit empty functions on Windows either. It can lead to
1938 // duplicate entries (two functions with the same RVA) in the Guard CF Table
1939 // after linking, causing the kernel not to load the binary:
1940 // https://developercommunity.visualstudio.com/content/problem/45366/vc-linker-creates-invalid-dll-with-clang-cl.html
1941 // FIXME: Hide this behind some API in e.g. MCAsmInfo or MCTargetStreamer.
1942 const Triple &TT = TM.getTargetTriple();
1943 if (!HasAnyRealCode && (MAI->hasSubsectionsViaSymbols() ||
1944 (TT.isOSWindows() && TT.isOSBinFormatCOFF()))) {
1945 MCInst Noop = MF->getSubtarget().getInstrInfo()->getNop();
1946
1947 // Targets can opt-out of emitting the noop here by leaving the opcode
1948 // unspecified.
1949 if (Noop.getOpcode()) {
1950 OutStreamer->AddComment(T: "avoids zero-length function");
1951 emitNops(N: 1);
1952 }
1953 }
1954
1955 // Switch to the original section in case basic block sections was used.
1956 OutStreamer->switchSection(Section: MF->getSection());
1957
1958 const Function &F = MF->getFunction();
1959 for (const auto &BB : F) {
1960 if (!BB.hasAddressTaken())
1961 continue;
1962 MCSymbol *Sym = GetBlockAddressSymbol(BB: &BB);
1963 if (Sym->isDefined())
1964 continue;
1965 OutStreamer->AddComment(T: "Address of block that was removed by CodeGen");
1966 OutStreamer->emitLabel(Symbol: Sym);
1967 }
1968
1969 // Emit target-specific gunk after the function body.
1970 emitFunctionBodyEnd();
1971
1972 // Even though wasm supports .type and .size in general, function symbols
1973 // are automatically sized.
1974 bool EmitFunctionSize = MAI->hasDotTypeDotSizeDirective() && !TT.isWasm();
1975
1976 if (needFuncLabels(MF: *MF) || EmitFunctionSize) {
1977 // Create a symbol for the end of function.
1978 CurrentFnEnd = createTempSymbol(Name: "func_end");
1979 OutStreamer->emitLabel(Symbol: CurrentFnEnd);
1980 }
1981
1982 // If the target wants a .size directive for the size of the function, emit
1983 // it.
1984 if (EmitFunctionSize) {
1985 // We can get the size as difference between the function label and the
1986 // temp label.
1987 const MCExpr *SizeExp = MCBinaryExpr::createSub(
1988 LHS: MCSymbolRefExpr::create(Symbol: CurrentFnEnd, Ctx&: OutContext),
1989 RHS: MCSymbolRefExpr::create(Symbol: CurrentFnSymForSize, Ctx&: OutContext), Ctx&: OutContext);
1990 OutStreamer->emitELFSize(Symbol: CurrentFnSym, Value: SizeExp);
1991 if (CurrentFnBeginLocal)
1992 OutStreamer->emitELFSize(Symbol: CurrentFnBeginLocal, Value: SizeExp);
1993 }
1994
1995 // Call endBasicBlockSection on the last block now, if it wasn't already
1996 // called.
1997 if (!MF->back().isEndSection()) {
1998 for (const HandlerInfo &HI : Handlers) {
1999 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
2000 HI.TimerGroupDescription, TimePassesIsEnabled);
2001 HI.Handler->endBasicBlockSection(MBB: MF->back());
2002 }
2003 }
2004 for (const HandlerInfo &HI : Handlers) {
2005 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
2006 HI.TimerGroupDescription, TimePassesIsEnabled);
2007 HI.Handler->markFunctionEnd();
2008 }
2009
2010 MBBSectionRanges[MF->front().getSectionIDNum()] =
2011 MBBSectionRange{.BeginLabel: CurrentFnBegin, .EndLabel: CurrentFnEnd};
2012
2013 // Print out jump tables referenced by the function.
2014 emitJumpTableInfo();
2015
2016 // Emit post-function debug and/or EH information.
2017 for (const HandlerInfo &HI : Handlers) {
2018 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
2019 HI.TimerGroupDescription, TimePassesIsEnabled);
2020 HI.Handler->endFunction(MF);
2021 }
2022
2023 // Emit section containing BB address offsets and their metadata, when
2024 // BB labels are requested for this function. Skip empty functions.
2025 if (HasAnyRealCode) {
2026 if (MF->hasBBLabels() || MF->getTarget().Options.BBAddrMap)
2027 emitBBAddrMapSection(MF: *MF);
2028 else if (PgoAnalysisMapFeatures.getBits() != 0)
2029 MF->getContext().reportWarning(
2030 L: SMLoc(), Msg: "pgo-analysis-map is enabled for function " + MF->getName() +
2031 " but it does not have labels");
2032 }
2033
2034 // Emit sections containing instruction and function PCs.
2035 emitPCSections(MF: *MF);
2036
2037 // Emit section containing stack size metadata.
2038 emitStackSizeSection(MF: *MF);
2039
2040 // Emit .su file containing function stack size information.
2041 emitStackUsage(MF: *MF);
2042
2043 emitPatchableFunctionEntries();
2044
2045 if (isVerbose())
2046 OutStreamer->getCommentOS() << "-- End function\n";
2047
2048 OutStreamer->addBlankLine();
2049}
2050
2051/// Compute the number of Global Variables that uses a Constant.
2052static unsigned getNumGlobalVariableUses(const Constant *C) {
2053 if (!C)
2054 return 0;
2055
2056 if (isa<GlobalVariable>(Val: C))
2057 return 1;
2058
2059 unsigned NumUses = 0;
2060 for (const auto *CU : C->users())
2061 NumUses += getNumGlobalVariableUses(C: dyn_cast<Constant>(Val: CU));
2062
2063 return NumUses;
2064}
2065
2066/// Only consider global GOT equivalents if at least one user is a
2067/// cstexpr inside an initializer of another global variables. Also, don't
2068/// handle cstexpr inside instructions. During global variable emission,
2069/// candidates are skipped and are emitted later in case at least one cstexpr
2070/// isn't replaced by a PC relative GOT entry access.
2071static bool isGOTEquivalentCandidate(const GlobalVariable *GV,
2072 unsigned &NumGOTEquivUsers) {
2073 // Global GOT equivalents are unnamed private globals with a constant
2074 // pointer initializer to another global symbol. They must point to a
2075 // GlobalVariable or Function, i.e., as GlobalValue.
2076 if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() ||
2077 !GV->isConstant() || !GV->isDiscardableIfUnused() ||
2078 !isa<GlobalValue>(Val: GV->getOperand(i_nocapture: 0)))
2079 return false;
2080
2081 // To be a got equivalent, at least one of its users need to be a constant
2082 // expression used by another global variable.
2083 for (const auto *U : GV->users())
2084 NumGOTEquivUsers += getNumGlobalVariableUses(C: dyn_cast<Constant>(Val: U));
2085
2086 return NumGOTEquivUsers > 0;
2087}
2088
2089/// Unnamed constant global variables solely contaning a pointer to
2090/// another globals variable is equivalent to a GOT table entry; it contains the
2091/// the address of another symbol. Optimize it and replace accesses to these
2092/// "GOT equivalents" by using the GOT entry for the final global instead.
2093/// Compute GOT equivalent candidates among all global variables to avoid
2094/// emitting them if possible later on, after it use is replaced by a GOT entry
2095/// access.
2096void AsmPrinter::computeGlobalGOTEquivs(Module &M) {
2097 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
2098 return;
2099
2100 for (const auto &G : M.globals()) {
2101 unsigned NumGOTEquivUsers = 0;
2102 if (!isGOTEquivalentCandidate(GV: &G, NumGOTEquivUsers))
2103 continue;
2104
2105 const MCSymbol *GOTEquivSym = getSymbol(GV: &G);
2106 GlobalGOTEquivs[GOTEquivSym] = std::make_pair(x: &G, y&: NumGOTEquivUsers);
2107 }
2108}
2109
2110/// Constant expressions using GOT equivalent globals may not be eligible
2111/// for PC relative GOT entry conversion, in such cases we need to emit such
2112/// globals we previously omitted in EmitGlobalVariable.
2113void AsmPrinter::emitGlobalGOTEquivs() {
2114 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
2115 return;
2116
2117 SmallVector<const GlobalVariable *, 8> FailedCandidates;
2118 for (auto &I : GlobalGOTEquivs) {
2119 const GlobalVariable *GV = I.second.first;
2120 unsigned Cnt = I.second.second;
2121 if (Cnt)
2122 FailedCandidates.push_back(Elt: GV);
2123 }
2124 GlobalGOTEquivs.clear();
2125
2126 for (const auto *GV : FailedCandidates)
2127 emitGlobalVariable(GV);
2128}
2129
2130void AsmPrinter::emitGlobalAlias(const Module &M, const GlobalAlias &GA) {
2131 MCSymbol *Name = getSymbol(GV: &GA);
2132 bool IsFunction = GA.getValueType()->isFunctionTy();
2133 // Treat bitcasts of functions as functions also. This is important at least
2134 // on WebAssembly where object and function addresses can't alias each other.
2135 if (!IsFunction)
2136 IsFunction = isa<Function>(Val: GA.getAliasee()->stripPointerCasts());
2137
2138 // AIX's assembly directive `.set` is not usable for aliasing purpose,
2139 // so AIX has to use the extra-label-at-definition strategy. At this
2140 // point, all the extra label is emitted, we just have to emit linkage for
2141 // those labels.
2142 if (TM.getTargetTriple().isOSBinFormatXCOFF()) {
2143 assert(MAI->hasVisibilityOnlyWithLinkage() &&
2144 "Visibility should be handled with emitLinkage() on AIX.");
2145
2146 // Linkage for alias of global variable has been emitted.
2147 if (isa<GlobalVariable>(Val: GA.getAliaseeObject()))
2148 return;
2149
2150 emitLinkage(GV: &GA, GVSym: Name);
2151 // If it's a function, also emit linkage for aliases of function entry
2152 // point.
2153 if (IsFunction)
2154 emitLinkage(GV: &GA,
2155 GVSym: getObjFileLowering().getFunctionEntryPointSymbol(Func: &GA, TM));
2156 return;
2157 }
2158
2159 if (GA.hasExternalLinkage() || !MAI->getWeakRefDirective())
2160 OutStreamer->emitSymbolAttribute(Symbol: Name, Attribute: MCSA_Global);
2161 else if (GA.hasWeakLinkage() || GA.hasLinkOnceLinkage())
2162 OutStreamer->emitSymbolAttribute(Symbol: Name, Attribute: MCSA_WeakReference);
2163 else
2164 assert(GA.hasLocalLinkage() && "Invalid alias linkage");
2165
2166 // Set the symbol type to function if the alias has a function type.
2167 // This affects codegen when the aliasee is not a function.
2168 if (IsFunction) {
2169 OutStreamer->emitSymbolAttribute(Symbol: Name, Attribute: MCSA_ELF_TypeFunction);
2170 if (TM.getTargetTriple().isOSBinFormatCOFF()) {
2171 OutStreamer->beginCOFFSymbolDef(Symbol: Name);
2172 OutStreamer->emitCOFFSymbolStorageClass(
2173 StorageClass: GA.hasLocalLinkage() ? COFF::IMAGE_SYM_CLASS_STATIC
2174 : COFF::IMAGE_SYM_CLASS_EXTERNAL);
2175 OutStreamer->emitCOFFSymbolType(Type: COFF::IMAGE_SYM_DTYPE_FUNCTION
2176 << COFF::SCT_COMPLEX_TYPE_SHIFT);
2177 OutStreamer->endCOFFSymbolDef();
2178 }
2179 }
2180
2181 emitVisibility(Sym: Name, Visibility: GA.getVisibility());
2182
2183 const MCExpr *Expr = lowerConstant(CV: GA.getAliasee());
2184
2185 if (MAI->hasAltEntry() && isa<MCBinaryExpr>(Val: Expr))
2186 OutStreamer->emitSymbolAttribute(Symbol: Name, Attribute: MCSA_AltEntry);
2187
2188 // Emit the directives as assignments aka .set:
2189 OutStreamer->emitAssignment(Symbol: Name, Value: Expr);
2190 MCSymbol *LocalAlias = getSymbolPreferLocal(GV: GA);
2191 if (LocalAlias != Name)
2192 OutStreamer->emitAssignment(Symbol: LocalAlias, Value: Expr);
2193
2194 // If the aliasee does not correspond to a symbol in the output, i.e. the
2195 // alias is not of an object or the aliased object is private, then set the
2196 // size of the alias symbol from the type of the alias. We don't do this in
2197 // other situations as the alias and aliasee having differing types but same
2198 // size may be intentional.
2199 const GlobalObject *BaseObject = GA.getAliaseeObject();
2200 if (MAI->hasDotTypeDotSizeDirective() && GA.getValueType()->isSized() &&
2201 (!BaseObject || BaseObject->hasPrivateLinkage())) {
2202 const DataLayout &DL = M.getDataLayout();
2203 uint64_t Size = DL.getTypeAllocSize(Ty: GA.getValueType());
2204 OutStreamer->emitELFSize(Symbol: Name, Value: MCConstantExpr::create(Value: Size, Ctx&: OutContext));
2205 }
2206}
2207
2208void AsmPrinter::emitGlobalIFunc(Module &M, const GlobalIFunc &GI) {
2209 assert(!TM.getTargetTriple().isOSBinFormatXCOFF() &&
2210 "IFunc is not supported on AIX.");
2211
2212 auto EmitLinkage = [&](MCSymbol *Sym) {
2213 if (GI.hasExternalLinkage() || !MAI->getWeakRefDirective())
2214 OutStreamer->emitSymbolAttribute(Symbol: Sym, Attribute: MCSA_Global);
2215 else if (GI.hasWeakLinkage() || GI.hasLinkOnceLinkage())
2216 OutStreamer->emitSymbolAttribute(Symbol: Sym, Attribute: MCSA_WeakReference);
2217 else
2218 assert(GI.hasLocalLinkage() && "Invalid ifunc linkage");
2219 };
2220
2221 if (TM.getTargetTriple().isOSBinFormatELF()) {
2222 MCSymbol *Name = getSymbol(GV: &GI);
2223 EmitLinkage(Name);
2224 OutStreamer->emitSymbolAttribute(Symbol: Name, Attribute: MCSA_ELF_TypeIndFunction);
2225 emitVisibility(Sym: Name, Visibility: GI.getVisibility());
2226
2227 // Emit the directives as assignments aka .set:
2228 const MCExpr *Expr = lowerConstant(CV: GI.getResolver());
2229 OutStreamer->emitAssignment(Symbol: Name, Value: Expr);
2230 MCSymbol *LocalAlias = getSymbolPreferLocal(GV: GI);
2231 if (LocalAlias != Name)
2232 OutStreamer->emitAssignment(Symbol: LocalAlias, Value: Expr);
2233
2234 return;
2235 }
2236
2237 if (!TM.getTargetTriple().isOSBinFormatMachO() || !getIFuncMCSubtargetInfo())
2238 llvm::report_fatal_error(reason: "IFuncs are not supported on this platform");
2239
2240 // On Darwin platforms, emit a manually-constructed .symbol_resolver that
2241 // implements the symbol resolution duties of the IFunc.
2242 //
2243 // Normally, this would be handled by linker magic, but unfortunately there
2244 // are a few limitations in ld64 and ld-prime's implementation of
2245 // .symbol_resolver that mean we can't always use them:
2246 //
2247 // * resolvers cannot be the target of an alias
2248 // * resolvers cannot have private linkage
2249 // * resolvers cannot have linkonce linkage
2250 // * resolvers cannot appear in executables
2251 // * resolvers cannot appear in bundles
2252 //
2253 // This works around that by emitting a close approximation of what the
2254 // linker would have done.
2255
2256 MCSymbol *LazyPointer =
2257 GetExternalSymbolSymbol(Sym: GI.getName() + ".lazy_pointer");
2258 MCSymbol *StubHelper = GetExternalSymbolSymbol(Sym: GI.getName() + ".stub_helper");
2259
2260 OutStreamer->switchSection(Section: OutContext.getObjectFileInfo()->getDataSection());
2261
2262 const DataLayout &DL = M.getDataLayout();
2263 emitAlignment(Alignment: Align(DL.getPointerSize()));
2264 OutStreamer->emitLabel(Symbol: LazyPointer);
2265 emitVisibility(Sym: LazyPointer, Visibility: GI.getVisibility());
2266 OutStreamer->emitValue(Value: MCSymbolRefExpr::create(Symbol: StubHelper, Ctx&: OutContext), Size: 8);
2267
2268 OutStreamer->switchSection(Section: OutContext.getObjectFileInfo()->getTextSection());
2269
2270 const TargetSubtargetInfo *STI =
2271 TM.getSubtargetImpl(*GI.getResolverFunction());
2272 const TargetLowering *TLI = STI->getTargetLowering();
2273 Align TextAlign(TLI->getMinFunctionAlignment());
2274
2275 MCSymbol *Stub = getSymbol(GV: &GI);
2276 EmitLinkage(Stub);
2277 OutStreamer->emitCodeAlignment(Alignment: TextAlign, STI: getIFuncMCSubtargetInfo());
2278 OutStreamer->emitLabel(Symbol: Stub);
2279 emitVisibility(Sym: Stub, Visibility: GI.getVisibility());
2280 emitMachOIFuncStubBody(M, GI, LazyPointer);
2281
2282 OutStreamer->emitCodeAlignment(Alignment: TextAlign, STI: getIFuncMCSubtargetInfo());
2283 OutStreamer->emitLabel(Symbol: StubHelper);
2284 emitVisibility(Sym: StubHelper, Visibility: GI.getVisibility());
2285 emitMachOIFuncStubHelperBody(M, GI, LazyPointer);
2286}
2287
2288void AsmPrinter::emitRemarksSection(remarks::RemarkStreamer &RS) {
2289 if (!RS.needsSection())
2290 return;
2291
2292 remarks::RemarkSerializer &RemarkSerializer = RS.getSerializer();
2293
2294 std::optional<SmallString<128>> Filename;
2295 if (std::optional<StringRef> FilenameRef = RS.getFilename()) {
2296 Filename = *FilenameRef;
2297 sys::fs::make_absolute(path&: *Filename);
2298 assert(!Filename->empty() && "The filename can't be empty.");
2299 }
2300
2301 std::string Buf;
2302 raw_string_ostream OS(Buf);
2303 std::unique_ptr<remarks::MetaSerializer> MetaSerializer =
2304 Filename ? RemarkSerializer.metaSerializer(OS, ExternalFilename: Filename->str())
2305 : RemarkSerializer.metaSerializer(OS);
2306 MetaSerializer->emit();
2307
2308 // Switch to the remarks section.
2309 MCSection *RemarksSection =
2310 OutContext.getObjectFileInfo()->getRemarksSection();
2311 OutStreamer->switchSection(Section: RemarksSection);
2312
2313 OutStreamer->emitBinaryData(Data: OS.str());
2314}
2315
2316bool AsmPrinter::doFinalization(Module &M) {
2317 // Set the MachineFunction to nullptr so that we can catch attempted
2318 // accesses to MF specific features at the module level and so that
2319 // we can conditionalize accesses based on whether or not it is nullptr.
2320 MF = nullptr;
2321
2322 // Gather all GOT equivalent globals in the module. We really need two
2323 // passes over the globals: one to compute and another to avoid its emission
2324 // in EmitGlobalVariable, otherwise we would not be able to handle cases
2325 // where the got equivalent shows up before its use.
2326 computeGlobalGOTEquivs(M);
2327
2328 // Emit global variables.
2329 for (const auto &G : M.globals())
2330 emitGlobalVariable(GV: &G);
2331
2332 // Emit remaining GOT equivalent globals.
2333 emitGlobalGOTEquivs();
2334
2335 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
2336
2337 // Emit linkage(XCOFF) and visibility info for declarations
2338 for (const Function &F : M) {
2339 if (!F.isDeclarationForLinker())
2340 continue;
2341
2342 MCSymbol *Name = getSymbol(GV: &F);
2343 // Function getSymbol gives us the function descriptor symbol for XCOFF.
2344
2345 if (!TM.getTargetTriple().isOSBinFormatXCOFF()) {
2346 GlobalValue::VisibilityTypes V = F.getVisibility();
2347 if (V == GlobalValue::DefaultVisibility)
2348 continue;
2349
2350 emitVisibility(Sym: Name, Visibility: V, IsDefinition: false);
2351 continue;
2352 }
2353
2354 if (F.isIntrinsic())
2355 continue;
2356
2357 // Handle the XCOFF case.
2358 // Variable `Name` is the function descriptor symbol (see above). Get the
2359 // function entry point symbol.
2360 MCSymbol *FnEntryPointSym = TLOF.getFunctionEntryPointSymbol(Func: &F, TM);
2361 // Emit linkage for the function entry point.
2362 emitLinkage(GV: &F, GVSym: FnEntryPointSym);
2363
2364 // Emit linkage for the function descriptor.
2365 emitLinkage(GV: &F, GVSym: Name);
2366 }
2367
2368 // Emit the remarks section contents.
2369 // FIXME: Figure out when is the safest time to emit this section. It should
2370 // not come after debug info.
2371 if (remarks::RemarkStreamer *RS = M.getContext().getMainRemarkStreamer())
2372 emitRemarksSection(RS&: *RS);
2373
2374 TLOF.emitModuleMetadata(Streamer&: *OutStreamer, M);
2375
2376 if (TM.getTargetTriple().isOSBinFormatELF()) {
2377 MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
2378
2379 // Output stubs for external and common global variables.
2380 MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
2381 if (!Stubs.empty()) {
2382 OutStreamer->switchSection(Section: TLOF.getDataSection());
2383 const DataLayout &DL = M.getDataLayout();
2384
2385 emitAlignment(Alignment: Align(DL.getPointerSize()));
2386 for (const auto &Stub : Stubs) {
2387 OutStreamer->emitLabel(Symbol: Stub.first);
2388 OutStreamer->emitSymbolValue(Sym: Stub.second.getPointer(),
2389 Size: DL.getPointerSize());
2390 }
2391 }
2392 }
2393
2394 if (TM.getTargetTriple().isOSBinFormatCOFF()) {
2395 MachineModuleInfoCOFF &MMICOFF =
2396 MMI->getObjFileInfo<MachineModuleInfoCOFF>();
2397
2398 // Output stubs for external and common global variables.
2399 MachineModuleInfoCOFF::SymbolListTy Stubs = MMICOFF.GetGVStubList();
2400 if (!Stubs.empty()) {
2401 const DataLayout &DL = M.getDataLayout();
2402
2403 for (const auto &Stub : Stubs) {
2404 SmallString<256> SectionName = StringRef(".rdata$");
2405 SectionName += Stub.first->getName();
2406 OutStreamer->switchSection(Section: OutContext.getCOFFSection(
2407 Section: SectionName,
2408 Characteristics: COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ |
2409 COFF::IMAGE_SCN_LNK_COMDAT,
2410 Kind: SectionKind::getReadOnly(), COMDATSymName: Stub.first->getName(),
2411 Selection: COFF::IMAGE_COMDAT_SELECT_ANY));
2412 emitAlignment(Alignment: Align(DL.getPointerSize()));
2413 OutStreamer->emitSymbolAttribute(Symbol: Stub.first, Attribute: MCSA_Global);
2414 OutStreamer->emitLabel(Symbol: Stub.first);
2415 OutStreamer->emitSymbolValue(Sym: Stub.second.getPointer(),
2416 Size: DL.getPointerSize());
2417 }
2418 }
2419 }
2420
2421 // This needs to happen before emitting debug information since that can end
2422 // arbitrary sections.
2423 if (auto *TS = OutStreamer->getTargetStreamer())
2424 TS->emitConstantPools();
2425
2426 // Emit Stack maps before any debug info. Mach-O requires that no data or
2427 // text sections come after debug info has been emitted. This matters for
2428 // stack maps as they are arbitrary data, and may even have a custom format
2429 // through user plugins.
2430 emitStackMaps();
2431
2432 // Print aliases in topological order, that is, for each alias a = b,
2433 // b must be printed before a.
2434 // This is because on some targets (e.g. PowerPC) linker expects aliases in
2435 // such an order to generate correct TOC information.
2436 SmallVector<const GlobalAlias *, 16> AliasStack;
2437 SmallPtrSet<const GlobalAlias *, 16> AliasVisited;
2438 for (const auto &Alias : M.aliases()) {
2439 if (Alias.hasAvailableExternallyLinkage())
2440 continue;
2441 for (const GlobalAlias *Cur = &Alias; Cur;
2442 Cur = dyn_cast<GlobalAlias>(Val: Cur->getAliasee())) {
2443 if (!AliasVisited.insert(Ptr: Cur).second)
2444 break;
2445 AliasStack.push_back(Elt: Cur);
2446 }
2447 for (const GlobalAlias *AncestorAlias : llvm::reverse(C&: AliasStack))
2448 emitGlobalAlias(M, GA: *AncestorAlias);
2449 AliasStack.clear();
2450 }
2451
2452 // IFuncs must come before deubginfo in case the backend decides to emit them
2453 // as actual functions, since on Mach-O targets, we cannot create regular
2454 // sections after DWARF.
2455 for (const auto &IFunc : M.ifuncs())
2456 emitGlobalIFunc(M, GI: IFunc);
2457
2458 // Finalize debug and EH information.
2459 for (const HandlerInfo &HI : Handlers) {
2460 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
2461 HI.TimerGroupDescription, TimePassesIsEnabled);
2462 HI.Handler->endModule();
2463 }
2464
2465 // This deletes all the ephemeral handlers that AsmPrinter added, while
2466 // keeping all the user-added handlers alive until the AsmPrinter is
2467 // destroyed.
2468 Handlers.erase(first: Handlers.begin() + NumUserHandlers, last: Handlers.end());
2469 DD = nullptr;
2470
2471 // If the target wants to know about weak references, print them all.
2472 if (MAI->getWeakRefDirective()) {
2473 // FIXME: This is not lazy, it would be nice to only print weak references
2474 // to stuff that is actually used. Note that doing so would require targets
2475 // to notice uses in operands (due to constant exprs etc). This should
2476 // happen with the MC stuff eventually.
2477
2478 // Print out module-level global objects here.
2479 for (const auto &GO : M.global_objects()) {
2480 if (!GO.hasExternalWeakLinkage())
2481 continue;
2482 OutStreamer->emitSymbolAttribute(Symbol: getSymbol(GV: &GO), Attribute: MCSA_WeakReference);
2483 }
2484 if (shouldEmitWeakSwiftAsyncExtendedFramePointerFlags()) {
2485 auto SymbolName = "swift_async_extendedFramePointerFlags";
2486 auto Global = M.getGlobalVariable(Name: SymbolName);
2487 if (!Global) {
2488 auto Int8PtrTy = PointerType::getUnqual(C&: M.getContext());
2489 Global = new GlobalVariable(M, Int8PtrTy, false,
2490 GlobalValue::ExternalWeakLinkage, nullptr,
2491 SymbolName);
2492 OutStreamer->emitSymbolAttribute(Symbol: getSymbol(GV: Global), Attribute: MCSA_WeakReference);
2493 }
2494 }
2495 }
2496
2497 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
2498 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
2499 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
2500 if (GCMetadataPrinter *MP = getOrCreateGCPrinter(S&: **--I))
2501 MP->finishAssembly(M, Info&: *MI, AP&: *this);
2502
2503 // Emit llvm.ident metadata in an '.ident' directive.
2504 emitModuleIdents(M);
2505
2506 // Emit bytes for llvm.commandline metadata.
2507 // The command line metadata is emitted earlier on XCOFF.
2508 if (!TM.getTargetTriple().isOSBinFormatXCOFF())
2509 emitModuleCommandLines(M);
2510
2511 // Emit .note.GNU-split-stack and .note.GNU-no-split-stack sections if
2512 // split-stack is used.
2513 if (TM.getTargetTriple().isOSBinFormatELF() && HasSplitStack) {
2514 OutStreamer->switchSection(Section: OutContext.getELFSection(Section: ".note.GNU-split-stack",
2515 Type: ELF::SHT_PROGBITS, Flags: 0));
2516 if (HasNoSplitStack)
2517 OutStreamer->switchSection(Section: OutContext.getELFSection(
2518 Section: ".note.GNU-no-split-stack", Type: ELF::SHT_PROGBITS, Flags: 0));
2519 }
2520
2521 // If we don't have any trampolines, then we don't require stack memory
2522 // to be executable. Some targets have a directive to declare this.
2523 Function *InitTrampolineIntrinsic = M.getFunction(Name: "llvm.init.trampoline");
2524 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
2525 if (MCSection *S = MAI->getNonexecutableStackSection(Ctx&: OutContext))
2526 OutStreamer->switchSection(Section: S);
2527
2528 if (TM.Options.EmitAddrsig) {
2529 // Emit address-significance attributes for all globals.
2530 OutStreamer->emitAddrsig();
2531 for (const GlobalValue &GV : M.global_values()) {
2532 if (!GV.use_empty() && !GV.isThreadLocal() &&
2533 !GV.hasDLLImportStorageClass() &&
2534 !GV.getName().starts_with(Prefix: "llvm.") &&
2535 !GV.hasAtLeastLocalUnnamedAddr())
2536 OutStreamer->emitAddrsigSym(Sym: getSymbol(GV: &GV));
2537 }
2538 }
2539
2540 // Emit symbol partition specifications (ELF only).
2541 if (TM.getTargetTriple().isOSBinFormatELF()) {
2542 unsigned UniqueID = 0;
2543 for (const GlobalValue &GV : M.global_values()) {
2544 if (!GV.hasPartition() || GV.isDeclarationForLinker() ||
2545 GV.getVisibility() != GlobalValue::DefaultVisibility)
2546 continue;
2547
2548 OutStreamer->switchSection(
2549 Section: OutContext.getELFSection(Section: ".llvm_sympart", Type: ELF::SHT_LLVM_SYMPART, Flags: 0, EntrySize: 0,
2550 Group: "", IsComdat: false, UniqueID: ++UniqueID, LinkedToSym: nullptr));
2551 OutStreamer->emitBytes(Data: GV.getPartition());
2552 OutStreamer->emitZeros(NumBytes: 1);
2553 OutStreamer->emitValue(
2554 Value: MCSymbolRefExpr::create(Symbol: getSymbol(GV: &GV), Ctx&: OutContext),
2555 Size: MAI->getCodePointerSize());
2556 }
2557 }
2558
2559 // Allow the target to emit any magic that it wants at the end of the file,
2560 // after everything else has gone out.
2561 emitEndOfAsmFile(M);
2562
2563 MMI = nullptr;
2564 AddrLabelSymbols = nullptr;
2565
2566 OutStreamer->finish();
2567 OutStreamer->reset();
2568 OwnedMLI.reset();
2569 OwnedMDT.reset();
2570
2571 return false;
2572}
2573
2574MCSymbol *AsmPrinter::getMBBExceptionSym(const MachineBasicBlock &MBB) {
2575 auto Res = MBBSectionExceptionSyms.try_emplace(Key: MBB.getSectionIDNum());
2576 if (Res.second)
2577 Res.first->second = createTempSymbol(Name: "exception");
2578 return Res.first->second;
2579}
2580
2581void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
2582 this->MF = &MF;
2583 const Function &F = MF.getFunction();
2584
2585 // Record that there are split-stack functions, so we will emit a special
2586 // section to tell the linker.
2587 if (MF.shouldSplitStack()) {
2588 HasSplitStack = true;
2589
2590 if (!MF.getFrameInfo().needsSplitStackProlog())
2591 HasNoSplitStack = true;
2592 } else
2593 HasNoSplitStack = true;
2594
2595 // Get the function symbol.
2596 if (!MAI->needsFunctionDescriptors()) {
2597 CurrentFnSym = getSymbol(GV: &MF.getFunction());
2598 } else {
2599 assert(TM.getTargetTriple().isOSAIX() &&
2600 "Only AIX uses the function descriptor hooks.");
2601 // AIX is unique here in that the name of the symbol emitted for the
2602 // function body does not have the same name as the source function's
2603 // C-linkage name.
2604 assert(CurrentFnDescSym && "The function descriptor symbol needs to be"
2605 " initalized first.");
2606
2607 // Get the function entry point symbol.
2608 CurrentFnSym = getObjFileLowering().getFunctionEntryPointSymbol(Func: &F, TM);
2609 }
2610
2611 CurrentFnSymForSize = CurrentFnSym;
2612 CurrentFnBegin = nullptr;
2613 CurrentFnBeginLocal = nullptr;
2614 CurrentSectionBeginSym = nullptr;
2615 MBBSectionRanges.clear();
2616 MBBSectionExceptionSyms.clear();
2617 bool NeedsLocalForSize = MAI->needsLocalForSize();
2618 if (F.hasFnAttribute(Kind: "patchable-function-entry") ||
2619 F.hasFnAttribute(Kind: "function-instrument") ||
2620 F.hasFnAttribute(Kind: "xray-instruction-threshold") || needFuncLabels(MF) ||
2621 NeedsLocalForSize || MF.getTarget().Options.EmitStackSizeSection ||
2622 MF.getTarget().Options.BBAddrMap || MF.hasBBLabels()) {
2623 CurrentFnBegin = createTempSymbol(Name: "func_begin");
2624 if (NeedsLocalForSize)
2625 CurrentFnSymForSize = CurrentFnBegin;
2626 }
2627
2628 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
2629}
2630
2631namespace {
2632
2633// Keep track the alignment, constpool entries per Section.
2634 struct SectionCPs {
2635 MCSection *S;
2636 Align Alignment;
2637 SmallVector<unsigned, 4> CPEs;
2638
2639 SectionCPs(MCSection *s, Align a) : S(s), Alignment(a) {}
2640 };
2641
2642} // end anonymous namespace
2643
2644/// EmitConstantPool - Print to the current output stream assembly
2645/// representations of the constants in the constant pool MCP. This is
2646/// used to print out constants which have been "spilled to memory" by
2647/// the code generator.
2648void AsmPrinter::emitConstantPool() {
2649 const MachineConstantPool *MCP = MF->getConstantPool();
2650 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
2651 if (CP.empty()) return;
2652
2653 // Calculate sections for constant pool entries. We collect entries to go into
2654 // the same section together to reduce amount of section switch statements.
2655 SmallVector<SectionCPs, 4> CPSections;
2656 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
2657 const MachineConstantPoolEntry &CPE = CP[i];
2658 Align Alignment = CPE.getAlign();
2659
2660 SectionKind Kind = CPE.getSectionKind(DL: &getDataLayout());
2661
2662 const Constant *C = nullptr;
2663 if (!CPE.isMachineConstantPoolEntry())
2664 C = CPE.Val.ConstVal;
2665
2666 MCSection *S = getObjFileLowering().getSectionForConstant(
2667 DL: getDataLayout(), Kind, C, Alignment);
2668
2669 // The number of sections are small, just do a linear search from the
2670 // last section to the first.
2671 bool Found = false;
2672 unsigned SecIdx = CPSections.size();
2673 while (SecIdx != 0) {
2674 if (CPSections[--SecIdx].S == S) {
2675 Found = true;
2676 break;
2677 }
2678 }
2679 if (!Found) {
2680 SecIdx = CPSections.size();
2681 CPSections.push_back(Elt: SectionCPs(S, Alignment));
2682 }
2683
2684 if (Alignment > CPSections[SecIdx].Alignment)
2685 CPSections[SecIdx].Alignment = Alignment;
2686 CPSections[SecIdx].CPEs.push_back(Elt: i);
2687 }
2688
2689 // Now print stuff into the calculated sections.
2690 const MCSection *CurSection = nullptr;
2691 unsigned Offset = 0;
2692 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
2693 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
2694 unsigned CPI = CPSections[i].CPEs[j];
2695 MCSymbol *Sym = GetCPISymbol(CPID: CPI);
2696 if (!Sym->isUndefined())
2697 continue;
2698
2699 if (CurSection != CPSections[i].S) {
2700 OutStreamer->switchSection(Section: CPSections[i].S);
2701 emitAlignment(Alignment: Align(CPSections[i].Alignment));
2702 CurSection = CPSections[i].S;
2703 Offset = 0;
2704 }
2705
2706 MachineConstantPoolEntry CPE = CP[CPI];
2707
2708 // Emit inter-object padding for alignment.
2709 unsigned NewOffset = alignTo(Size: Offset, A: CPE.getAlign());
2710 OutStreamer->emitZeros(NumBytes: NewOffset - Offset);
2711
2712 Offset = NewOffset + CPE.getSizeInBytes(DL: getDataLayout());
2713
2714 OutStreamer->emitLabel(Symbol: Sym);
2715 if (CPE.isMachineConstantPoolEntry())
2716 emitMachineConstantPoolValue(MCPV: CPE.Val.MachineCPVal);
2717 else
2718 emitGlobalConstant(DL: getDataLayout(), CV: CPE.Val.ConstVal);
2719 }
2720 }
2721}
2722
2723// Print assembly representations of the jump tables used by the current
2724// function.
2725void AsmPrinter::emitJumpTableInfo() {
2726 const DataLayout &DL = MF->getDataLayout();
2727 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
2728 if (!MJTI) return;
2729 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
2730 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2731 if (JT.empty()) return;
2732
2733 // Pick the directive to use to print the jump table entries, and switch to
2734 // the appropriate section.
2735 const Function &F = MF->getFunction();
2736 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
2737 bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
2738 UsesLabelDifference: MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
2739 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference64,
2740 F);
2741 if (JTInDiffSection) {
2742 // Drop it in the readonly section.
2743 MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(F, TM);
2744 OutStreamer->switchSection(Section: ReadOnlySection);
2745 }
2746
2747 emitAlignment(Alignment: Align(MJTI->getEntryAlignment(TD: DL)));
2748
2749 // Jump tables in code sections are marked with a data_region directive
2750 // where that's supported.
2751 if (!JTInDiffSection)
2752 OutStreamer->emitDataRegion(Kind: MCDR_DataRegionJT32);
2753
2754 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
2755 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2756
2757 // If this jump table was deleted, ignore it.
2758 if (JTBBs.empty()) continue;
2759
2760 // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
2761 /// emit a .set directive for each unique entry.
2762 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
2763 MAI->doesSetDirectiveSuppressReloc()) {
2764 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
2765 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
2766 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,Ctx&: OutContext);
2767 for (const MachineBasicBlock *MBB : JTBBs) {
2768 if (!EmittedSets.insert(Ptr: MBB).second)
2769 continue;
2770
2771 // .set LJTSet, LBB32-base
2772 const MCExpr *LHS =
2773 MCSymbolRefExpr::create(Symbol: MBB->getSymbol(), Ctx&: OutContext);
2774 OutStreamer->emitAssignment(Symbol: GetJTSetSymbol(UID: JTI, MBBID: MBB->getNumber()),
2775 Value: MCBinaryExpr::createSub(LHS, RHS: Base,
2776 Ctx&: OutContext));
2777 }
2778 }
2779
2780 // On some targets (e.g. Darwin) we want to emit two consecutive labels
2781 // before each jump table. The first label is never referenced, but tells
2782 // the assembler and linker the extents of the jump table object. The
2783 // second label is actually referenced by the code.
2784 if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
2785 // FIXME: This doesn't have to have any specific name, just any randomly
2786 // named and numbered local label started with 'l' would work. Simplify
2787 // GetJTISymbol.
2788 OutStreamer->emitLabel(Symbol: GetJTISymbol(JTID: JTI, isLinkerPrivate: true));
2789
2790 MCSymbol* JTISymbol = GetJTISymbol(JTID: JTI);
2791 OutStreamer->emitLabel(Symbol: JTISymbol);
2792
2793 for (const MachineBasicBlock *MBB : JTBBs)
2794 emitJumpTableEntry(MJTI, MBB, uid: JTI);
2795 }
2796 if (!JTInDiffSection)
2797 OutStreamer->emitDataRegion(Kind: MCDR_DataRegionEnd);
2798}
2799
2800/// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
2801/// current stream.
2802void AsmPrinter::emitJumpTableEntry(const MachineJumpTableInfo *MJTI,
2803 const MachineBasicBlock *MBB,
2804 unsigned UID) const {
2805 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
2806 const MCExpr *Value = nullptr;
2807 switch (MJTI->getEntryKind()) {
2808 case MachineJumpTableInfo::EK_Inline:
2809 llvm_unreachable("Cannot emit EK_Inline jump table entry");
2810 case MachineJumpTableInfo::EK_Custom32:
2811 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
2812 MJTI, MBB, UID, OutContext);
2813 break;
2814 case MachineJumpTableInfo::EK_BlockAddress:
2815 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
2816 // .word LBB123
2817 Value = MCSymbolRefExpr::create(Symbol: MBB->getSymbol(), Ctx&: OutContext);
2818 break;
2819 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
2820 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
2821 // with a relocation as gp-relative, e.g.:
2822 // .gprel32 LBB123
2823 MCSymbol *MBBSym = MBB->getSymbol();
2824 OutStreamer->emitGPRel32Value(Value: MCSymbolRefExpr::create(Symbol: MBBSym, Ctx&: OutContext));
2825 return;
2826 }
2827
2828 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
2829 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
2830 // with a relocation as gp-relative, e.g.:
2831 // .gpdword LBB123
2832 MCSymbol *MBBSym = MBB->getSymbol();
2833 OutStreamer->emitGPRel64Value(Value: MCSymbolRefExpr::create(Symbol: MBBSym, Ctx&: OutContext));
2834 return;
2835 }
2836
2837 case MachineJumpTableInfo::EK_LabelDifference32:
2838 case MachineJumpTableInfo::EK_LabelDifference64: {
2839 // Each entry is the address of the block minus the address of the jump
2840 // table. This is used for PIC jump tables where gprel32 is not supported.
2841 // e.g.:
2842 // .word LBB123 - LJTI1_2
2843 // If the .set directive avoids relocations, this is emitted as:
2844 // .set L4_5_set_123, LBB123 - LJTI1_2
2845 // .word L4_5_set_123
2846 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
2847 MAI->doesSetDirectiveSuppressReloc()) {
2848 Value = MCSymbolRefExpr::create(Symbol: GetJTSetSymbol(UID, MBBID: MBB->getNumber()),
2849 Ctx&: OutContext);
2850 break;
2851 }
2852 Value = MCSymbolRefExpr::create(Symbol: MBB->getSymbol(), Ctx&: OutContext);
2853 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
2854 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, JTI: UID, Ctx&: OutContext);
2855 Value = MCBinaryExpr::createSub(LHS: Value, RHS: Base, Ctx&: OutContext);
2856 break;
2857 }
2858 }
2859
2860 assert(Value && "Unknown entry kind!");
2861
2862 unsigned EntrySize = MJTI->getEntrySize(TD: getDataLayout());
2863 OutStreamer->emitValue(Value, Size: EntrySize);
2864}
2865
2866/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
2867/// special global used by LLVM. If so, emit it and return true, otherwise
2868/// do nothing and return false.
2869bool AsmPrinter::emitSpecialLLVMGlobal(const GlobalVariable *GV) {
2870 if (GV->getName() == "llvm.used") {
2871 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
2872 emitLLVMUsedList(InitList: cast<ConstantArray>(Val: GV->getInitializer()));
2873 return true;
2874 }
2875
2876 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
2877 if (GV->getSection() == "llvm.metadata" ||
2878 GV->hasAvailableExternallyLinkage())
2879 return true;
2880
2881 if (GV->getName() == "llvm.arm64ec.symbolmap") {
2882 // For ARM64EC, print the table that maps between symbols and the
2883 // corresponding thunks to translate between x64 and AArch64 code.
2884 // This table is generated by AArch64Arm64ECCallLowering.
2885 OutStreamer->switchSection(Section: OutContext.getCOFFSection(
2886 Section: ".hybmp$x", Characteristics: COFF::IMAGE_SCN_LNK_INFO, Kind: SectionKind::getMetadata()));
2887 auto *Arr = cast<ConstantArray>(Val: GV->getInitializer());
2888 for (auto &U : Arr->operands()) {
2889 auto *C = cast<Constant>(Val: U);
2890 auto *Src = cast<Function>(Val: C->getOperand(i: 0)->stripPointerCasts());
2891 auto *Dst = cast<Function>(Val: C->getOperand(i: 1)->stripPointerCasts());
2892 int Kind = cast<ConstantInt>(Val: C->getOperand(i: 2))->getZExtValue();
2893
2894 if (Src->hasDLLImportStorageClass()) {
2895 // For now, we assume dllimport functions aren't directly called.
2896 // (We might change this later to match MSVC.)
2897 OutStreamer->emitCOFFSymbolIndex(
2898 Symbol: OutContext.getOrCreateSymbol(Name: "__imp_" + Src->getName()));
2899 OutStreamer->emitCOFFSymbolIndex(Symbol: getSymbol(GV: Dst));
2900 OutStreamer->emitInt32(Value: Kind);
2901 } else {
2902 // FIXME: For non-dllimport functions, MSVC emits the same entry
2903 // twice, for reasons I don't understand. I have to assume the linker
2904 // ignores the redundant entry; there aren't any reasonable semantics
2905 // to attach to it.
2906 OutStreamer->emitCOFFSymbolIndex(Symbol: getSymbol(GV: Src));
2907 OutStreamer->emitCOFFSymbolIndex(Symbol: getSymbol(GV: Dst));
2908 OutStreamer->emitInt32(Value: Kind);
2909 }
2910 }
2911 return true;
2912 }
2913
2914 if (!GV->hasAppendingLinkage()) return false;
2915
2916 assert(GV->hasInitializer() && "Not a special LLVM global!");
2917
2918 if (GV->getName() == "llvm.global_ctors") {
2919 emitXXStructorList(DL: GV->getParent()->getDataLayout(), List: GV->getInitializer(),
2920 /* isCtor */ IsCtor: true);
2921
2922 return true;
2923 }
2924
2925 if (GV->getName() == "llvm.global_dtors") {
2926 emitXXStructorList(DL: GV->getParent()->getDataLayout(), List: GV->getInitializer(),
2927 /* isCtor */ IsCtor: false);
2928
2929 return true;
2930 }
2931
2932 report_fatal_error(reason: "unknown special variable");
2933}
2934
2935/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
2936/// global in the specified llvm.used list.
2937void AsmPrinter::emitLLVMUsedList(const ConstantArray *InitList) {
2938 // Should be an array of 'i8*'.
2939 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
2940 const GlobalValue *GV =
2941 dyn_cast<GlobalValue>(Val: InitList->getOperand(i_nocapture: i)->stripPointerCasts());
2942 if (GV)
2943 OutStreamer->emitSymbolAttribute(Symbol: getSymbol(GV), Attribute: MCSA_NoDeadStrip);
2944 }
2945}
2946
2947void AsmPrinter::preprocessXXStructorList(const DataLayout &DL,
2948 const Constant *List,
2949 SmallVector<Structor, 8> &Structors) {
2950 // Should be an array of '{ i32, void ()*, i8* }' structs. The first value is
2951 // the init priority.
2952 if (!isa<ConstantArray>(Val: List))
2953 return;
2954
2955 // Gather the structors in a form that's convenient for sorting by priority.
2956 for (Value *O : cast<ConstantArray>(Val: List)->operands()) {
2957 auto *CS = cast<ConstantStruct>(Val: O);
2958 if (CS->getOperand(i_nocapture: 1)->isNullValue())
2959 break; // Found a null terminator, skip the rest.
2960 ConstantInt *Priority = dyn_cast<ConstantInt>(Val: CS->getOperand(i_nocapture: 0));
2961 if (!Priority)
2962 continue; // Malformed.
2963 Structors.push_back(Elt: Structor());
2964 Structor &S = Structors.back();
2965 S.Priority = Priority->getLimitedValue(Limit: 65535);
2966 S.Func = CS->getOperand(i_nocapture: 1);
2967 if (!CS->getOperand(i_nocapture: 2)->isNullValue()) {
2968 if (TM.getTargetTriple().isOSAIX())
2969 llvm::report_fatal_error(
2970 reason: "associated data of XXStructor list is not yet supported on AIX");
2971 S.ComdatKey =
2972 dyn_cast<GlobalValue>(Val: CS->getOperand(i_nocapture: 2)->stripPointerCasts());
2973 }
2974 }
2975
2976 // Emit the function pointers in the target-specific order
2977 llvm::stable_sort(Range&: Structors, C: [](const Structor &L, const Structor &R) {
2978 return L.Priority < R.Priority;
2979 });
2980}
2981
2982/// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
2983/// priority.
2984void AsmPrinter::emitXXStructorList(const DataLayout &DL, const Constant *List,
2985 bool IsCtor) {
2986 SmallVector<Structor, 8> Structors;
2987 preprocessXXStructorList(DL, List, Structors);
2988 if (Structors.empty())
2989 return;
2990
2991 // Emit the structors in reverse order if we are using the .ctor/.dtor
2992 // initialization scheme.
2993 if (!TM.Options.UseInitArray)
2994 std::reverse(first: Structors.begin(), last: Structors.end());
2995
2996 const Align Align = DL.getPointerPrefAlignment();
2997 for (Structor &S : Structors) {
2998 const TargetLoweringObjectFile &Obj = getObjFileLowering();
2999 const MCSymbol *KeySym = nullptr;
3000 if (GlobalValue *GV = S.ComdatKey) {
3001 if (GV->isDeclarationForLinker())
3002 // If the associated variable is not defined in this module
3003 // (it might be available_externally, or have been an
3004 // available_externally definition that was dropped by the
3005 // EliminateAvailableExternally pass), some other TU
3006 // will provide its dynamic initializer.
3007 continue;
3008
3009 KeySym = getSymbol(GV);
3010 }
3011
3012 MCSection *OutputSection =
3013 (IsCtor ? Obj.getStaticCtorSection(Priority: S.Priority, KeySym)
3014 : Obj.getStaticDtorSection(Priority: S.Priority, KeySym));
3015 OutStreamer->switchSection(Section: OutputSection);
3016 if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
3017 emitAlignment(Alignment: Align);
3018 emitXXStructor(DL, CV: S.Func);
3019 }
3020}
3021
3022void AsmPrinter::emitModuleIdents(Module &M) {
3023 if (!MAI->hasIdentDirective())
3024 return;
3025
3026 if (const NamedMDNode *NMD = M.getNamedMetadata(Name: "llvm.ident")) {
3027 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
3028 const MDNode *N = NMD->getOperand(i);
3029 assert(N->getNumOperands() == 1 &&
3030 "llvm.ident metadata entry can have only one operand");
3031 const MDString *S = cast<MDString>(Val: N->getOperand(I: 0));
3032 OutStreamer->emitIdent(IdentString: S->getString());
3033 }
3034 }
3035}
3036
3037void AsmPrinter::emitModuleCommandLines(Module &M) {
3038 MCSection *CommandLine = getObjFileLowering().getSectionForCommandLines();
3039 if (!CommandLine)
3040 return;
3041
3042 const NamedMDNode *NMD = M.getNamedMetadata(Name: "llvm.commandline");
3043 if (!NMD || !NMD->getNumOperands())
3044 return;
3045
3046 OutStreamer->pushSection();
3047 OutStreamer->switchSection(Section: CommandLine);
3048 OutStreamer->emitZeros(NumBytes: 1);
3049 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
3050 const MDNode *N = NMD->getOperand(i);
3051 assert(N->getNumOperands() == 1 &&
3052 "llvm.commandline metadata entry can have only one operand");
3053 const MDString *S = cast<MDString>(Val: N->getOperand(I: 0));
3054 OutStreamer->emitBytes(Data: S->getString());
3055 OutStreamer->emitZeros(NumBytes: 1);
3056 }
3057 OutStreamer->popSection();
3058}
3059
3060//===--------------------------------------------------------------------===//
3061// Emission and print routines
3062//
3063
3064/// Emit a byte directive and value.
3065///
3066void AsmPrinter::emitInt8(int Value) const { OutStreamer->emitInt8(Value); }
3067
3068/// Emit a short directive and value.
3069void AsmPrinter::emitInt16(int Value) const { OutStreamer->emitInt16(Value); }
3070
3071/// Emit a long directive and value.
3072void AsmPrinter::emitInt32(int Value) const { OutStreamer->emitInt32(Value); }
3073
3074/// EmitSLEB128 - emit the specified signed leb128 value.
3075void AsmPrinter::emitSLEB128(int64_t Value, const char *Desc) const {
3076 if (isVerbose() && Desc)
3077 OutStreamer->AddComment(T: Desc);
3078
3079 OutStreamer->emitSLEB128IntValue(Value);
3080}
3081
3082void AsmPrinter::emitULEB128(uint64_t Value, const char *Desc,
3083 unsigned PadTo) const {
3084 if (isVerbose() && Desc)
3085 OutStreamer->AddComment(T: Desc);
3086
3087 OutStreamer->emitULEB128IntValue(Value, PadTo);
3088}
3089
3090/// Emit a long long directive and value.
3091void AsmPrinter::emitInt64(uint64_t Value) const {
3092 OutStreamer->emitInt64(Value);
3093}
3094
3095/// Emit something like ".long Hi-Lo" where the size in bytes of the directive
3096/// is specified by Size and Hi/Lo specify the labels. This implicitly uses
3097/// .set if it avoids relocations.
3098void AsmPrinter::emitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
3099 unsigned Size) const {
3100 OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
3101}
3102
3103/// Emit something like ".uleb128 Hi-Lo".
3104void AsmPrinter::emitLabelDifferenceAsULEB128(const MCSymbol *Hi,
3105 const MCSymbol *Lo) const {
3106 OutStreamer->emitAbsoluteSymbolDiffAsULEB128(Hi, Lo);
3107}
3108
3109/// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
3110/// where the size in bytes of the directive is specified by Size and Label
3111/// specifies the label. This implicitly uses .set if it is available.
3112void AsmPrinter::emitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
3113 unsigned Size,
3114 bool IsSectionRelative) const {
3115 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
3116 OutStreamer->emitCOFFSecRel32(Symbol: Label, Offset);
3117 if (Size > 4)
3118 OutStreamer->emitZeros(NumBytes: Size - 4);
3119 return;
3120 }
3121
3122 // Emit Label+Offset (or just Label if Offset is zero)
3123 const MCExpr *Expr = MCSymbolRefExpr::create(Symbol: Label, Ctx&: OutContext);
3124 if (Offset)
3125 Expr = MCBinaryExpr::createAdd(
3126 LHS: Expr, RHS: MCConstantExpr::create(Value: Offset, Ctx&: OutContext), Ctx&: OutContext);
3127
3128 OutStreamer->emitValue(Value: Expr, Size);
3129}
3130
3131//===----------------------------------------------------------------------===//
3132
3133// EmitAlignment - Emit an alignment directive to the specified power of
3134// two boundary. If a global value is specified, and if that global has
3135// an explicit alignment requested, it will override the alignment request
3136// if required for correctness.
3137void AsmPrinter::emitAlignment(Align Alignment, const GlobalObject *GV,
3138 unsigned MaxBytesToEmit) const {
3139 if (GV)
3140 Alignment = getGVAlignment(GV, DL: GV->getParent()->getDataLayout(), InAlign: Alignment);
3141
3142 if (Alignment == Align(1))
3143 return; // 1-byte aligned: no need to emit alignment.
3144
3145 if (getCurrentSection()->getKind().isText()) {
3146 const MCSubtargetInfo *STI = nullptr;
3147 if (this->MF)
3148 STI = &getSubtargetInfo();
3149 else
3150 STI = TM.getMCSubtargetInfo();
3151 OutStreamer->emitCodeAlignment(Alignment, STI, MaxBytesToEmit);
3152 } else
3153 OutStreamer->emitValueToAlignment(Alignment, Value: 0, ValueSize: 1, MaxBytesToEmit);
3154}
3155
3156//===----------------------------------------------------------------------===//
3157// Constant emission.
3158//===----------------------------------------------------------------------===//
3159
3160const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) {
3161 MCContext &Ctx = OutContext;
3162
3163 if (CV->isNullValue() || isa<UndefValue>(Val: CV))
3164 return MCConstantExpr::create(Value: 0, Ctx);
3165
3166 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val: CV))
3167 return MCConstantExpr::create(Value: CI->getZExtValue(), Ctx);
3168
3169 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Val: CV))
3170 return MCSymbolRefExpr::create(Symbol: getSymbol(GV), Ctx);
3171
3172 if (const BlockAddress *BA = dyn_cast<BlockAddress>(Val: CV))
3173 return MCSymbolRefExpr::create(Symbol: GetBlockAddressSymbol(BA), Ctx);
3174
3175 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(Val: CV))
3176 return getObjFileLowering().lowerDSOLocalEquivalent(Equiv, TM);
3177
3178 if (const NoCFIValue *NC = dyn_cast<NoCFIValue>(Val: CV))
3179 return MCSymbolRefExpr::create(Symbol: getSymbol(GV: NC->getGlobalValue()), Ctx);
3180
3181 const ConstantExpr *CE = dyn_cast<ConstantExpr>(Val: CV);
3182 if (!CE) {
3183 llvm_unreachable("Unknown constant value to lower!");
3184 }
3185
3186 // The constant expression opcodes are limited to those that are necessary
3187 // to represent relocations on supported targets. Expressions involving only
3188 // constant addresses are constant folded instead.
3189 switch (CE->getOpcode()) {
3190 default:
3191 break; // Error
3192 case Instruction::AddrSpaceCast: {
3193 const Constant *Op = CE->getOperand(i_nocapture: 0);
3194 unsigned DstAS = CE->getType()->getPointerAddressSpace();
3195 unsigned SrcAS = Op->getType()->getPointerAddressSpace();
3196 if (TM.isNoopAddrSpaceCast(SrcAS, DestAS: DstAS))
3197 return lowerConstant(CV: Op);
3198
3199 break; // Error
3200 }
3201 case Instruction::GetElementPtr: {
3202 // Generate a symbolic expression for the byte address
3203 APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
3204 cast<GEPOperator>(Val: CE)->accumulateConstantOffset(DL: getDataLayout(), Offset&: OffsetAI);
3205
3206 const MCExpr *Base = lowerConstant(CV: CE->getOperand(i_nocapture: 0));
3207 if (!OffsetAI)
3208 return Base;
3209
3210 int64_t Offset = OffsetAI.getSExtValue();
3211 return MCBinaryExpr::createAdd(LHS: Base, RHS: MCConstantExpr::create(Value: Offset, Ctx),
3212 Ctx);
3213 }
3214
3215 case Instruction::Trunc:
3216 // We emit the value and depend on the assembler to truncate the generated
3217 // expression properly. This is important for differences between
3218 // blockaddress labels. Since the two labels are in the same function, it
3219 // is reasonable to treat their delta as a 32-bit value.
3220 [[fallthrough]];
3221 case Instruction::BitCast:
3222 return lowerConstant(CV: CE->getOperand(i_nocapture: 0));
3223
3224 case Instruction::IntToPtr: {
3225 const DataLayout &DL = getDataLayout();
3226
3227 // Handle casts to pointers by changing them into casts to the appropriate
3228 // integer type. This promotes constant folding and simplifies this code.
3229 Constant *Op = CE->getOperand(i_nocapture: 0);
3230 Op = ConstantFoldIntegerCast(C: Op, DestTy: DL.getIntPtrType(CV->getType()),
3231 /*IsSigned*/ false, DL);
3232 if (Op)
3233 return lowerConstant(CV: Op);
3234
3235 break; // Error
3236 }
3237
3238 case Instruction::PtrToInt: {
3239 const DataLayout &DL = getDataLayout();
3240
3241 // Support only foldable casts to/from pointers that can be eliminated by
3242 // changing the pointer to the appropriately sized integer type.
3243 Constant *Op = CE->getOperand(i_nocapture: 0);
3244 Type *Ty = CE->getType();
3245
3246 const MCExpr *OpExpr = lowerConstant(CV: Op);
3247
3248 // We can emit the pointer value into this slot if the slot is an
3249 // integer slot equal to the size of the pointer.
3250 //
3251 // If the pointer is larger than the resultant integer, then
3252 // as with Trunc just depend on the assembler to truncate it.
3253 if (DL.getTypeAllocSize(Ty).getFixedValue() <=
3254 DL.getTypeAllocSize(Ty: Op->getType()).getFixedValue())
3255 return OpExpr;
3256
3257 break; // Error
3258 }
3259
3260 case Instruction::Sub: {
3261 GlobalValue *LHSGV;
3262 APInt LHSOffset;
3263 DSOLocalEquivalent *DSOEquiv;
3264 if (IsConstantOffsetFromGlobal(C: CE->getOperand(i_nocapture: 0), GV&: LHSGV, Offset&: LHSOffset,
3265 DL: getDataLayout(), DSOEquiv: &DSOEquiv)) {
3266 GlobalValue *RHSGV;
3267 APInt RHSOffset;
3268 if (IsConstantOffsetFromGlobal(C: CE->getOperand(i_nocapture: 1), GV&: RHSGV, Offset&: RHSOffset,
3269 DL: getDataLayout())) {
3270 const MCExpr *RelocExpr =
3271 getObjFileLowering().lowerRelativeReference(LHS: LHSGV, RHS: RHSGV, TM);
3272 if (!RelocExpr) {
3273 const MCExpr *LHSExpr =
3274 MCSymbolRefExpr::create(Symbol: getSymbol(GV: LHSGV), Ctx);
3275 if (DSOEquiv &&
3276 getObjFileLowering().supportDSOLocalEquivalentLowering())
3277 LHSExpr =
3278 getObjFileLowering().lowerDSOLocalEquivalent(Equiv: DSOEquiv, TM);
3279 RelocExpr = MCBinaryExpr::createSub(
3280 LHS: LHSExpr, RHS: MCSymbolRefExpr::create(Symbol: getSymbol(GV: RHSGV), Ctx), Ctx);
3281 }
3282 int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
3283 if (Addend != 0)
3284 RelocExpr = MCBinaryExpr::createAdd(
3285 LHS: RelocExpr, RHS: MCConstantExpr::create(Value: Addend, Ctx), Ctx);
3286 return RelocExpr;
3287 }
3288 }
3289
3290 const MCExpr *LHS = lowerConstant(CV: CE->getOperand(i_nocapture: 0));
3291 const MCExpr *RHS = lowerConstant(CV: CE->getOperand(i_nocapture: 1));
3292 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
3293 break;
3294 }
3295
3296 case Instruction::Add: {
3297 const MCExpr *LHS = lowerConstant(CV: CE->getOperand(i_nocapture: 0));
3298 const MCExpr *RHS = lowerConstant(CV: CE->getOperand(i_nocapture: 1));
3299 return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
3300 }
3301 }
3302
3303 // If the code isn't optimized, there may be outstanding folding
3304 // opportunities. Attempt to fold the expression using DataLayout as a
3305 // last resort before giving up.
3306 Constant *C = ConstantFoldConstant(C: CE, DL: getDataLayout());
3307 if (C != CE)
3308 return lowerConstant(CV: C);
3309
3310 // Otherwise report the problem to the user.
3311 std::string S;
3312 raw_string_ostream OS(S);
3313 OS << "Unsupported expression in static initializer: ";
3314 CE->printAsOperand(O&: OS, /*PrintType=*/false,
3315 M: !MF ? nullptr : MF->getFunction().getParent());
3316 report_fatal_error(reason: Twine(OS.str()));
3317}
3318
3319static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
3320 AsmPrinter &AP,
3321 const Constant *BaseCV = nullptr,
3322 uint64_t Offset = 0,
3323 AsmPrinter::AliasMapTy *AliasList = nullptr);
3324
3325static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
3326static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP);
3327
3328/// isRepeatedByteSequence - Determine whether the given value is
3329/// composed of a repeated sequence of identical bytes and return the
3330/// byte value. If it is not a repeated sequence, return -1.
3331static int isRepeatedByteSequence(const ConstantDataSequential *V) {
3332 StringRef Data = V->getRawDataValues();
3333 assert(!Data.empty() && "Empty aggregates should be CAZ node");
3334 char C = Data[0];
3335 for (unsigned i = 1, e = Data.size(); i != e; ++i)
3336 if (Data[i] != C) return -1;
3337 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
3338}
3339
3340/// isRepeatedByteSequence - Determine whether the given value is
3341/// composed of a repeated sequence of identical bytes and return the
3342/// byte value. If it is not a repeated sequence, return -1.
3343static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
3344 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val: V)) {
3345 uint64_t Size = DL.getTypeAllocSizeInBits(Ty: V->getType());
3346 assert(Size % 8 == 0);
3347
3348 // Extend the element to take zero padding into account.
3349 APInt Value = CI->getValue().zext(width: Size);
3350 if (!Value.isSplat(SplatSizeInBits: 8))
3351 return -1;
3352
3353 return Value.zextOrTrunc(width: 8).getZExtValue();
3354 }
3355 if (const ConstantArray *CA = dyn_cast<ConstantArray>(Val: V)) {
3356 // Make sure all array elements are sequences of the same repeated
3357 // byte.
3358 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
3359 Constant *Op0 = CA->getOperand(i_nocapture: 0);
3360 int Byte = isRepeatedByteSequence(V: Op0, DL);
3361 if (Byte == -1)
3362 return -1;
3363
3364 // All array elements must be equal.
3365 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
3366 if (CA->getOperand(i_nocapture: i) != Op0)
3367 return -1;
3368 return Byte;
3369 }
3370
3371 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(Val: V))
3372 return isRepeatedByteSequence(V: CDS);
3373
3374 return -1;
3375}
3376
3377static void emitGlobalAliasInline(AsmPrinter &AP, uint64_t Offset,
3378 AsmPrinter::AliasMapTy *AliasList) {
3379 if (AliasList) {
3380 auto AliasIt = AliasList->find(Val: Offset);
3381 if (AliasIt != AliasList->end()) {
3382 for (const GlobalAlias *GA : AliasIt->second)
3383 AP.OutStreamer->emitLabel(Symbol: AP.getSymbol(GV: GA));
3384 AliasList->erase(Val: Offset);
3385 }
3386 }
3387}
3388
3389static void emitGlobalConstantDataSequential(
3390 const DataLayout &DL, const ConstantDataSequential *CDS, AsmPrinter &AP,
3391 AsmPrinter::AliasMapTy *AliasList) {
3392 // See if we can aggregate this into a .fill, if so, emit it as such.
3393 int Value = isRepeatedByteSequence(V: CDS, DL);
3394 if (Value != -1) {
3395 uint64_t Bytes = DL.getTypeAllocSize(Ty: CDS->getType());
3396 // Don't emit a 1-byte object as a .fill.
3397 if (Bytes > 1)
3398 return AP.OutStreamer->emitFill(NumBytes: Bytes, FillValue: Value);
3399 }
3400
3401 // If this can be emitted with .ascii/.asciz, emit it as such.
3402 if (CDS->isString())
3403 return AP.OutStreamer->emitBytes(Data: CDS->getAsString());
3404
3405 // Otherwise, emit the values in successive locations.
3406 unsigned ElementByteSize = CDS->getElementByteSize();
3407 if (isa<IntegerType>(Val: CDS->getElementType())) {
3408 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) {
3409 emitGlobalAliasInline(AP, Offset: ElementByteSize * I, AliasList);
3410 if (AP.isVerbose())
3411 AP.OutStreamer->getCommentOS()
3412 << format(Fmt: "0x%" PRIx64 "\n", Vals: CDS->getElementAsInteger(i: I));
3413 AP.OutStreamer->emitIntValue(Value: CDS->getElementAsInteger(i: I),
3414 Size: ElementByteSize);
3415 }
3416 } else {
3417 Type *ET = CDS->getElementType();
3418 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) {
3419 emitGlobalAliasInline(AP, Offset: ElementByteSize * I, AliasList);
3420 emitGlobalConstantFP(APF: CDS->getElementAsAPFloat(i: I), ET, AP);
3421 }
3422 }
3423
3424 unsigned Size = DL.getTypeAllocSize(Ty: CDS->getType());
3425 unsigned EmittedSize =
3426 DL.getTypeAllocSize(Ty: CDS->getElementType()) * CDS->getNumElements();
3427 assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!");
3428 if (unsigned Padding = Size - EmittedSize)
3429 AP.OutStreamer->emitZeros(NumBytes: Padding);
3430}
3431
3432static void emitGlobalConstantArray(const DataLayout &DL,
3433 const ConstantArray *CA, AsmPrinter &AP,
3434 const Constant *BaseCV, uint64_t Offset,
3435 AsmPrinter::AliasMapTy *AliasList) {
3436 // See if we can aggregate some values. Make sure it can be
3437 // represented as a series of bytes of the constant value.
3438 int Value = isRepeatedByteSequence(V: CA, DL);
3439
3440 if (Value != -1) {
3441 uint64_t Bytes = DL.getTypeAllocSize(Ty: CA->getType());
3442 AP.OutStreamer->emitFill(NumBytes: Bytes, FillValue: Value);
3443 } else {
3444 for (unsigned I = 0, E = CA->getNumOperands(); I != E; ++I) {
3445 emitGlobalConstantImpl(DL, C: CA->getOperand(i_nocapture: I), AP, BaseCV, Offset,
3446 AliasList);
3447 Offset += DL.getTypeAllocSize(Ty: CA->getOperand(i_nocapture: I)->getType());
3448 }
3449 }
3450}
3451
3452static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP);
3453
3454static void emitGlobalConstantVector(const DataLayout &DL,
3455 const ConstantVector *CV, AsmPrinter &AP,
3456 AsmPrinter::AliasMapTy *AliasList) {
3457 Type *ElementType = CV->getType()->getElementType();
3458 uint64_t ElementSizeInBits = DL.getTypeSizeInBits(Ty: ElementType);
3459 uint64_t ElementAllocSizeInBits = DL.getTypeAllocSizeInBits(Ty: ElementType);
3460 uint64_t EmittedSize;
3461 if (ElementSizeInBits != ElementAllocSizeInBits) {
3462 // If the allocation size of an element is different from the size in bits,
3463 // printing each element separately will insert incorrect padding.
3464 //
3465 // The general algorithm here is complicated; instead of writing it out
3466 // here, just use the existing code in ConstantFolding.
3467 Type *IntT =
3468 IntegerType::get(C&: CV->getContext(), NumBits: DL.getTypeSizeInBits(Ty: CV->getType()));
3469 ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Val: ConstantFoldConstant(
3470 C: ConstantExpr::getBitCast(C: const_cast<ConstantVector *>(CV), Ty: IntT), DL));
3471 if (!CI) {
3472 report_fatal_error(
3473 reason: "Cannot lower vector global with unusual element type");
3474 }
3475 emitGlobalAliasInline(AP, Offset: 0, AliasList);
3476 emitGlobalConstantLargeInt(CI, AP);
3477 EmittedSize = DL.getTypeStoreSize(Ty: CV->getType());
3478 } else {
3479 for (unsigned I = 0, E = CV->getType()->getNumElements(); I != E; ++I) {
3480 emitGlobalAliasInline(AP, Offset: DL.getTypeAllocSize(Ty: CV->getType()) * I, AliasList);
3481 emitGlobalConstantImpl(DL, C: CV->getOperand(i_nocapture: I), AP);
3482 }
3483 EmittedSize =
3484 DL.getTypeAllocSize(Ty: ElementType) * CV->getType()->getNumElements();
3485 }
3486
3487 unsigned Size = DL.getTypeAllocSize(Ty: CV->getType());
3488 if (unsigned Padding = Size - EmittedSize)
3489 AP.OutStreamer->emitZeros(NumBytes: Padding);
3490}
3491
3492static void emitGlobalConstantStruct(const DataLayout &DL,
3493 const ConstantStruct *CS, AsmPrinter &AP,
3494 const Constant *BaseCV, uint64_t Offset,
3495 AsmPrinter::AliasMapTy *AliasList) {
3496 // Print the fields in successive locations. Pad to align if needed!
3497 unsigned Size = DL.getTypeAllocSize(Ty: CS->getType());
3498 const StructLayout *Layout = DL.getStructLayout(Ty: CS->getType());
3499 uint64_t SizeSoFar = 0;
3500 for (unsigned I = 0, E = CS->getNumOperands(); I != E; ++I) {
3501 const Constant *Field = CS->getOperand(i_nocapture: I);
3502
3503 // Print the actual field value.
3504 emitGlobalConstantImpl(DL, C: Field, AP, BaseCV, Offset: Offset + SizeSoFar,
3505 AliasList);
3506
3507 // Check if padding is needed and insert one or more 0s.
3508 uint64_t FieldSize = DL.getTypeAllocSize(Ty: Field->getType());
3509 uint64_t PadSize = ((I == E - 1 ? Size : Layout->getElementOffset(Idx: I + 1)) -
3510 Layout->getElementOffset(Idx: I)) -
3511 FieldSize;
3512 SizeSoFar += FieldSize + PadSize;
3513
3514 // Insert padding - this may include padding to increase the size of the
3515 // current field up to the ABI size (if the struct is not packed) as well
3516 // as padding to ensure that the next field starts at the right offset.
3517 AP.OutStreamer->emitZeros(NumBytes: PadSize);
3518 }
3519 assert(SizeSoFar == Layout->getSizeInBytes() &&
3520 "Layout of constant struct may be incorrect!");
3521}
3522
3523static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) {
3524 assert(ET && "Unknown float type");
3525 APInt API = APF.bitcastToAPInt();
3526
3527 // First print a comment with what we think the original floating-point value
3528 // should have been.
3529 if (AP.isVerbose()) {
3530 SmallString<8> StrVal;
3531 APF.toString(Str&: StrVal);
3532 ET->print(O&: AP.OutStreamer->getCommentOS());
3533 AP.OutStreamer->getCommentOS() << ' ' << StrVal << '\n';
3534 }
3535
3536 // Now iterate through the APInt chunks, emitting them in endian-correct
3537 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
3538 // floats).
3539 unsigned NumBytes = API.getBitWidth() / 8;
3540 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
3541 const uint64_t *p = API.getRawData();
3542
3543 // PPC's long double has odd notions of endianness compared to how LLVM
3544 // handles it: p[0] goes first for *big* endian on PPC.
3545 if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) {
3546 int Chunk = API.getNumWords() - 1;
3547
3548 if (TrailingBytes)
3549 AP.OutStreamer->emitIntValueInHexWithPadding(Value: p[Chunk--], Size: TrailingBytes);
3550
3551 for (; Chunk >= 0; --Chunk)
3552 AP.OutStreamer->emitIntValueInHexWithPadding(Value: p[Chunk], Size: sizeof(uint64_t));
3553 } else {
3554 unsigned Chunk;
3555 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
3556 AP.OutStreamer->emitIntValueInHexWithPadding(Value: p[Chunk], Size: sizeof(uint64_t));
3557
3558 if (TrailingBytes)
3559 AP.OutStreamer->emitIntValueInHexWithPadding(Value: p[Chunk], Size: TrailingBytes);
3560 }
3561
3562 // Emit the tail padding for the long double.
3563 const DataLayout &DL = AP.getDataLayout();
3564 AP.OutStreamer->emitZeros(NumBytes: DL.getTypeAllocSize(Ty: ET) - DL.getTypeStoreSize(Ty: ET));
3565}
3566
3567static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
3568 emitGlobalConstantFP(APF: CFP->getValueAPF(), ET: CFP->getType(), AP);
3569}
3570
3571static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
3572 const DataLayout &DL = AP.getDataLayout();
3573 unsigned BitWidth = CI->getBitWidth();
3574
3575 // Copy the value as we may massage the layout for constants whose bit width
3576 // is not a multiple of 64-bits.
3577 APInt Realigned(CI->getValue());
3578 uint64_t ExtraBits = 0;
3579 unsigned ExtraBitsSize = BitWidth & 63;
3580
3581 if (ExtraBitsSize) {
3582 // The bit width of the data is not a multiple of 64-bits.
3583 // The extra bits are expected to be at the end of the chunk of the memory.
3584 // Little endian:
3585 // * Nothing to be done, just record the extra bits to emit.
3586 // Big endian:
3587 // * Record the extra bits to emit.
3588 // * Realign the raw data to emit the chunks of 64-bits.
3589 if (DL.isBigEndian()) {
3590 // Basically the structure of the raw data is a chunk of 64-bits cells:
3591 // 0 1 BitWidth / 64
3592 // [chunk1][chunk2] ... [chunkN].
3593 // The most significant chunk is chunkN and it should be emitted first.
3594 // However, due to the alignment issue chunkN contains useless bits.
3595 // Realign the chunks so that they contain only useful information:
3596 // ExtraBits 0 1 (BitWidth / 64) - 1
3597 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
3598 ExtraBitsSize = alignTo(Value: ExtraBitsSize, Align: 8);
3599 ExtraBits = Realigned.getRawData()[0] &
3600 (((uint64_t)-1) >> (64 - ExtraBitsSize));
3601 if (BitWidth >= 64)
3602 Realigned.lshrInPlace(ShiftAmt: ExtraBitsSize);
3603 } else
3604 ExtraBits = Realigned.getRawData()[BitWidth / 64];
3605 }
3606
3607 // We don't expect assemblers to support integer data directives
3608 // for more than 64 bits, so we emit the data in at most 64-bit
3609 // quantities at a time.
3610 const uint64_t *RawData = Realigned.getRawData();
3611 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
3612 uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
3613 AP.OutStreamer->emitIntValue(Value: Val, Size: 8);
3614 }
3615
3616 if (ExtraBitsSize) {
3617 // Emit the extra bits after the 64-bits chunks.
3618
3619 // Emit a directive that fills the expected size.
3620 uint64_t Size = AP.getDataLayout().getTypeStoreSize(Ty: CI->getType());
3621 Size -= (BitWidth / 64) * 8;
3622 assert(Size && Size * 8 >= ExtraBitsSize &&
3623 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
3624 == ExtraBits && "Directive too small for extra bits.");
3625 AP.OutStreamer->emitIntValue(Value: ExtraBits, Size);
3626 }
3627}
3628
3629/// Transform a not absolute MCExpr containing a reference to a GOT
3630/// equivalent global, by a target specific GOT pc relative access to the
3631/// final symbol.
3632static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
3633 const Constant *BaseCst,
3634 uint64_t Offset) {
3635 // The global @foo below illustrates a global that uses a got equivalent.
3636 //
3637 // @bar = global i32 42
3638 // @gotequiv = private unnamed_addr constant i32* @bar
3639 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
3640 // i64 ptrtoint (i32* @foo to i64))
3641 // to i32)
3642 //
3643 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
3644 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
3645 // form:
3646 //
3647 // foo = cstexpr, where
3648 // cstexpr := <gotequiv> - "." + <cst>
3649 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
3650 //
3651 // After canonicalization by evaluateAsRelocatable `ME` turns into:
3652 //
3653 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
3654 // gotpcrelcst := <offset from @foo base> + <cst>
3655 MCValue MV;
3656 if (!(*ME)->evaluateAsRelocatable(Res&: MV, Layout: nullptr, Fixup: nullptr) || MV.isAbsolute())
3657 return;
3658 const MCSymbolRefExpr *SymA = MV.getSymA();
3659 if (!SymA)
3660 return;
3661
3662 // Check that GOT equivalent symbol is cached.
3663 const MCSymbol *GOTEquivSym = &SymA->getSymbol();
3664 if (!AP.GlobalGOTEquivs.count(Key: GOTEquivSym))
3665 return;
3666
3667 const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(Val: BaseCst);
3668 if (!BaseGV)
3669 return;
3670
3671 // Check for a valid base symbol
3672 const MCSymbol *BaseSym = AP.getSymbol(GV: BaseGV);
3673 const MCSymbolRefExpr *SymB = MV.getSymB();
3674
3675 if (!SymB || BaseSym != &SymB->getSymbol())
3676 return;
3677
3678 // Make sure to match:
3679 //
3680 // gotpcrelcst := <offset from @foo base> + <cst>
3681 //
3682 int64_t GOTPCRelCst = Offset + MV.getConstant();
3683 if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
3684 return;
3685
3686 // Emit the GOT PC relative to replace the got equivalent global, i.e.:
3687 //
3688 // bar:
3689 // .long 42
3690 // gotequiv:
3691 // .quad bar
3692 // foo:
3693 // .long gotequiv - "." + <cst>
3694 //
3695 // is replaced by the target specific equivalent to:
3696 //
3697 // bar:
3698 // .long 42
3699 // foo:
3700 // .long bar@GOTPCREL+<gotpcrelcst>
3701 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
3702 const GlobalVariable *GV = Result.first;
3703 int NumUses = (int)Result.second;
3704 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(Val: GV->getOperand(i_nocapture: 0));
3705 const MCSymbol *FinalSym = AP.getSymbol(GV: FinalGV);
3706 *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel(
3707 GV: FinalGV, Sym: FinalSym, MV, Offset, MMI: AP.MMI, Streamer&: *AP.OutStreamer);
3708
3709 // Update GOT equivalent usage information
3710 --NumUses;
3711 if (NumUses >= 0)
3712 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(x&: GV, y&: NumUses);
3713}
3714
3715static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
3716 AsmPrinter &AP, const Constant *BaseCV,
3717 uint64_t Offset,
3718 AsmPrinter::AliasMapTy *AliasList) {
3719 emitGlobalAliasInline(AP, Offset, AliasList);
3720 uint64_t Size = DL.getTypeAllocSize(Ty: CV->getType());
3721
3722 // Globals with sub-elements such as combinations of arrays and structs
3723 // are handled recursively by emitGlobalConstantImpl. Keep track of the
3724 // constant symbol base and the current position with BaseCV and Offset.
3725 if (!BaseCV && CV->hasOneUse())
3726 BaseCV = dyn_cast<Constant>(Val: CV->user_back());
3727
3728 if (isa<ConstantAggregateZero>(Val: CV) || isa<UndefValue>(Val: CV))
3729 return AP.OutStreamer->emitZeros(NumBytes: Size);
3730
3731 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val: CV)) {
3732 const uint64_t StoreSize = DL.getTypeStoreSize(Ty: CV->getType());
3733
3734 if (StoreSize <= 8) {
3735 if (AP.isVerbose())
3736 AP.OutStreamer->getCommentOS()
3737 << format(Fmt: "0x%" PRIx64 "\n", Vals: CI->getZExtValue());
3738 AP.OutStreamer->emitIntValue(Value: CI->getZExtValue(), Size: StoreSize);
3739 } else {
3740 emitGlobalConstantLargeInt(CI, AP);
3741 }
3742
3743 // Emit tail padding if needed
3744 if (Size != StoreSize)
3745 AP.OutStreamer->emitZeros(NumBytes: Size - StoreSize);
3746
3747 return;
3748 }
3749
3750 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Val: CV))
3751 return emitGlobalConstantFP(CFP, AP);
3752
3753 if (isa<ConstantPointerNull>(Val: CV)) {
3754 AP.OutStreamer->emitIntValue(Value: 0, Size);
3755 return;
3756 }
3757
3758 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(Val: CV))
3759 return emitGlobalConstantDataSequential(DL, CDS, AP, AliasList);
3760
3761 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(Val: CV))
3762 return emitGlobalConstantArray(DL, CA: CVA, AP, BaseCV, Offset, AliasList);
3763
3764 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(Val: CV))
3765 return emitGlobalConstantStruct(DL, CS: CVS, AP, BaseCV, Offset, AliasList);
3766
3767 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Val: CV)) {
3768 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
3769 // vectors).
3770 if (CE->getOpcode() == Instruction::BitCast)
3771 return emitGlobalConstantImpl(DL, CV: CE->getOperand(i_nocapture: 0), AP);
3772
3773 if (Size > 8) {
3774 // If the constant expression's size is greater than 64-bits, then we have
3775 // to emit the value in chunks. Try to constant fold the value and emit it
3776 // that way.
3777 Constant *New = ConstantFoldConstant(C: CE, DL);
3778 if (New != CE)
3779 return emitGlobalConstantImpl(DL, CV: New, AP);
3780 }
3781 }
3782
3783 if (const ConstantVector *V = dyn_cast<ConstantVector>(Val: CV))
3784 return emitGlobalConstantVector(DL, CV: V, AP, AliasList);
3785
3786 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
3787 // thread the streamer with EmitValue.
3788 const MCExpr *ME = AP.lowerConstant(CV);
3789
3790 // Since lowerConstant already folded and got rid of all IR pointer and
3791 // integer casts, detect GOT equivalent accesses by looking into the MCExpr
3792 // directly.
3793 if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel())
3794 handleIndirectSymViaGOTPCRel(AP, ME: &ME, BaseCst: BaseCV, Offset);
3795
3796 AP.OutStreamer->emitValue(Value: ME, Size);
3797}
3798
3799/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
3800void AsmPrinter::emitGlobalConstant(const DataLayout &DL, const Constant *CV,
3801 AliasMapTy *AliasList) {
3802 uint64_t Size = DL.getTypeAllocSize(Ty: CV->getType());
3803 if (Size)
3804 emitGlobalConstantImpl(DL, CV, AP&: *this, BaseCV: nullptr, Offset: 0, AliasList);
3805 else if (MAI->hasSubsectionsViaSymbols()) {
3806 // If the global has zero size, emit a single byte so that two labels don't
3807 // look like they are at the same location.
3808 OutStreamer->emitIntValue(Value: 0, Size: 1);
3809 }
3810 if (!AliasList)
3811 return;
3812 // TODO: These remaining aliases are not emitted in the correct location. Need
3813 // to handle the case where the alias offset doesn't refer to any sub-element.
3814 for (auto &AliasPair : *AliasList) {
3815 for (const GlobalAlias *GA : AliasPair.second)
3816 OutStreamer->emitLabel(Symbol: getSymbol(GV: GA));
3817 }
3818}
3819
3820void AsmPrinter::emitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
3821 // Target doesn't support this yet!
3822 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
3823}
3824
3825void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
3826 if (Offset > 0)
3827 OS << '+' << Offset;
3828 else if (Offset < 0)
3829 OS << Offset;
3830}
3831
3832void AsmPrinter::emitNops(unsigned N) {
3833 MCInst Nop = MF->getSubtarget().getInstrInfo()->getNop();
3834 for (; N; --N)
3835 EmitToStreamer(S&: *OutStreamer, Inst: Nop);
3836}
3837
3838//===----------------------------------------------------------------------===//
3839// Symbol Lowering Routines.
3840//===----------------------------------------------------------------------===//
3841
3842MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const {
3843 return OutContext.createTempSymbol(Name, AlwaysAddSuffix: true);
3844}
3845
3846MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
3847 return const_cast<AsmPrinter *>(this)->getAddrLabelSymbol(
3848 BB: BA->getBasicBlock());
3849}
3850
3851MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
3852 return const_cast<AsmPrinter *>(this)->getAddrLabelSymbol(BB);
3853}
3854
3855/// GetCPISymbol - Return the symbol for the specified constant pool entry.
3856MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
3857 if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment()) {
3858 const MachineConstantPoolEntry &CPE =
3859 MF->getConstantPool()->getConstants()[CPID];
3860 if (!CPE.isMachineConstantPoolEntry()) {
3861 const DataLayout &DL = MF->getDataLayout();
3862 SectionKind Kind = CPE.getSectionKind(DL: &DL);
3863 const Constant *C = CPE.Val.ConstVal;
3864 Align Alignment = CPE.Alignment;
3865 if (const MCSectionCOFF *S = dyn_cast<MCSectionCOFF>(
3866 Val: getObjFileLowering().getSectionForConstant(DL, Kind, C,
3867 Alignment))) {
3868 if (MCSymbol *Sym = S->getCOMDATSymbol()) {
3869 if (Sym->isUndefined())
3870 OutStreamer->emitSymbolAttribute(Symbol: Sym, Attribute: MCSA_Global);
3871 return Sym;
3872 }
3873 }
3874 }
3875 }
3876
3877 const DataLayout &DL = getDataLayout();
3878 return OutContext.getOrCreateSymbol(Name: Twine(DL.getPrivateGlobalPrefix()) +
3879 "CPI" + Twine(getFunctionNumber()) + "_" +
3880 Twine(CPID));
3881}
3882
3883/// GetJTISymbol - Return the symbol for the specified jump table entry.
3884MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
3885 return MF->getJTISymbol(JTI: JTID, Ctx&: OutContext, isLinkerPrivate);
3886}
3887
3888/// GetJTSetSymbol - Return the symbol for the specified jump table .set
3889/// FIXME: privatize to AsmPrinter.
3890MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
3891 const DataLayout &DL = getDataLayout();
3892 return OutContext.getOrCreateSymbol(Name: Twine(DL.getPrivateGlobalPrefix()) +
3893 Twine(getFunctionNumber()) + "_" +
3894 Twine(UID) + "_set_" + Twine(MBBID));
3895}
3896
3897MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
3898 StringRef Suffix) const {
3899 return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, TM);
3900}
3901
3902/// Return the MCSymbol for the specified ExternalSymbol.
3903MCSymbol *AsmPrinter::GetExternalSymbolSymbol(Twine Sym) const {
3904 SmallString<60> NameStr;
3905 Mangler::getNameWithPrefix(OutName&: NameStr, GVName: Sym, DL: getDataLayout());
3906 return OutContext.getOrCreateSymbol(Name: NameStr);
3907}
3908
3909/// PrintParentLoopComment - Print comments about parent loops of this one.
3910static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
3911 unsigned FunctionNumber) {
3912 if (!Loop) return;
3913 PrintParentLoopComment(OS, Loop: Loop->getParentLoop(), FunctionNumber);
3914 OS.indent(NumSpaces: Loop->getLoopDepth()*2)
3915 << "Parent Loop BB" << FunctionNumber << "_"
3916 << Loop->getHeader()->getNumber()
3917 << " Depth=" << Loop->getLoopDepth() << '\n';
3918}
3919
3920/// PrintChildLoopComment - Print comments about child loops within
3921/// the loop for this basic block, with nesting.
3922static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
3923 unsigned FunctionNumber) {
3924 // Add child loop information
3925 for (const MachineLoop *CL : *Loop) {
3926 OS.indent(NumSpaces: CL->getLoopDepth()*2)
3927 << "Child Loop BB" << FunctionNumber << "_"
3928 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
3929 << '\n';
3930 PrintChildLoopComment(OS, Loop: CL, FunctionNumber);
3931 }
3932}
3933
3934/// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
3935static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
3936 const MachineLoopInfo *LI,
3937 const AsmPrinter &AP) {
3938 // Add loop depth information
3939 const MachineLoop *Loop = LI->getLoopFor(BB: &MBB);
3940 if (!Loop) return;
3941
3942 MachineBasicBlock *Header = Loop->getHeader();
3943 assert(Header && "No header for loop");
3944
3945 // If this block is not a loop header, just print out what is the loop header
3946 // and return.
3947 if (Header != &MBB) {
3948 AP.OutStreamer->AddComment(T: " in Loop: Header=BB" +
3949 Twine(AP.getFunctionNumber())+"_" +
3950 Twine(Loop->getHeader()->getNumber())+
3951 " Depth="+Twine(Loop->getLoopDepth()));
3952 return;
3953 }
3954
3955 // Otherwise, it is a loop header. Print out information about child and
3956 // parent loops.
3957 raw_ostream &OS = AP.OutStreamer->getCommentOS();
3958
3959 PrintParentLoopComment(OS, Loop: Loop->getParentLoop(), FunctionNumber: AP.getFunctionNumber());
3960
3961 OS << "=>";
3962 OS.indent(NumSpaces: Loop->getLoopDepth()*2-2);
3963
3964 OS << "This ";
3965 if (Loop->isInnermost())
3966 OS << "Inner ";
3967 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
3968
3969 PrintChildLoopComment(OS, Loop, FunctionNumber: AP.getFunctionNumber());
3970}
3971
3972/// emitBasicBlockStart - This method prints the label for the specified
3973/// MachineBasicBlock, an alignment (if present) and a comment describing
3974/// it if appropriate.
3975void AsmPrinter::emitBasicBlockStart(const MachineBasicBlock &MBB) {
3976 // End the previous funclet and start a new one.
3977 if (MBB.isEHFuncletEntry()) {
3978 for (const HandlerInfo &HI : Handlers) {
3979 HI.Handler->endFunclet();
3980 HI.Handler->beginFunclet(MBB);
3981 }
3982 }
3983
3984 // Switch to a new section if this basic block must begin a section. The
3985 // entry block is always placed in the function section and is handled
3986 // separately.
3987 if (MBB.isBeginSection() && !MBB.isEntryBlock()) {
3988 OutStreamer->switchSection(
3989 Section: getObjFileLowering().getSectionForMachineBasicBlock(F: MF->getFunction(),
3990 MBB, TM));
3991 CurrentSectionBeginSym = MBB.getSymbol();
3992 }
3993
3994 // Emit an alignment directive for this block, if needed.
3995 const Align Alignment = MBB.getAlignment();
3996 if (Alignment != Align(1))
3997 emitAlignment(Alignment, GV: nullptr, MaxBytesToEmit: MBB.getMaxBytesForAlignment());
3998
3999 // If the block has its address taken, emit any labels that were used to
4000 // reference the block. It is possible that there is more than one label
4001 // here, because multiple LLVM BB's may have been RAUW'd to this block after
4002 // the references were generated.
4003 if (MBB.isIRBlockAddressTaken()) {
4004 if (isVerbose())
4005 OutStreamer->AddComment(T: "Block address taken");
4006
4007 BasicBlock *BB = MBB.getAddressTakenIRBlock();
4008 assert(BB && BB->hasAddressTaken() && "Missing BB");
4009 for (MCSymbol *Sym : getAddrLabelSymbolToEmit(BB))
4010 OutStreamer->emitLabel(Symbol: Sym);
4011 } else if (isVerbose() && MBB.isMachineBlockAddressTaken()) {
4012 OutStreamer->AddComment(T: "Block address taken");
4013 }
4014
4015 // Print some verbose block comments.
4016 if (isVerbose()) {
4017 if (const BasicBlock *BB = MBB.getBasicBlock()) {
4018 if (BB->hasName()) {
4019 BB->printAsOperand(O&: OutStreamer->getCommentOS(),
4020 /*PrintType=*/false, M: BB->getModule());
4021 OutStreamer->getCommentOS() << '\n';
4022 }
4023 }
4024
4025 assert(MLI != nullptr && "MachineLoopInfo should has been computed");
4026 emitBasicBlockLoopComments(MBB, LI: MLI, AP: *this);
4027 }
4028
4029 // Print the main label for the block.
4030 if (shouldEmitLabelForBasicBlock(MBB)) {
4031 if (isVerbose() && MBB.hasLabelMustBeEmitted())
4032 OutStreamer->AddComment(T: "Label of block must be emitted");
4033 OutStreamer->emitLabel(Symbol: MBB.getSymbol());
4034 } else {
4035 if (isVerbose()) {
4036 // NOTE: Want this comment at start of line, don't emit with AddComment.
4037 OutStreamer->emitRawComment(T: " %bb." + Twine(MBB.getNumber()) + ":",
4038 TabPrefix: false);
4039 }
4040 }
4041
4042 if (MBB.isEHCatchretTarget() &&
4043 MAI->getExceptionHandlingType() == ExceptionHandling::WinEH) {
4044 OutStreamer->emitLabel(Symbol: MBB.getEHCatchretSymbol());
4045 }
4046
4047 // With BB sections, each basic block must handle CFI information on its own
4048 // if it begins a section (Entry block call is handled separately, next to
4049 // beginFunction).
4050 if (MBB.isBeginSection() && !MBB.isEntryBlock())
4051 for (const HandlerInfo &HI : Handlers)
4052 HI.Handler->beginBasicBlockSection(MBB);
4053}
4054
4055void AsmPrinter::emitBasicBlockEnd(const MachineBasicBlock &MBB) {
4056 // Check if CFI information needs to be updated for this MBB with basic block
4057 // sections.
4058 if (MBB.isEndSection())
4059 for (const HandlerInfo &HI : Handlers)
4060 HI.Handler->endBasicBlockSection(MBB);
4061}
4062
4063void AsmPrinter::emitVisibility(MCSymbol *Sym, unsigned Visibility,
4064 bool IsDefinition) const {
4065 MCSymbolAttr Attr = MCSA_Invalid;
4066
4067 switch (Visibility) {
4068 default: break;
4069 case GlobalValue::HiddenVisibility:
4070 if (IsDefinition)
4071 Attr = MAI->getHiddenVisibilityAttr();
4072 else
4073 Attr = MAI->getHiddenDeclarationVisibilityAttr();
4074 break;
4075 case GlobalValue::ProtectedVisibility:
4076 Attr = MAI->getProtectedVisibilityAttr();
4077 break;
4078 }
4079
4080 if (Attr != MCSA_Invalid)
4081 OutStreamer->emitSymbolAttribute(Symbol: Sym, Attribute: Attr);
4082}
4083
4084bool AsmPrinter::shouldEmitLabelForBasicBlock(
4085 const MachineBasicBlock &MBB) const {
4086 // With `-fbasic-block-sections=`, a label is needed for every non-entry block
4087 // in the labels mode (option `=labels`) and every section beginning in the
4088 // sections mode (`=all` and `=list=`).
4089 if ((MF->hasBBLabels() || MF->getTarget().Options.BBAddrMap ||
4090 MBB.isBeginSection()) &&
4091 !MBB.isEntryBlock())
4092 return true;
4093 // A label is needed for any block with at least one predecessor (when that
4094 // predecessor is not the fallthrough predecessor, or if it is an EH funclet
4095 // entry, or if a label is forced).
4096 return !MBB.pred_empty() &&
4097 (!isBlockOnlyReachableByFallthrough(MBB: &MBB) || MBB.isEHFuncletEntry() ||
4098 MBB.hasLabelMustBeEmitted());
4099}
4100
4101/// isBlockOnlyReachableByFallthough - Return true if the basic block has
4102/// exactly one predecessor and the control transfer mechanism between
4103/// the predecessor and this block is a fall-through.
4104bool AsmPrinter::
4105isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
4106 // If this is a landing pad, it isn't a fall through. If it has no preds,
4107 // then nothing falls through to it.
4108 if (MBB->isEHPad() || MBB->pred_empty())
4109 return false;
4110
4111 // If there isn't exactly one predecessor, it can't be a fall through.
4112 if (MBB->pred_size() > 1)
4113 return false;
4114
4115 // The predecessor has to be immediately before this block.
4116 MachineBasicBlock *Pred = *MBB->pred_begin();
4117 if (!Pred->isLayoutSuccessor(MBB))
4118 return false;
4119
4120 // If the block is completely empty, then it definitely does fall through.
4121 if (Pred->empty())
4122 return true;
4123
4124 // Check the terminators in the previous blocks
4125 for (const auto &MI : Pred->terminators()) {
4126 // If it is not a simple branch, we are in a table somewhere.
4127 if (!MI.isBranch() || MI.isIndirectBranch())
4128 return false;
4129
4130 // If we are the operands of one of the branches, this is not a fall
4131 // through. Note that targets with delay slots will usually bundle
4132 // terminators with the delay slot instruction.
4133 for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) {
4134 if (OP->isJTI())
4135 return false;
4136 if (OP->isMBB() && OP->getMBB() == MBB)
4137 return false;
4138 }
4139 }
4140
4141 return true;
4142}
4143
4144GCMetadataPrinter *AsmPrinter::getOrCreateGCPrinter(GCStrategy &S) {
4145 if (!S.usesMetadata())
4146 return nullptr;
4147
4148 auto [GCPI, Inserted] = GCMetadataPrinters.insert(KV: {&S, nullptr});
4149 if (!Inserted)
4150 return GCPI->second.get();
4151
4152 auto Name = S.getName();
4153
4154 for (const GCMetadataPrinterRegistry::entry &GCMetaPrinter :
4155 GCMetadataPrinterRegistry::entries())
4156 if (Name == GCMetaPrinter.getName()) {
4157 std::unique_ptr<GCMetadataPrinter> GMP = GCMetaPrinter.instantiate();
4158 GMP->S = &S;
4159 GCPI->second = std::move(GMP);
4160 return GCPI->second.get();
4161 }
4162
4163 report_fatal_error(reason: "no GCMetadataPrinter registered for GC: " + Twine(Name));
4164}
4165
4166void AsmPrinter::emitStackMaps() {
4167 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
4168 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
4169 bool NeedsDefault = false;
4170 if (MI->begin() == MI->end())
4171 // No GC strategy, use the default format.
4172 NeedsDefault = true;
4173 else
4174 for (const auto &I : *MI) {
4175 if (GCMetadataPrinter *MP = getOrCreateGCPrinter(S&: *I))
4176 if (MP->emitStackMaps(SM, AP&: *this))
4177 continue;
4178 // The strategy doesn't have printer or doesn't emit custom stack maps.
4179 // Use the default format.
4180 NeedsDefault = true;
4181 }
4182
4183 if (NeedsDefault)
4184 SM.serializeToStackMapSection();
4185}
4186
4187/// Pin vtable to this file.
4188AsmPrinterHandler::~AsmPrinterHandler() = default;
4189
4190void AsmPrinterHandler::markFunctionEnd() {}
4191
4192// In the binary's "xray_instr_map" section, an array of these function entries
4193// describes each instrumentation point. When XRay patches your code, the index
4194// into this table will be given to your handler as a patch point identifier.
4195void AsmPrinter::XRayFunctionEntry::emit(int Bytes, MCStreamer *Out) const {
4196 auto Kind8 = static_cast<uint8_t>(Kind);
4197 Out->emitBinaryData(Data: StringRef(reinterpret_cast<const char *>(&Kind8), 1));
4198 Out->emitBinaryData(
4199 Data: StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1));
4200 Out->emitBinaryData(Data: StringRef(reinterpret_cast<const char *>(&Version), 1));
4201 auto Padding = (4 * Bytes) - ((2 * Bytes) + 3);
4202 assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size");
4203 Out->emitZeros(NumBytes: Padding);
4204}
4205
4206void AsmPrinter::emitXRayTable() {
4207 if (Sleds.empty())
4208 return;
4209
4210 auto PrevSection = OutStreamer->getCurrentSectionOnly();
4211 const Function &F = MF->getFunction();
4212 MCSection *InstMap = nullptr;
4213 MCSection *FnSledIndex = nullptr;
4214 const Triple &TT = TM.getTargetTriple();
4215 // Use PC-relative addresses on all targets.
4216 if (TT.isOSBinFormatELF()) {
4217 auto LinkedToSym = cast<MCSymbolELF>(Val: CurrentFnSym);
4218 auto Flags = ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER;
4219 StringRef GroupName;
4220 if (F.hasComdat()) {
4221 Flags |= ELF::SHF_GROUP;
4222 GroupName = F.getComdat()->getName();
4223 }
4224 InstMap = OutContext.getELFSection(Section: "xray_instr_map", Type: ELF::SHT_PROGBITS,
4225 Flags, EntrySize: 0, Group: GroupName, IsComdat: F.hasComdat(),
4226 UniqueID: MCSection::NonUniqueID, LinkedToSym);
4227
4228 if (TM.Options.XRayFunctionIndex)
4229 FnSledIndex = OutContext.getELFSection(
4230 Section: "xray_fn_idx", Type: ELF::SHT_PROGBITS, Flags, EntrySize: 0, Group: GroupName, IsComdat: F.hasComdat(),
4231 UniqueID: MCSection::NonUniqueID, LinkedToSym);
4232 } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) {
4233 InstMap = OutContext.getMachOSection(Segment: "__DATA", Section: "xray_instr_map",
4234 TypeAndAttributes: MachO::S_ATTR_LIVE_SUPPORT,
4235 K: SectionKind::getReadOnlyWithRel());
4236 if (TM.Options.XRayFunctionIndex)
4237 FnSledIndex = OutContext.getMachOSection(Segment: "__DATA", Section: "xray_fn_idx",
4238 TypeAndAttributes: MachO::S_ATTR_LIVE_SUPPORT,
4239 K: SectionKind::getReadOnly());
4240 } else {
4241 llvm_unreachable("Unsupported target");
4242 }
4243
4244 auto WordSizeBytes = MAI->getCodePointerSize();
4245
4246 // Now we switch to the instrumentation map section. Because this is done
4247 // per-function, we are able to create an index entry that will represent the
4248 // range of sleds associated with a function.
4249 auto &Ctx = OutContext;
4250 MCSymbol *SledsStart =
4251 OutContext.createLinkerPrivateSymbol(Name: "xray_sleds_start");
4252 OutStreamer->switchSection(Section: InstMap);
4253 OutStreamer->emitLabel(Symbol: SledsStart);
4254 for (const auto &Sled : Sleds) {
4255 MCSymbol *Dot = Ctx.createTempSymbol();
4256 OutStreamer->emitLabel(Symbol: Dot);
4257 OutStreamer->emitValueImpl(
4258 Value: MCBinaryExpr::createSub(LHS: MCSymbolRefExpr::create(Symbol: Sled.Sled, Ctx),
4259 RHS: MCSymbolRefExpr::create(Symbol: Dot, Ctx), Ctx),
4260 Size: WordSizeBytes);
4261 OutStreamer->emitValueImpl(
4262 Value: MCBinaryExpr::createSub(
4263 LHS: MCSymbolRefExpr::create(Symbol: CurrentFnBegin, Ctx),
4264 RHS: MCBinaryExpr::createAdd(LHS: MCSymbolRefExpr::create(Symbol: Dot, Ctx),
4265 RHS: MCConstantExpr::create(Value: WordSizeBytes, Ctx),
4266 Ctx),
4267 Ctx),
4268 Size: WordSizeBytes);
4269 Sled.emit(Bytes: WordSizeBytes, Out: OutStreamer.get());
4270 }
4271 MCSymbol *SledsEnd = OutContext.createTempSymbol(Name: "xray_sleds_end", AlwaysAddSuffix: true);
4272 OutStreamer->emitLabel(Symbol: SledsEnd);
4273
4274 // We then emit a single entry in the index per function. We use the symbols
4275 // that bound the instrumentation map as the range for a specific function.
4276 // Each entry here will be 2 * word size aligned, as we're writing down two
4277 // pointers. This should work for both 32-bit and 64-bit platforms.
4278 if (FnSledIndex) {
4279 OutStreamer->switchSection(Section: FnSledIndex);
4280 OutStreamer->emitCodeAlignment(Alignment: Align(2 * WordSizeBytes),
4281 STI: &getSubtargetInfo());
4282 // For Mach-O, use an "l" symbol as the atom of this subsection. The label
4283 // difference uses a SUBTRACTOR external relocation which references the
4284 // symbol.
4285 MCSymbol *Dot = Ctx.createLinkerPrivateSymbol(Name: "xray_fn_idx");
4286 OutStreamer->emitLabel(Symbol: Dot);
4287 OutStreamer->emitValueImpl(
4288 Value: MCBinaryExpr::createSub(LHS: MCSymbolRefExpr::create(Symbol: SledsStart, Ctx),
4289 RHS: MCSymbolRefExpr::create(Symbol: Dot, Ctx), Ctx),
4290 Size: WordSizeBytes);
4291 OutStreamer->emitValueImpl(Value: MCConstantExpr::create(Value: Sleds.size(), Ctx),
4292 Size: WordSizeBytes);
4293 OutStreamer->switchSection(Section: PrevSection);
4294 }
4295 Sleds.clear();
4296}
4297
4298void AsmPrinter::recordSled(MCSymbol *Sled, const MachineInstr &MI,
4299 SledKind Kind, uint8_t Version) {
4300 const Function &F = MI.getMF()->getFunction();
4301 auto Attr = F.getFnAttribute(Kind: "function-instrument");
4302 bool LogArgs = F.hasFnAttribute(Kind: "xray-log-args");
4303 bool AlwaysInstrument =
4304 Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always";
4305 if (Kind == SledKind::FUNCTION_ENTER && LogArgs)
4306 Kind = SledKind::LOG_ARGS_ENTER;
4307 Sleds.emplace_back(Args: XRayFunctionEntry{.Sled: Sled, .Function: CurrentFnSym, .Kind: Kind,
4308 .AlwaysInstrument: AlwaysInstrument, .Fn: &F, .Version: Version});
4309}
4310
4311void AsmPrinter::emitPatchableFunctionEntries() {
4312 const Function &F = MF->getFunction();
4313 unsigned PatchableFunctionPrefix = 0, PatchableFunctionEntry = 0;
4314 (void)F.getFnAttribute(Kind: "patchable-function-prefix")
4315 .getValueAsString()
4316 .getAsInteger(Radix: 10, Result&: PatchableFunctionPrefix);
4317 (void)F.getFnAttribute(Kind: "patchable-function-entry")
4318 .getValueAsString()
4319 .getAsInteger(Radix: 10, Result&: PatchableFunctionEntry);
4320 if (!PatchableFunctionPrefix && !PatchableFunctionEntry)
4321 return;
4322 const unsigned PointerSize = getPointerSize();
4323 if (TM.getTargetTriple().isOSBinFormatELF()) {
4324 auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC;
4325 const MCSymbolELF *LinkedToSym = nullptr;
4326 StringRef GroupName;
4327
4328 // GNU as < 2.35 did not support section flag 'o'. GNU ld < 2.36 did not
4329 // support mixed SHF_LINK_ORDER and non-SHF_LINK_ORDER sections.
4330 if (MAI->useIntegratedAssembler() || MAI->binutilsIsAtLeast(Major: 2, Minor: 36)) {
4331 Flags |= ELF::SHF_LINK_ORDER;
4332 if (F.hasComdat()) {
4333 Flags |= ELF::SHF_GROUP;
4334 GroupName = F.getComdat()->getName();
4335 }
4336 LinkedToSym = cast<MCSymbolELF>(Val: CurrentFnSym);
4337 }
4338 OutStreamer->switchSection(Section: OutContext.getELFSection(
4339 Section: "__patchable_function_entries", Type: ELF::SHT_PROGBITS, Flags, EntrySize: 0, Group: GroupName,
4340 IsComdat: F.hasComdat(), UniqueID: MCSection::NonUniqueID, LinkedToSym));
4341 emitAlignment(Alignment: Align(PointerSize));
4342 OutStreamer->emitSymbolValue(Sym: CurrentPatchableFunctionEntrySym, Size: PointerSize);
4343 }
4344}
4345
4346uint16_t AsmPrinter::getDwarfVersion() const {
4347 return OutStreamer->getContext().getDwarfVersion();
4348}
4349
4350void AsmPrinter::setDwarfVersion(uint16_t Version) {
4351 OutStreamer->getContext().setDwarfVersion(Version);
4352}
4353
4354bool AsmPrinter::isDwarf64() const {
4355 return OutStreamer->getContext().getDwarfFormat() == dwarf::DWARF64;
4356}
4357
4358unsigned int AsmPrinter::getDwarfOffsetByteSize() const {
4359 return dwarf::getDwarfOffsetByteSize(
4360 Format: OutStreamer->getContext().getDwarfFormat());
4361}
4362
4363dwarf::FormParams AsmPrinter::getDwarfFormParams() const {
4364 return {.Version: getDwarfVersion(), .AddrSize: uint8_t(MAI->getCodePointerSize()),
4365 .Format: OutStreamer->getContext().getDwarfFormat(),
4366 .DwarfUsesRelocationsAcrossSections: doesDwarfUseRelocationsAcrossSections()};
4367}
4368
4369unsigned int AsmPrinter::getUnitLengthFieldByteSize() const {
4370 return dwarf::getUnitLengthFieldByteSize(
4371 Format: OutStreamer->getContext().getDwarfFormat());
4372}
4373
4374std::tuple<const MCSymbol *, uint64_t, const MCSymbol *,
4375 codeview::JumpTableEntrySize>
4376AsmPrinter::getCodeViewJumpTableInfo(int JTI, const MachineInstr *BranchInstr,
4377 const MCSymbol *BranchLabel) const {
4378 const auto TLI = MF->getSubtarget().getTargetLowering();
4379 const auto BaseExpr =
4380 TLI->getPICJumpTableRelocBaseExpr(MF, JTI, Ctx&: MMI->getContext());
4381 const auto Base = &cast<MCSymbolRefExpr>(Val: BaseExpr)->getSymbol();
4382
4383 // By default, for the architectures that support CodeView,
4384 // EK_LabelDifference32 is implemented as an Int32 from the base address.
4385 return std::make_tuple(args: Base, args: 0, args&: BranchLabel,
4386 args: codeview::JumpTableEntrySize::Int32);
4387}
4388

source code of llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp