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/AsmPrinterAnalysis.h"
40#include "llvm/CodeGen/BasicBlockSectionsProfileReader.h"
41#include "llvm/CodeGen/GCMetadata.h"
42#include "llvm/CodeGen/GCMetadataPrinter.h"
43#include "llvm/CodeGen/InsertCodePrefetch.h"
44#include "llvm/CodeGen/LazyMachineBlockFrequencyInfo.h"
45#include "llvm/CodeGen/MachineBasicBlock.h"
46#include "llvm/CodeGen/MachineBlockHashInfo.h"
47#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
48#include "llvm/CodeGen/MachineConstantPool.h"
49#include "llvm/CodeGen/MachineDominators.h"
50#include "llvm/CodeGen/MachineFrameInfo.h"
51#include "llvm/CodeGen/MachineFunction.h"
52#include "llvm/CodeGen/MachineFunctionPass.h"
53#include "llvm/CodeGen/MachineInstr.h"
54#include "llvm/CodeGen/MachineInstrBundle.h"
55#include "llvm/CodeGen/MachineJumpTableInfo.h"
56#include "llvm/CodeGen/MachineLoopInfo.h"
57#include "llvm/CodeGen/MachineModuleInfo.h"
58#include "llvm/CodeGen/MachineModuleInfoImpls.h"
59#include "llvm/CodeGen/MachineOperand.h"
60#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
61#include "llvm/CodeGen/StackMaps.h"
62#include "llvm/CodeGen/TargetFrameLowering.h"
63#include "llvm/CodeGen/TargetInstrInfo.h"
64#include "llvm/CodeGen/TargetLowering.h"
65#include "llvm/CodeGen/TargetOpcodes.h"
66#include "llvm/CodeGen/TargetRegisterInfo.h"
67#include "llvm/CodeGen/TargetSubtargetInfo.h"
68#include "llvm/Config/config.h"
69#include "llvm/IR/BasicBlock.h"
70#include "llvm/IR/Comdat.h"
71#include "llvm/IR/Constant.h"
72#include "llvm/IR/Constants.h"
73#include "llvm/IR/DataLayout.h"
74#include "llvm/IR/DebugInfoMetadata.h"
75#include "llvm/IR/DerivedTypes.h"
76#include "llvm/IR/EHPersonalities.h"
77#include "llvm/IR/Function.h"
78#include "llvm/IR/GCStrategy.h"
79#include "llvm/IR/GlobalAlias.h"
80#include "llvm/IR/GlobalIFunc.h"
81#include "llvm/IR/GlobalObject.h"
82#include "llvm/IR/GlobalValue.h"
83#include "llvm/IR/GlobalVariable.h"
84#include "llvm/IR/Instruction.h"
85#include "llvm/IR/Instructions.h"
86#include "llvm/IR/LLVMRemarkStreamer.h"
87#include "llvm/IR/Mangler.h"
88#include "llvm/IR/Metadata.h"
89#include "llvm/IR/Module.h"
90#include "llvm/IR/Operator.h"
91#include "llvm/IR/PseudoProbe.h"
92#include "llvm/IR/Type.h"
93#include "llvm/IR/Value.h"
94#include "llvm/IR/ValueHandle.h"
95#include "llvm/MC/MCAsmInfo.h"
96#include "llvm/MC/MCContext.h"
97#include "llvm/MC/MCDirectives.h"
98#include "llvm/MC/MCExpr.h"
99#include "llvm/MC/MCInst.h"
100#include "llvm/MC/MCSchedule.h"
101#include "llvm/MC/MCSection.h"
102#include "llvm/MC/MCSectionCOFF.h"
103#include "llvm/MC/MCSectionELF.h"
104#include "llvm/MC/MCSectionMachO.h"
105#include "llvm/MC/MCSectionXCOFF.h"
106#include "llvm/MC/MCStreamer.h"
107#include "llvm/MC/MCSubtargetInfo.h"
108#include "llvm/MC/MCSymbol.h"
109#include "llvm/MC/MCSymbolELF.h"
110#include "llvm/MC/MCTargetOptions.h"
111#include "llvm/MC/MCValue.h"
112#include "llvm/MC/SectionKind.h"
113#include "llvm/MC/TargetRegistry.h"
114#include "llvm/Object/ELFTypes.h"
115#include "llvm/Pass.h"
116#include "llvm/Remarks/RemarkStreamer.h"
117#include "llvm/Support/Casting.h"
118#include "llvm/Support/CommandLine.h"
119#include "llvm/Support/Compiler.h"
120#include "llvm/Support/ErrorHandling.h"
121#include "llvm/Support/FileSystem.h"
122#include "llvm/Support/Format.h"
123#include "llvm/Support/MathExtras.h"
124#include "llvm/Support/Path.h"
125#include "llvm/Support/VCSRevision.h"
126#include "llvm/Support/VirtualFileSystem.h"
127#include "llvm/Support/raw_ostream.h"
128#include "llvm/Target/TargetLoweringObjectFile.h"
129#include "llvm/Target/TargetMachine.h"
130#include "llvm/Target/TargetOptions.h"
131#include <algorithm>
132#include <cassert>
133#include <cinttypes>
134#include <cstdint>
135#include <iterator>
136#include <memory>
137#include <optional>
138#include <string>
139#include <utility>
140#include <vector>
141
142using namespace llvm;
143
144#define DEBUG_TYPE "asm-printer"
145
146enum class PGOMapFeaturesEnum {
147 None,
148 FuncEntryCount,
149 BBFreq,
150 BrProb,
151 PropellerCFG,
152 All,
153};
154static cl::list<PGOMapFeaturesEnum> PgoAnalysisMapFeatures(
155 "pgo-analysis-map", cl::Hidden, cl::CommaSeparated,
156 cl::values(
157 clEnumValN(PGOMapFeaturesEnum::None, "none", "Disable all options"),
158 clEnumValN(PGOMapFeaturesEnum::FuncEntryCount, "func-entry-count",
159 "Function Entry Count"),
160 clEnumValN(PGOMapFeaturesEnum::BBFreq, "bb-freq",
161 "Basic Block Frequency"),
162 clEnumValN(PGOMapFeaturesEnum::BrProb, "br-prob", "Branch Probability"),
163 clEnumValN(PGOMapFeaturesEnum::All, "all", "Enable all options")),
164 cl::desc(
165 "Enable extended information within the SHT_LLVM_BB_ADDR_MAP that is "
166 "extracted from PGO related analysis."));
167
168static cl::opt<bool> PgoAnalysisMapEmitBBSectionsCfg(
169 "pgo-analysis-map-emit-bb-sections-cfg",
170 cl::desc("Enable the post-link cfg information from the basic block "
171 "sections profile in the PGO analysis map"),
172 cl::Hidden, cl::init(Val: false));
173
174static cl::opt<bool> BBAddrMapSkipEmitBBEntries(
175 "basic-block-address-map-skip-bb-entries",
176 cl::desc("Skip emitting basic block entries in the SHT_LLVM_BB_ADDR_MAP "
177 "section. It's used to save binary size when BB entries are "
178 "unnecessary for some PGOAnalysisMap features."),
179 cl::Hidden, cl::init(Val: false));
180
181static cl::opt<bool> BBAddrMapEmitFuncGUID(
182 "basic-block-address-map-emit-func-guid",
183 cl::desc("Emit the function GUID in the SHT_LLVM_BB_ADDR_MAP section for "
184 "functions with local linkage. This allows identifying them "
185 "without relying on their (possibly non-unique) symbol names."),
186 cl::Hidden, cl::init(Val: false));
187
188static cl::opt<bool> EmitJumpTableSizesSection(
189 "emit-jump-table-sizes-section",
190 cl::desc("Emit a section containing jump table addresses and sizes"),
191 cl::Hidden, cl::init(Val: false));
192
193// This isn't turned on by default, since several of the scheduling models are
194// not completely accurate, and we don't want to be misleading.
195static cl::opt<bool> PrintLatency(
196 "asm-print-latency",
197 cl::desc("Print instruction latencies as verbose asm comments"), cl::Hidden,
198 cl::init(Val: false));
199
200static cl::opt<std::string>
201 StackUsageFile("stack-usage-file",
202 cl::desc("Output filename for stack usage information"),
203 cl::value_desc("filename"), cl::Hidden);
204
205STATISTIC(EmittedInsts, "Number of machine instrs printed");
206
207char AsmPrinter::ID = 0;
208
209namespace {
210class AddrLabelMapCallbackPtr final : CallbackVH {
211 AddrLabelMap *Map = nullptr;
212
213public:
214 AddrLabelMapCallbackPtr() = default;
215 AddrLabelMapCallbackPtr(Value *V) : CallbackVH(V) {}
216
217 void setPtr(BasicBlock *BB) {
218 ValueHandleBase::operator=(RHS: BB);
219 }
220
221 void setMap(AddrLabelMap *map) { Map = map; }
222
223 void deleted() override;
224 void allUsesReplacedWith(Value *V2) override;
225};
226} // namespace
227
228class llvm::AddrLabelMap {
229 MCContext &Context;
230 struct AddrLabelSymEntry {
231 /// The symbols for the label.
232 TinyPtrVector<MCSymbol *> Symbols;
233
234 Function *Fn; // The containing function of the BasicBlock.
235 unsigned Index; // The index in BBCallbacks for the BasicBlock.
236 };
237
238 DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols;
239
240 /// Callbacks for the BasicBlock's that we have entries for. We use this so
241 /// we get notified if a block is deleted or RAUWd.
242 std::vector<AddrLabelMapCallbackPtr> BBCallbacks;
243
244 /// This is a per-function list of symbols whose corresponding BasicBlock got
245 /// deleted. These symbols need to be emitted at some point in the file, so
246 /// AsmPrinter emits them after the function body.
247 DenseMap<AssertingVH<Function>, std::vector<MCSymbol *>>
248 DeletedAddrLabelsNeedingEmission;
249
250public:
251 AddrLabelMap(MCContext &context) : Context(context) {}
252
253 ~AddrLabelMap() {
254 assert(DeletedAddrLabelsNeedingEmission.empty() &&
255 "Some labels for deleted blocks never got emitted");
256 }
257
258 ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(BasicBlock *BB);
259
260 void takeDeletedSymbolsForFunction(Function *F,
261 std::vector<MCSymbol *> &Result);
262
263 void UpdateForDeletedBlock(BasicBlock *BB);
264 void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New);
265};
266
267ArrayRef<MCSymbol *> AddrLabelMap::getAddrLabelSymbolToEmit(BasicBlock *BB) {
268 assert(BB->hasAddressTaken() &&
269 "Shouldn't get label for block without address taken");
270 AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
271
272 // If we already had an entry for this block, just return it.
273 if (!Entry.Symbols.empty()) {
274 assert(BB->getParent() == Entry.Fn && "Parent changed");
275 return Entry.Symbols;
276 }
277
278 // Otherwise, this is a new entry, create a new symbol for it and add an
279 // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd.
280 BBCallbacks.emplace_back(args&: BB);
281 BBCallbacks.back().setMap(this);
282 Entry.Index = BBCallbacks.size() - 1;
283 Entry.Fn = BB->getParent();
284 MCSymbol *Sym = BB->hasAddressTaken() ? Context.createNamedTempSymbol()
285 : Context.createTempSymbol();
286 Entry.Symbols.push_back(NewVal: Sym);
287 return Entry.Symbols;
288}
289
290/// If we have any deleted symbols for F, return them.
291void AddrLabelMap::takeDeletedSymbolsForFunction(
292 Function *F, std::vector<MCSymbol *> &Result) {
293 DenseMap<AssertingVH<Function>, std::vector<MCSymbol *>>::iterator I =
294 DeletedAddrLabelsNeedingEmission.find(Val: F);
295
296 // If there are no entries for the function, just return.
297 if (I == DeletedAddrLabelsNeedingEmission.end())
298 return;
299
300 // Otherwise, take the list.
301 std::swap(x&: Result, y&: I->second);
302 DeletedAddrLabelsNeedingEmission.erase(I);
303}
304
305//===- Address of Block Management ----------------------------------------===//
306
307ArrayRef<MCSymbol *>
308AsmPrinter::getAddrLabelSymbolToEmit(const BasicBlock *BB) {
309 // Lazily create AddrLabelSymbols.
310 if (!AddrLabelSymbols)
311 AddrLabelSymbols = std::make_unique<AddrLabelMap>(args&: OutContext);
312 return AddrLabelSymbols->getAddrLabelSymbolToEmit(
313 BB: const_cast<BasicBlock *>(BB));
314}
315
316void AsmPrinter::takeDeletedSymbolsForFunction(
317 const Function *F, std::vector<MCSymbol *> &Result) {
318 // If no blocks have had their addresses taken, we're done.
319 if (!AddrLabelSymbols)
320 return;
321 return AddrLabelSymbols->takeDeletedSymbolsForFunction(
322 F: const_cast<Function *>(F), Result);
323}
324
325void AddrLabelMap::UpdateForDeletedBlock(BasicBlock *BB) {
326 // If the block got deleted, there is no need for the symbol. If the symbol
327 // was already emitted, we can just forget about it, otherwise we need to
328 // queue it up for later emission when the function is output.
329 AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]);
330 AddrLabelSymbols.erase(Val: BB);
331 assert(!Entry.Symbols.empty() && "Didn't have a symbol, why a callback?");
332 BBCallbacks[Entry.Index] = nullptr; // Clear the callback.
333
334#if !LLVM_MEMORY_SANITIZER_BUILD
335 // BasicBlock is destroyed already, so this access is UB detectable by msan.
336 assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) &&
337 "Block/parent mismatch");
338#endif
339
340 for (MCSymbol *Sym : Entry.Symbols) {
341 if (Sym->isDefined())
342 return;
343
344 // If the block is not yet defined, we need to emit it at the end of the
345 // function. Add the symbol to the DeletedAddrLabelsNeedingEmission list
346 // for the containing Function. Since the block is being deleted, its
347 // parent may already be removed, we have to get the function from 'Entry'.
348 DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(x: Sym);
349 }
350}
351
352void AddrLabelMap::UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New) {
353 // Get the entry for the RAUW'd block and remove it from our map.
354 AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]);
355 AddrLabelSymbols.erase(Val: Old);
356 assert(!OldEntry.Symbols.empty() && "Didn't have a symbol, why a callback?");
357
358 AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
359
360 // If New is not address taken, just move our symbol over to it.
361 if (NewEntry.Symbols.empty()) {
362 BBCallbacks[OldEntry.Index].setPtr(New); // Update the callback.
363 NewEntry = std::move(OldEntry); // Set New's entry.
364 return;
365 }
366
367 BBCallbacks[OldEntry.Index] = nullptr; // Update the callback.
368
369 // Otherwise, we need to add the old symbols to the new block's set.
370 llvm::append_range(C&: NewEntry.Symbols, R&: OldEntry.Symbols);
371}
372
373void AddrLabelMapCallbackPtr::deleted() {
374 Map->UpdateForDeletedBlock(BB: cast<BasicBlock>(Val: getValPtr()));
375}
376
377void AddrLabelMapCallbackPtr::allUsesReplacedWith(Value *V2) {
378 Map->UpdateForRAUWBlock(Old: cast<BasicBlock>(Val: getValPtr()), New: cast<BasicBlock>(Val: V2));
379}
380
381/// getGVAlignment - Return the alignment to use for the specified global
382/// value. This rounds up to the preferred alignment if possible and legal.
383Align AsmPrinter::getGVAlignment(const GlobalObject *GV, const DataLayout &DL,
384 Align InAlign) {
385 Align Alignment;
386 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(Val: GV))
387 Alignment = DL.getPreferredAlign(GV: GVar);
388
389 // If InAlign is specified, round it to it.
390 if (InAlign > Alignment)
391 Alignment = InAlign;
392
393 // If the GV has a specified alignment, take it into account.
394 MaybeAlign GVAlign;
395 if (auto *GVar = dyn_cast<GlobalVariable>(Val: GV))
396 GVAlign = GVar->getAlign();
397 else if (auto *F = dyn_cast<Function>(Val: GV))
398 GVAlign = F->getAlign();
399 if (!GVAlign)
400 return Alignment;
401
402 assert(GVAlign && "GVAlign must be set");
403
404 // If the GVAlign is larger than NumBits, or if we are required to obey
405 // NumBits because the GV has an assigned section, obey it.
406 if (*GVAlign > Alignment || GV->hasSection())
407 Alignment = *GVAlign;
408 return Alignment;
409}
410
411AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer,
412 char &ID)
413 : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
414 OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)),
415 PointerSize(tm.getTargetTriple().getArchPointerBitWidth() / 8),
416 SM(*this) {
417 VerboseAsm = OutStreamer->isVerboseAsm();
418 DwarfUsesRelocationsAcrossSections =
419 MAI.doesDwarfUseRelocationsAcrossSections();
420 GetMMI = [this]() {
421 auto *MMIWP = getAnalysisIfAvailable<MachineModuleInfoWrapperPass>();
422 return MMIWP ? &MMIWP->getMMI() : nullptr;
423 };
424 GetORE = [this](MachineFunction &MF) {
425 return &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
426 };
427 GetMDT = [this](MachineFunction &MF) {
428 auto *MDTWrapper =
429 getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
430 return MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
431 };
432 GetMLI = [this](MachineFunction &MF) {
433 auto *MLIWrapper = getAnalysisIfAvailable<MachineLoopInfoWrapperPass>();
434 return MLIWrapper ? &MLIWrapper->getLI() : nullptr;
435 };
436 GetMBPI = [this](MachineFunction &MF) {
437 return &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
438 };
439 GetMBFI = [this](MachineFunction &MF) {
440 return &getAnalysis<LazyMachineBlockFrequencyInfoPass>().getBFI();
441 };
442 GetMBHI = [this](MachineFunction &MF) {
443 return &getAnalysis<MachineBlockHashInfo>().getMBHI();
444 };
445 GetBBSPR = [this](MachineFunction &MF) {
446 auto *BBSPRPass =
447 getAnalysisIfAvailable<BasicBlockSectionsProfileReaderWrapperPass>();
448 return BBSPRPass ? &BBSPRPass->getBBSPR() : nullptr;
449 };
450 BeginGCAssembly = [this](Module &M) {
451 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
452 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
453 for (const auto &I : *MI)
454 if (GCMetadataPrinter *MP = getOrCreateGCPrinter(S&: *I))
455 MP->beginAssembly(M, Info&: *MI, AP&: *this);
456 };
457 FinishGCAssembly = [this](Module &M) {
458 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
459 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
460 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E;)
461 if (GCMetadataPrinter *MP = getOrCreateGCPrinter(S&: **--I))
462 MP->finishAssembly(M, Info&: *MI, AP&: *this);
463 };
464 EmitStackMaps = [this](Module &M) {
465 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
466 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
467 bool NeedsDefault = false;
468 if (MI->begin() == MI->end())
469 // No GC strategy, use the default format.
470 NeedsDefault = true;
471 else
472 for (const auto &I : *MI) {
473 if (GCMetadataPrinter *MP = getOrCreateGCPrinter(S&: *I))
474 if (MP->emitStackMaps(SM, AP&: *this))
475 continue;
476 // The strategy doesn't have printer or doesn't emit custom stack maps.
477 // Use the default format.
478 NeedsDefault = true;
479 }
480
481 if (NeedsDefault)
482 SM.serializeToStackMapSection();
483 };
484 AssertDebugEHFinalized = [&]() {
485 assert(!DD && Handlers.size() == NumUserHandlers &&
486 "Debug/EH info didn't get finalized");
487 };
488}
489
490AsmPrinter::~AsmPrinter() { AssertDebugEHFinalized(); }
491
492bool AsmPrinter::isPositionIndependent() const {
493 return TM.isPositionIndependent();
494}
495
496/// getFunctionNumber - Return a unique ID for the current function.
497unsigned AsmPrinter::getFunctionNumber() const {
498 return MF->getFunctionNumber();
499}
500
501const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
502 return *TM.getObjFileLowering();
503}
504
505const DataLayout &AsmPrinter::getDataLayout() const {
506 assert(MMI && "MMI could not be nullptr!");
507 return MMI->getModule()->getDataLayout();
508}
509
510const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const {
511 assert(MF && "getSubtargetInfo requires a valid MachineFunction!");
512 return MF->getSubtarget<MCSubtargetInfo>();
513}
514
515void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
516 S.emitInstruction(Inst, STI: getSubtargetInfo());
517}
518
519/// getCurrentSection() - Return the current section we are emitting to.
520const MCSection *AsmPrinter::getCurrentSection() const {
521 return OutStreamer->getCurrentSectionOnly();
522}
523
524/// createDwarfDebug() - Create the DwarfDebug handler.
525DwarfDebug *AsmPrinter::createDwarfDebug() { return new DwarfDebug(this); }
526
527void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
528 AU.setPreservesAll();
529 MachineFunctionPass::getAnalysisUsage(AU);
530 AU.addRequired<MachineOptimizationRemarkEmitterPass>();
531 AU.addRequired<GCModuleInfo>();
532 AU.addRequired<LazyMachineBlockFrequencyInfoPass>();
533 AU.addRequired<MachineBranchProbabilityInfoWrapperPass>();
534 if (shouldEmitBBHash())
535 AU.addRequired<MachineBlockHashInfo>();
536 AU.addUsedIfAvailable<BasicBlockSectionsProfileReaderWrapperPass>();
537}
538
539bool AsmPrinter::doInitialization(Module &M) {
540 MMI = GetMMI();
541 PointerSize = M.getDataLayout().getPointerSize(AS: 0);
542 HasSplitStack = false;
543 HasNoSplitStack = false;
544 DbgInfoAvailable = !M.debug_compile_units().empty();
545 ModuleExceptionModel = M.getExceptionModel();
546 const Triple &Target = M.getTargetTriple();
547
548 AddrLabelSymbols = nullptr;
549
550 // On AIX, we delay emitting any section information until
551 // after emitting the .file pseudo-op. This allows additional
552 // information (such as the embedded command line) to be associated
553 // with all sections in the object file rather than a single section.
554 if (!Target.isOSBinFormatXCOFF())
555 OutStreamer->initSections(STI: TM.getMCSubtargetInfo());
556
557 // Emit the version-min deployment target directive if needed.
558 //
559 // FIXME: If we end up with a collection of these sorts of Darwin-specific
560 // or ELF-specific things, it may make sense to have a platform helper class
561 // that will work with the target helper class. For now keep it here, as the
562 // alternative is duplicated code in each of the target asm printers that
563 // use the directive, where it would need the same conditionalization
564 // anyway.
565 if (Target.isOSBinFormatMachO() && Target.isOSDarwin()) {
566 Triple TVT(M.getDarwinTargetVariantTriple());
567 OutStreamer->emitVersionForTarget(
568 Target, SDKVersion: M.getSDKVersion(),
569 DarwinTargetVariantTriple: M.getDarwinTargetVariantTriple().empty() ? nullptr : &TVT,
570 DarwinTargetVariantSDKVersion: M.getDarwinTargetVariantSDKVersion());
571 }
572
573 // Allow the target to emit any magic that it wants at the start of the file.
574 emitStartOfAsmFile(M);
575
576 // Very minimal debug info. It is ignored if we emit actual debug info. If we
577 // don't, this at least helps the user find where a global came from.
578 if (MAI.hasSingleParameterDotFile()) {
579 // .file "foo.c"
580 if (MAI.isAIX()) {
581 const char VerStr[] =
582#ifdef PACKAGE_VENDOR
583 PACKAGE_VENDOR " "
584#endif
585 PACKAGE_NAME " version " PACKAGE_VERSION
586#ifdef LLVM_REVISION
587 " (" LLVM_REVISION ")"
588#endif
589 ;
590 // TODO: Add timestamp and description.
591 OutStreamer->emitFileDirective(Filename: M.getSourceFileName(), CompilerVersion: VerStr, TimeStamp: "", Description: "");
592 } else {
593 OutStreamer->emitFileDirective(
594 Filename: llvm::sys::path::filename(path: M.getSourceFileName()));
595 }
596 }
597
598 // On AIX, emit bytes for llvm.commandline metadata after .file so that the
599 // C_INFO symbol is preserved if any csect is kept by the linker.
600 if (Target.isOSBinFormatXCOFF()) {
601 emitModuleCommandLines(M);
602 // Now we can generate section information.
603 OutStreamer->switchSection(
604 Section: OutContext.getObjectFileInfo()->getTextSection());
605
606 // To work around an AIX assembler and/or linker bug, generate
607 // a rename for the default text-section symbol name. This call has
608 // no effect when generating object code directly.
609 MCSection *TextSection =
610 OutStreamer->getContext().getObjectFileInfo()->getTextSection();
611 MCSymbolXCOFF *XSym =
612 static_cast<MCSectionXCOFF *>(TextSection)->getQualNameSymbol();
613 if (XSym->hasRename())
614 OutStreamer->emitXCOFFRenameDirective(Name: XSym, Rename: XSym->getSymbolTableName());
615 }
616
617 BeginGCAssembly(M);
618
619 // Emit module-level inline asm if it exists.
620 if (M.hasModuleInlineAsm()) {
621 OutStreamer->AddComment(T: "Start of file scope inline assembly");
622 OutStreamer->addBlankLine();
623 for (const Module::GlobalAsmFragment &Frag : M.getModuleInlineAsm()) {
624 const MCSubtargetInfo &AsmSTI = TM.getMCSubtargetInfo(
625 CPU: Frag.Props.TargetCPU, FS: Frag.Props.TargetFeatures);
626 bool DidPush = emitTargetFeaturePush(STI: AsmSTI);
627 emitInlineAsm(
628 Str: Frag.Asm, STI: AsmSTI, MCOptions: TM.Options.MCOptions, LocMDNode: nullptr,
629 AsmDialect: InlineAsm::AsmDialect(TM.getMCAsmInfo().getAssemblerDialect()));
630 emitTargetFeaturePop(STI: AsmSTI, DidPush);
631 }
632 OutStreamer->AddComment(T: "End of file scope inline assembly");
633 OutStreamer->addBlankLine();
634 }
635
636 if (MAI.doesSupportDebugInformation()) {
637 bool EmitCodeView = M.getCodeViewFlag();
638 // On Windows and UEFI targets, emit minimal CodeView compiler info even
639 // when debug info is disabled. UEFI follows the MSVC toolchain
640 // conventions, so it is treated the same way as Windows here.
641 if ((Target.isOSWindows() || Target.isUEFI()) &&
642 M.getNamedMetadata(Name: "llvm.dbg.cu"))
643 Handlers.push_back(Elt: std::make_unique<CodeViewDebug>(args: this));
644 if (!EmitCodeView || M.getDwarfVersion()) {
645 if (hasDebugInfo()) {
646 DD = createDwarfDebug();
647 Handlers.push_back(Elt: std::unique_ptr<DwarfDebug>(DD));
648 }
649 }
650 }
651
652 if (M.getNamedMetadata(Name: PseudoProbeDescMetadataName))
653 PP = std::make_unique<PseudoProbeHandler>(args: this);
654
655 switch (ModuleExceptionModel) {
656 case ExceptionHandling::None:
657 // We may want to emit CFI for debug.
658 [[fallthrough]];
659 case ExceptionHandling::SjLj:
660 case ExceptionHandling::DwarfCFI:
661 case ExceptionHandling::ARM:
662 for (auto &F : M.getFunctionList()) {
663 if (getFunctionCFISectionType(F) != CFISection::None)
664 ModuleCFISection = getFunctionCFISectionType(F);
665 // If any function needsUnwindTableEntry(), it needs .eh_frame and hence
666 // the module needs .eh_frame. If we have found that case, we are done.
667 if (ModuleCFISection == CFISection::EH)
668 break;
669 }
670 assert(ModuleExceptionModel == ExceptionHandling::DwarfCFI ||
671 usesCFIWithoutEH() || ModuleCFISection != CFISection::EH);
672 break;
673 default:
674 break;
675 }
676
677 EHStreamer *ES = nullptr;
678 switch (ModuleExceptionModel) {
679 case ExceptionHandling::Default:
680 llvm_unreachable("should have resolved exception model kind");
681 case ExceptionHandling::None:
682 case ExceptionHandling::Emscripten:
683 // Emscripten EH is handled in JS glue code and emits no EH tables here.
684 if (!usesCFIWithoutEH())
685 break;
686 [[fallthrough]];
687 case ExceptionHandling::SjLj:
688 case ExceptionHandling::DwarfCFI:
689 case ExceptionHandling::ZOS:
690 ES = new DwarfCFIException(this);
691 break;
692 case ExceptionHandling::ARM:
693 ES = new ARMException(this);
694 break;
695 case ExceptionHandling::WinEH:
696 switch (MAI.getWinEHEncodingType()) {
697 default: llvm_unreachable("unsupported unwinding information encoding");
698 case WinEH::EncodingType::Invalid:
699 break;
700 case WinEH::EncodingType::X86:
701 case WinEH::EncodingType::Itanium:
702 ES = new WinException(this);
703 break;
704 }
705 break;
706 case ExceptionHandling::Wasm:
707 ES = new WasmException(this);
708 break;
709 case ExceptionHandling::AIX:
710 ES = new AIXException(this);
711 break;
712 }
713 if (ES)
714 EHHandlers.push_back(Elt: std::unique_ptr<EHStreamer>(ES));
715
716 // All CFG modes required the tables emitted.
717 if (M.getControlFlowGuardMode() != ControlFlowGuardMode::Disabled)
718 Handlers.push_back(Elt: std::make_unique<WinCFGuard>(args: this));
719
720 for (auto &Handler : Handlers)
721 Handler->beginModule(M: &M);
722 for (auto &Handler : EHHandlers)
723 Handler->beginModule(M: &M);
724
725 return false;
726}
727
728static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
729 if (!MAI.hasWeakDefCanBeHiddenDirective())
730 return false;
731
732 return GV->canBeOmittedFromSymbolTable();
733}
734
735void AsmPrinter::emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
736 GlobalValue::LinkageTypes Linkage = GV->getLinkage();
737 switch (Linkage) {
738 case GlobalValue::CommonLinkage:
739 case GlobalValue::LinkOnceAnyLinkage:
740 case GlobalValue::LinkOnceODRLinkage:
741 case GlobalValue::WeakAnyLinkage:
742 case GlobalValue::WeakODRLinkage:
743 if (MAI.isMachO()) {
744 // .globl _foo
745 OutStreamer->emitSymbolAttribute(Symbol: GVSym, Attribute: MCSA_Global);
746
747 if (!canBeHidden(GV, MAI))
748 // .weak_definition _foo
749 OutStreamer->emitSymbolAttribute(Symbol: GVSym, Attribute: MCSA_WeakDefinition);
750 else
751 OutStreamer->emitSymbolAttribute(Symbol: GVSym, Attribute: MCSA_WeakDefAutoPrivate);
752 } else if (MAI.avoidWeakIfComdat() && GV->hasComdat()) {
753 // .globl _foo
754 OutStreamer->emitSymbolAttribute(Symbol: GVSym, Attribute: MCSA_Global);
755 //NOTE: linkonce is handled by the section the symbol was assigned to.
756 } else {
757 // .weak _foo
758 OutStreamer->emitSymbolAttribute(Symbol: GVSym, Attribute: MCSA_Weak);
759 }
760 return;
761 case GlobalValue::ExternalLinkage:
762 OutStreamer->emitSymbolAttribute(Symbol: GVSym, Attribute: MCSA_Global);
763 return;
764 case GlobalValue::PrivateLinkage:
765 case GlobalValue::InternalLinkage:
766 return;
767 case GlobalValue::ExternalWeakLinkage:
768 case GlobalValue::AvailableExternallyLinkage:
769 case GlobalValue::AppendingLinkage:
770 llvm_unreachable("Should never emit this");
771 }
772 llvm_unreachable("Unknown linkage type!");
773}
774
775void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name,
776 const GlobalValue *GV) const {
777 TM.getNameWithPrefix(Name, GV, Mang&: getObjFileLowering().getMangler());
778}
779
780MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
781 return TM.getSymbol(GV);
782}
783
784MCSymbol *AsmPrinter::getSymbolPreferLocal(const GlobalValue &GV) const {
785 // On ELF, use .Lfoo$local if GV is a non-interposable GlobalObject with an
786 // exact definion (intersection of GlobalValue::hasExactDefinition() and
787 // !isInterposable()). These linkages include: external, appending, internal,
788 // private. It may be profitable to use a local alias for external. The
789 // assembler would otherwise be conservative and assume a global default
790 // visibility symbol can be interposable, even if the code generator already
791 // assumed it.
792 const Module &M = *GV.getParent();
793 if (M.getTargetTriple().isOSBinFormatELF() && GV.canBenefitFromLocalAlias()) {
794 if (TM.getRelocationModel() != Reloc::Static &&
795 M.getPIELevel() == PIELevel::Default && GV.isDSOLocal())
796 return getSymbolWithGlobalValueBase(GV: &GV, Suffix: "$local");
797 }
798 return TM.getSymbol(GV: &GV);
799}
800
801/// EmitGlobalVariable - Emit the specified global variable to the .s file.
802void AsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
803 MaybeAlign AlignmentGranule = getRequiredGlobalAlignmentGranule(GV: *GV);
804 emitGlobalVariable(GV, AlignmentGranule);
805 if (AlignmentGranule)
806 OutStreamer->emitValueToAlignment(Alignment: *AlignmentGranule);
807}
808
809void AsmPrinter::emitGlobalVariable(const GlobalVariable *GV,
810 MaybeAlign AlignmentGranule) {
811 bool IsEmuTLSVar = TM.useEmulatedTLS() && GV->isThreadLocal();
812 assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) &&
813 "No emulated TLS variables in the common section");
814
815 // Never emit TLS variable xyz in emulated TLS model.
816 // The initialization value is in __emutls_t.xyz instead of xyz.
817 if (IsEmuTLSVar)
818 return;
819
820 if (GV->hasInitializer()) {
821 // Check to see if this is a special global used by LLVM, if so, emit it.
822 if (emitSpecialLLVMGlobal(GV))
823 return;
824
825 // Skip the emission of global equivalents. The symbol can be emitted later
826 // on by emitGlobalGOTEquivs in case it turns out to be needed.
827 if (GlobalGOTEquivs.count(Key: getSymbol(GV)))
828 return;
829
830 if (isVerbose()) {
831 // When printing the control variable __emutls_v.*,
832 // we don't need to print the original TLS variable name.
833 GV->printAsOperand(O&: OutStreamer->getCommentOS(),
834 /*PrintType=*/false, M: GV->getParent());
835 OutStreamer->getCommentOS() << '\n';
836 }
837 }
838
839 MCSymbol *GVSym = getSymbol(GV);
840 MCSymbol *EmittedSym = GVSym;
841
842 // getOrCreateEmuTLSControlSym only creates the symbol with name and default
843 // attributes.
844 // GV's or GVSym's attributes will be used for the EmittedSym.
845 emitVisibility(Sym: EmittedSym, Visibility: GV->getVisibility(), IsDefinition: !GV->isDeclaration());
846
847 if (GV->isTagged()) {
848 if (TM.getTargetTriple().getArch() != Triple::aarch64)
849 OutContext.reportError(L: SMLoc(),
850 Msg: "tagged symbols (-fsanitize=memtag-globals) are "
851 "only supported on AArch64");
852 OutStreamer->emitSymbolAttribute(Symbol: EmittedSym, Attribute: MCSA_Memtag);
853 }
854
855 if (!GV->hasInitializer()) // External globals require no extra code.
856 return;
857
858 GVSym->redefineIfPossible();
859 if (GVSym->isDefined() || GVSym->isVariable())
860 OutContext.reportError(L: SMLoc(), Msg: "symbol '" + Twine(GVSym->getName()) +
861 "' is already defined");
862
863 if (MAI.hasDotTypeDotSizeDirective())
864 OutStreamer->emitSymbolAttribute(Symbol: EmittedSym, Attribute: MCSA_ELF_TypeObject);
865
866 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GO: GV, TM);
867
868 const DataLayout &DL = GV->getDataLayout();
869 uint64_t Size = GV->getGlobalSize(DL);
870
871 // If the alignment is specified, we *must* obey it. Overaligning a global
872 // with a specified alignment is a prompt way to break globals emitted to
873 // sections and expected to be contiguous (e.g. ObjC metadata).
874 //
875 // If we get passed in an explicit alignment granule, it is up to the caller
876 // to ensure that is not the case (i.e. that the GV is not in a section).
877 Align Alignment = getGVAlignment(GV, DL);
878
879 if (AlignmentGranule) {
880 assert(!GV->hasSection());
881 Size = alignTo(Size, A: *AlignmentGranule);
882 if (Alignment < *AlignmentGranule)
883 Alignment = *AlignmentGranule;
884 }
885
886 for (auto &Handler : Handlers)
887 Handler->setSymbolSize(Sym: GVSym, Size);
888
889 // Handle common symbols
890 if (GVKind.isCommon()) {
891 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
892 // .comm _foo, 42, 4
893 OutStreamer->emitCommonSymbol(Symbol: GVSym, Size, ByteAlignment: Alignment);
894 return;
895 }
896
897 // Determine to which section this global should be emitted.
898 MCSection *TheSection = getObjFileLowering().SectionForGlobal(GO: GV, Kind: GVKind, TM);
899
900 // If we have a bss global going to a section that supports the
901 // zerofill directive, do so here.
902 if (GVKind.isBSS() && MAI.isMachO() && TheSection->isBssSection()) {
903 if (Size == 0)
904 Size = 1; // zerofill of 0 bytes is undefined.
905 emitLinkage(GV, GVSym);
906 // .zerofill __DATA, __bss, _foo, 400, 5
907 OutStreamer->emitZerofill(Section: TheSection, Symbol: GVSym, Size, ByteAlignment: Alignment);
908 return;
909 }
910
911 // If this is a BSS local symbol and we are emitting in the BSS
912 // section use .lcomm/.comm directive.
913 if (GVKind.isBSSLocal() &&
914 getObjFileLowering().getBSSSection() == TheSection) {
915 if (Size == 0)
916 Size = 1; // .comm Foo, 0 is undefined, avoid it.
917
918 // Use .lcomm only if it supports user-specified alignment.
919 // Otherwise, while it would still be correct to use .lcomm in some
920 // cases (e.g. when Align == 1), the external assembler might enfore
921 // some -unknown- default alignment behavior, which could cause
922 // spurious differences between external and integrated assembler.
923 // Prefer to simply fall back to .local / .comm in this case.
924 if (MAI.getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
925 // .lcomm _foo, 42
926 OutStreamer->emitLocalCommonSymbol(Symbol: GVSym, Size, ByteAlignment: Alignment);
927 return;
928 }
929
930 // .local _foo
931 OutStreamer->emitSymbolAttribute(Symbol: GVSym, Attribute: MCSA_Local);
932 // .comm _foo, 42, 4
933 OutStreamer->emitCommonSymbol(Symbol: GVSym, Size, ByteAlignment: Alignment);
934 return;
935 }
936
937 // Handle thread local data for mach-o which requires us to output an
938 // additional structure of data and mangle the original symbol so that we
939 // can reference it later.
940 //
941 // TODO: This should become an "emit thread local global" method on TLOF.
942 // All of this macho specific stuff should be sunk down into TLOFMachO and
943 // stuff like "TLSExtraDataSection" should no longer be part of the parent
944 // TLOF class. This will also make it more obvious that stuff like
945 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
946 // specific code.
947 if (GVKind.isThreadLocal() && MAI.isMachO()) {
948 // Emit the .tbss symbol
949 MCSymbol *MangSym =
950 OutContext.getOrCreateSymbol(Name: GVSym->getName() + Twine("$tlv$init"));
951
952 if (GVKind.isThreadBSS()) {
953 TheSection = getObjFileLowering().getTLSBSSSection();
954 OutStreamer->emitTBSSSymbol(Section: TheSection, Symbol: MangSym, Size, ByteAlignment: Alignment);
955 } else if (GVKind.isThreadData()) {
956 OutStreamer->switchSection(Section: TheSection);
957
958 emitAlignment(Alignment, GV);
959 OutStreamer->emitLabel(Symbol: MangSym);
960
961 emitGlobalConstant(DL: GV->getDataLayout(),
962 CV: GV->getInitializer());
963 }
964
965 OutStreamer->addBlankLine();
966
967 // Emit the variable struct for the runtime.
968 MCSection *TLVSect = getObjFileLowering().getTLSExtraDataSection();
969
970 OutStreamer->switchSection(Section: TLVSect);
971 // Emit the linkage here.
972 emitLinkage(GV, GVSym);
973 OutStreamer->emitLabel(Symbol: GVSym);
974
975 // Three pointers in size:
976 // - __tlv_bootstrap - used to make sure support exists
977 // - spare pointer, used when mapped by the runtime
978 // - pointer to mangled symbol above with initializer
979 unsigned PtrSize = DL.getPointerTypeSize(Ty: GV->getType());
980 OutStreamer->emitSymbolValue(Sym: GetExternalSymbolSymbol(Sym: "_tlv_bootstrap"),
981 Size: PtrSize);
982 OutStreamer->emitIntValue(Value: 0, Size: PtrSize);
983 OutStreamer->emitSymbolValue(Sym: MangSym, Size: PtrSize);
984
985 OutStreamer->addBlankLine();
986 return;
987 }
988
989 MCSymbol *EmittedInitSym = GVSym;
990
991 OutStreamer->switchSection(Section: TheSection);
992
993 emitLinkage(GV, GVSym: EmittedInitSym);
994 emitAlignment(Alignment, GV);
995
996 OutStreamer->emitLabel(Symbol: EmittedInitSym);
997 MCSymbol *LocalAlias = getSymbolPreferLocal(GV: *GV);
998 if (LocalAlias != EmittedInitSym)
999 OutStreamer->emitLabel(Symbol: LocalAlias);
1000
1001 emitGlobalConstant(DL: GV->getDataLayout(), CV: GV->getInitializer());
1002
1003 if (MAI.hasDotTypeDotSizeDirective())
1004 // .size foo, 42
1005 OutStreamer->emitELFSize(Symbol: EmittedInitSym,
1006 Value: MCConstantExpr::create(Value: Size, Ctx&: OutContext));
1007
1008 OutStreamer->addBlankLine();
1009}
1010
1011/// Emit the directive and value for debug thread local expression
1012///
1013/// \p Value - The value to emit.
1014/// \p Size - The size of the integer (in bytes) to emit.
1015void AsmPrinter::emitDebugValue(const MCExpr *Value, unsigned Size) const {
1016 OutStreamer->emitValue(Value, Size);
1017}
1018
1019void AsmPrinter::emitFunctionHeaderComment() {}
1020
1021void AsmPrinter::emitFunctionPrefix(ArrayRef<const Constant *> Prefix) {
1022 const Function &F = MF->getFunction();
1023 if (!MAI.hasSubsectionsViaSymbols()) {
1024 for (auto &C : Prefix)
1025 emitGlobalConstant(DL: F.getDataLayout(), CV: C);
1026 return;
1027 }
1028 // Preserving prefix-like data on platforms which use subsections-via-symbols
1029 // is a bit tricky. Here we introduce a symbol for the prefix-like data
1030 // and use the .alt_entry attribute to mark the function's real entry point
1031 // as an alternative entry point to the symbol that precedes the function..
1032 OutStreamer->emitLabel(Symbol: OutContext.createLinkerPrivateTempSymbol());
1033
1034 for (auto &C : Prefix) {
1035 emitGlobalConstant(DL: F.getDataLayout(), CV: C);
1036 }
1037
1038 // Emit an .alt_entry directive for the actual function symbol.
1039 OutStreamer->emitSymbolAttribute(Symbol: CurrentFnSym, Attribute: MCSA_AltEntry);
1040}
1041
1042/// EmitFunctionHeader - This method emits the header for the current
1043/// function.
1044void AsmPrinter::emitFunctionHeader() {
1045 const Function &F = MF->getFunction();
1046
1047 if (isVerbose())
1048 OutStreamer->getCommentOS()
1049 << "-- Begin function "
1050 << GlobalValue::dropLLVMManglingEscape(Name: F.getName()) << '\n';
1051
1052 // Print out constants referenced by the function
1053 emitConstantPool();
1054
1055 // Print the 'header' of function.
1056 // If basic block sections are desired, explicitly request a unique section
1057 // for this function's entry block.
1058 if (MF->front().isBeginSection())
1059 MF->setSection(getObjFileLowering().getUniqueSectionForFunction(F, TM));
1060 else
1061 MF->setSection(getObjFileLowering().SectionForGlobal(GO: &F, TM));
1062 OutStreamer->switchSection(Section: MF->getSection());
1063
1064 if (MAI.isAIX())
1065 emitLinkage(GV: &F, GVSym: CurrentFnDescSym);
1066 else
1067 emitVisibility(Sym: CurrentFnSym, Visibility: F.getVisibility());
1068
1069 emitLinkage(GV: &F, GVSym: CurrentFnSym);
1070 if (MAI.hasFunctionAlignment()) {
1071 Align PrefAlign = MF->getPreferredAlignment();
1072 if (MAI.useIntegratedAssembler() && MAI.hasPreferredAlignment()) {
1073 // Emit .p2align for the effective minimum alignment (which accounts for
1074 // F's own align attribute via getGVAlignment), then emit .prefalign only
1075 // when the preferred alignment is greater. The end symbol must be
1076 // created here, before the function body, so that .prefalign can
1077 // reference it; emitFunctionBody will emit the label at the function
1078 // end.
1079 Align MinAlign = emitAlignment(Alignment: MF->getAlignment(), GV: &F);
1080 if (MinAlign < PrefAlign) {
1081 CurrentFnEnd = createTempSymbol(Name: "func_end");
1082 OutStreamer->emitPrefAlign(A: PrefAlign, End: *CurrentFnEnd,
1083 /*EmitNops=*/true, /*Fill=*/0,
1084 STI: getSubtargetInfo());
1085 }
1086 } else {
1087 emitAlignment(Alignment: PrefAlign, GV: &F);
1088 }
1089 }
1090
1091 if (MAI.hasDotTypeDotSizeDirective())
1092 OutStreamer->emitSymbolAttribute(Symbol: CurrentFnSym, Attribute: MCSA_ELF_TypeFunction);
1093
1094 if (F.hasFnAttribute(Kind: Attribute::Cold))
1095 OutStreamer->emitSymbolAttribute(Symbol: CurrentFnSym, Attribute: MCSA_Cold);
1096
1097 // Emit the prefix data.
1098 if (F.hasPrefixData())
1099 emitFunctionPrefix(Prefix: {F.getPrefixData()});
1100
1101 // Emit KCFI type information before patchable-function-prefix nops.
1102 emitKCFITypeId(MF: *MF);
1103
1104 // Emit M NOPs for -fpatchable-function-entry=N,M where M>0. We arbitrarily
1105 // place prefix data before NOPs.
1106 unsigned PatchableFunctionPrefix =
1107 F.getFnAttributeAsParsedInteger(Kind: "patchable-function-prefix");
1108 unsigned PatchableFunctionEntry =
1109 F.getFnAttributeAsParsedInteger(Kind: "patchable-function-entry");
1110 if (PatchableFunctionPrefix) {
1111 CurrentPatchableFunctionEntrySym =
1112 OutContext.createLinkerPrivateTempSymbol();
1113 OutStreamer->emitLabel(Symbol: CurrentPatchableFunctionEntrySym);
1114 emitNops(N: PatchableFunctionPrefix);
1115 } else if (PatchableFunctionEntry) {
1116 // May be reassigned when emitting the body, to reference the label after
1117 // the initial BTI (AArch64) or endbr32/endbr64 (x86).
1118 CurrentPatchableFunctionEntrySym = CurrentFnBegin;
1119 }
1120
1121 // Emit the function prologue data for the indirect call sanitizer.
1122 if (const MDNode *MD = F.getMetadata(KindID: LLVMContext::MD_func_sanitize)) {
1123 assert(MD->getNumOperands() == 2);
1124
1125 auto *PrologueSig = mdconst::extract<Constant>(MD: MD->getOperand(I: 0));
1126 auto *TypeHash = mdconst::extract<Constant>(MD: MD->getOperand(I: 1));
1127 emitFunctionPrefix(Prefix: {PrologueSig, TypeHash});
1128 }
1129
1130 if (isVerbose()) {
1131 F.printAsOperand(O&: OutStreamer->getCommentOS(),
1132 /*PrintType=*/false, M: F.getParent());
1133 emitFunctionHeaderComment();
1134 OutStreamer->getCommentOS() << '\n';
1135 }
1136
1137 // Emit the function descriptor. This is a virtual function to allow targets
1138 // to emit their specific function descriptor. Right now it is only used by
1139 // the AIX target. The PowerPC 64-bit V1 ELF target also uses function
1140 // descriptors and should be converted to use this hook as well.
1141 if (MAI.isAIX())
1142 emitFunctionDescriptor();
1143
1144 // Emit the CurrentFnSym. This is a virtual function to allow targets to do
1145 // their wild and crazy things as required.
1146 emitFunctionEntryLabel();
1147
1148 // If the function had address-taken blocks that got deleted, then we have
1149 // references to the dangling symbols. Emit them at the start of the function
1150 // so that we don't get references to undefined symbols.
1151 std::vector<MCSymbol*> DeadBlockSyms;
1152 takeDeletedSymbolsForFunction(F: &F, Result&: DeadBlockSyms);
1153 for (MCSymbol *DeadBlockSym : DeadBlockSyms) {
1154 OutStreamer->AddComment(T: "Address taken block that was later removed");
1155 OutStreamer->emitLabel(Symbol: DeadBlockSym);
1156 }
1157
1158 if (CurrentFnBegin) {
1159 if (MAI.useAssignmentForEHBegin()) {
1160 MCSymbol *CurPos = OutContext.createTempSymbol();
1161 OutStreamer->emitLabel(Symbol: CurPos);
1162 OutStreamer->emitAssignment(Symbol: CurrentFnBegin,
1163 Value: MCSymbolRefExpr::create(Symbol: CurPos, Ctx&: OutContext));
1164 } else {
1165 OutStreamer->emitLabel(Symbol: CurrentFnBegin);
1166 }
1167 }
1168
1169 // Emit pre-function debug and/or EH information.
1170 for (auto &Handler : Handlers) {
1171 Handler->beginFunction(MF);
1172 Handler->beginBasicBlockSection(MBB: MF->front());
1173 }
1174 for (auto &Handler : EHHandlers) {
1175 Handler->beginFunction(MF);
1176 Handler->beginBasicBlockSection(MBB: MF->front());
1177 }
1178
1179 // Emit the prologue data.
1180 if (F.hasPrologueData())
1181 emitGlobalConstant(DL: F.getDataLayout(), CV: F.getPrologueData());
1182}
1183
1184/// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
1185/// function. This can be overridden by targets as required to do custom stuff.
1186void AsmPrinter::emitFunctionEntryLabel() {
1187 CurrentFnSym->redefineIfPossible();
1188 OutStreamer->emitLabel(Symbol: CurrentFnSym);
1189
1190 if (TM.getTargetTriple().isOSBinFormatELF()) {
1191 MCSymbol *Sym = getSymbolPreferLocal(GV: MF->getFunction());
1192 if (Sym != CurrentFnSym) {
1193 CurrentFnBeginLocal = Sym;
1194 OutStreamer->emitLabel(Symbol: Sym);
1195 OutStreamer->emitSymbolAttribute(Symbol: Sym, Attribute: MCSA_ELF_TypeFunction);
1196 }
1197 }
1198}
1199
1200/// emitComments - Pretty-print comments for instructions.
1201static void emitComments(const MachineInstr &MI, const MCSubtargetInfo *STI,
1202 raw_ostream &CommentOS) {
1203 const MachineFunction *MF = MI.getMF();
1204 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1205
1206 // Check for spills and reloads
1207
1208 // We assume a single instruction only has a spill or reload, not
1209 // both.
1210 std::optional<LocationSize> Size;
1211 if ((Size = MI.getRestoreSize(TII))) {
1212 CommentOS << Size->getValue() << "-byte Reload\n";
1213 } else if ((Size = MI.getFoldedRestoreSize(TII))) {
1214 if (!Size->hasValue())
1215 CommentOS << "Unknown-size Folded Reload\n";
1216 else if (Size->getValue())
1217 CommentOS << Size->getValue() << "-byte Folded Reload\n";
1218 } else if ((Size = MI.getSpillSize(TII))) {
1219 CommentOS << Size->getValue() << "-byte Spill\n";
1220 } else if ((Size = MI.getFoldedSpillSize(TII))) {
1221 if (!Size->hasValue())
1222 CommentOS << "Unknown-size Folded Spill\n";
1223 else if (Size->getValue())
1224 CommentOS << Size->getValue() << "-byte Folded Spill\n";
1225 }
1226
1227 // Check for spill-induced copies
1228 if (MI.getAsmPrinterFlag(Flag: MachineInstr::ReloadReuse))
1229 CommentOS << " Reload Reuse\n";
1230
1231 if (PrintLatency) {
1232 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1233 const MCSchedModel &SCModel = STI->getSchedModel();
1234 int Latency = SCModel.computeInstrLatency<MCSubtargetInfo, MCInstrInfo,
1235 InstrItineraryData, MachineInstr>(
1236 STI: *STI, MCII: *TII, Inst: MI);
1237 // Report only interesting latencies.
1238 if (1 < Latency)
1239 CommentOS << " Latency: " << Latency << "\n";
1240 }
1241}
1242
1243/// emitImplicitDef - This method emits the specified machine instruction
1244/// that is an implicit def.
1245void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
1246 Register RegNo = MI->getOperand(i: 0).getReg();
1247
1248 SmallString<128> Str;
1249 raw_svector_ostream OS(Str);
1250 OS << "implicit-def: "
1251 << printReg(Reg: RegNo, TRI: MF->getSubtarget().getRegisterInfo());
1252
1253 OutStreamer->AddComment(T: OS.str());
1254 OutStreamer->addBlankLine();
1255}
1256
1257static void emitFreeze(const MachineInstr *MI, AsmPrinter &AP) {
1258 AP.OutStreamer->getCommentOS()
1259 << "freeze: "
1260 << printReg(Reg: MI->getOperand(i: 0).getReg(),
1261 TRI: AP.MF->getSubtarget().getRegisterInfo())
1262 << '\n';
1263 AP.OutStreamer->addBlankLine();
1264}
1265
1266static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
1267 std::string Str;
1268 raw_string_ostream OS(Str);
1269 OS << "kill:";
1270 for (const MachineOperand &Op : MI->operands()) {
1271 assert(Op.isReg() && "KILL instruction must have only register operands");
1272 OS << ' ' << (Op.isDef() ? "def " : "killed ")
1273 << printReg(Reg: Op.getReg(), TRI: AP.MF->getSubtarget().getRegisterInfo());
1274 }
1275 AP.OutStreamer->AddComment(T: Str);
1276 AP.OutStreamer->addBlankLine();
1277}
1278
1279static void emitFakeUse(const MachineInstr *MI, AsmPrinter &AP) {
1280 std::string Str;
1281 raw_string_ostream OS(Str);
1282 OS << "fake_use:";
1283 for (const MachineOperand &Op : MI->operands()) {
1284 // In some circumstances we can end up with fake uses of constants; skip
1285 // these.
1286 if (!Op.isReg())
1287 continue;
1288 OS << ' ' << printReg(Reg: Op.getReg(), TRI: AP.MF->getSubtarget().getRegisterInfo());
1289 }
1290 AP.OutStreamer->AddComment(T: OS.str());
1291 AP.OutStreamer->addBlankLine();
1292}
1293
1294/// emitDebugValueComment - This method handles the target-independent form
1295/// of DBG_VALUE, returning true if it was able to do so. A false return
1296/// means the target will need to handle MI in EmitInstruction.
1297static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
1298 // This code handles only the 4-operand target-independent form.
1299 if (MI->isNonListDebugValue() && MI->getNumOperands() != 4)
1300 return false;
1301
1302 SmallString<128> Str;
1303 raw_svector_ostream OS(Str);
1304 OS << "DEBUG_VALUE: ";
1305
1306 const DILocalVariable *V = MI->getDebugVariable();
1307 if (auto *SP = dyn_cast<DISubprogram>(Val: V->getScope())) {
1308 StringRef Name = SP->getName();
1309 if (!Name.empty())
1310 OS << Name << ":";
1311 }
1312 OS << V->getName();
1313 OS << " <- ";
1314
1315 const DIExpression *Expr = MI->getDebugExpression();
1316 // First convert this to a non-variadic expression if possible, to simplify
1317 // the output.
1318 if (auto NonVariadicExpr = DIExpression::convertToNonVariadicExpression(Expr))
1319 Expr = *NonVariadicExpr;
1320 // Then, output the possibly-simplified expression.
1321 if (Expr->getNumElements()) {
1322 OS << '[';
1323 ListSeparator LS;
1324 for (auto &Op : Expr->expr_ops()) {
1325 OS << LS << dwarf::OperationEncodingString(Encoding: Op.getOp());
1326 for (unsigned I = 0; I < Op.getNumArgs(); ++I)
1327 OS << ' ' << Op.getArg(I);
1328 }
1329 OS << "] ";
1330 }
1331
1332 // Register or immediate value. Register 0 means undef.
1333 for (const MachineOperand &Op : MI->debug_operands()) {
1334 if (&Op != MI->debug_operands().begin())
1335 OS << ", ";
1336 switch (Op.getType()) {
1337 case MachineOperand::MO_FPImmediate: {
1338 APFloat APF = APFloat(Op.getFPImm()->getValueAPF());
1339 Type *ImmTy = Op.getFPImm()->getType();
1340 if (ImmTy->isBFloatTy() || ImmTy->isHalfTy() || ImmTy->isFloatTy() ||
1341 ImmTy->isDoubleTy()) {
1342 OS << APF.convertToDouble();
1343 } else {
1344 // There is no good way to print long double. Convert a copy to
1345 // double. Ah well, it's only a comment.
1346 bool ignored;
1347 APF.convert(ToSemantics: APFloat::IEEEdouble(), RM: APFloat::rmNearestTiesToEven,
1348 losesInfo: &ignored);
1349 OS << "(long double) " << APF.convertToDouble();
1350 }
1351 break;
1352 }
1353 case MachineOperand::MO_Immediate: {
1354 OS << Op.getImm();
1355 break;
1356 }
1357 case MachineOperand::MO_CImmediate: {
1358 Op.getCImm()->getValue().print(OS, isSigned: false /*isSigned*/);
1359 break;
1360 }
1361 case MachineOperand::MO_TargetIndex: {
1362 OS << "!target-index(" << Op.getIndex() << "," << Op.getOffset() << ")";
1363 break;
1364 }
1365 case MachineOperand::MO_GlobalAddress: {
1366 Op.getGlobal()->printAsOperand(O&: OS, /*PrintType=*/false);
1367 if (Op.getOffset())
1368 OS << '+' << Op.getOffset();
1369 break;
1370 }
1371 case MachineOperand::MO_Register:
1372 case MachineOperand::MO_FrameIndex: {
1373 Register Reg;
1374 std::optional<StackOffset> Offset;
1375 if (Op.isReg()) {
1376 Reg = Op.getReg();
1377 } else {
1378 const TargetFrameLowering *TFI =
1379 AP.MF->getSubtarget().getFrameLowering();
1380 Offset = TFI->getFrameIndexReference(MF: *AP.MF, FI: Op.getIndex(), FrameReg&: Reg);
1381 }
1382 if (!Reg) {
1383 // Suppress offset, it is not meaningful here.
1384 OS << "undef";
1385 break;
1386 }
1387 // The second operand is only an offset if it's an immediate.
1388 if (MI->isIndirectDebugValue())
1389 Offset = StackOffset::getFixed(Fixed: MI->getDebugOffset().getImm());
1390 if (Offset)
1391 OS << '[';
1392 OS << printReg(Reg, TRI: AP.MF->getSubtarget().getRegisterInfo());
1393 if (Offset)
1394 OS << '+' << Offset->getFixed() << ']';
1395 break;
1396 }
1397 default:
1398 llvm_unreachable("Unknown operand type");
1399 }
1400 }
1401
1402 // NOTE: Want this comment at start of line, don't emit with AddComment.
1403 AP.OutStreamer->emitRawComment(T: Str);
1404 return true;
1405}
1406
1407/// This method handles the target-independent form of DBG_LABEL, returning
1408/// true if it was able to do so. A false return means the target will need
1409/// to handle MI in EmitInstruction.
1410static bool emitDebugLabelComment(const MachineInstr *MI, AsmPrinter &AP) {
1411 if (MI->getNumOperands() != 1)
1412 return false;
1413
1414 SmallString<128> Str;
1415 raw_svector_ostream OS(Str);
1416 OS << "DEBUG_LABEL: ";
1417
1418 const DILabel *V = MI->getDebugLabel();
1419 if (auto *SP = dyn_cast<DISubprogram>(
1420 Val: V->getScope()->getNonLexicalBlockFileScope())) {
1421 StringRef Name = SP->getName();
1422 if (!Name.empty())
1423 OS << Name << ":";
1424 }
1425 OS << V->getName();
1426
1427 // NOTE: Want this comment at start of line, don't emit with AddComment.
1428 AP.OutStreamer->emitRawComment(T: OS.str());
1429 return true;
1430}
1431
1432AsmPrinter::CFISection
1433AsmPrinter::getFunctionCFISectionType(const Function &F) const {
1434 // Ignore functions that won't get emitted.
1435 if (F.isDeclarationForLinker())
1436 return CFISection::None;
1437
1438 if (ModuleExceptionModel == ExceptionHandling::DwarfCFI &&
1439 F.needsUnwindTableEntry())
1440 return CFISection::EH;
1441
1442 if (MAI.usesCFIWithoutEH(EH: ModuleExceptionModel) && F.hasUWTable())
1443 return CFISection::EH;
1444
1445 if (hasDebugInfo() || TM.Options.ForceDwarfFrameSection)
1446 return CFISection::Debug;
1447
1448 return CFISection::None;
1449}
1450
1451AsmPrinter::CFISection
1452AsmPrinter::getFunctionCFISectionType(const MachineFunction &MF) const {
1453 return getFunctionCFISectionType(F: MF.getFunction());
1454}
1455
1456bool AsmPrinter::usesCFIWithoutEH() const {
1457 return MAI.usesCFIWithoutEH(EH: ModuleExceptionModel) &&
1458 ModuleCFISection != CFISection::None;
1459}
1460
1461void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) {
1462 if (!usesCFIWithoutEH() &&
1463 ModuleExceptionModel != ExceptionHandling::DwarfCFI &&
1464 ModuleExceptionModel != ExceptionHandling::ARM)
1465 return;
1466
1467 if (getFunctionCFISectionType(MF: *MF) == CFISection::None)
1468 return;
1469
1470 // If there is no "real" instruction following this CFI instruction, skip
1471 // emitting it; it would be beyond the end of the function's FDE range.
1472 auto *MBB = MI.getParent();
1473 auto I = std::next(x: MI.getIterator());
1474 while (I != MBB->end() && I->isTransient())
1475 ++I;
1476 if (I == MBB->instr_end() &&
1477 MBB->getReverseIterator() == MBB->getParent()->rbegin())
1478 return;
1479
1480 const std::vector<MCCFIInstruction> &Instrs = MF->getFrameInstructions();
1481 unsigned CFIIndex = MI.getOperand(i: 0).getCFIIndex();
1482 const MCCFIInstruction &CFI = Instrs[CFIIndex];
1483 emitCFIInstruction(Inst: CFI);
1484}
1485
1486void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) {
1487 // The operands are the MCSymbol and the frame offset of the allocation.
1488 MCSymbol *FrameAllocSym = MI.getOperand(i: 0).getMCSymbol();
1489 int FrameOffset = MI.getOperand(i: 1).getImm();
1490
1491 // Emit a symbol assignment.
1492 OutStreamer->emitAssignment(Symbol: FrameAllocSym,
1493 Value: MCConstantExpr::create(Value: FrameOffset, Ctx&: OutContext));
1494}
1495
1496/// Returns the BB metadata to be emitted in the SHT_LLVM_BB_ADDR_MAP section
1497/// for a given basic block. This can be used to capture more precise profile
1498/// information.
1499static uint32_t getBBAddrMapMetadata(const MachineBasicBlock &MBB) {
1500 const TargetInstrInfo *TII = MBB.getParent()->getSubtarget().getInstrInfo();
1501 return object::BBAddrMap::BBEntry::Metadata{
1502 .HasReturn: MBB.isReturnBlock(), .HasTailCall: !MBB.empty() && TII->isTailCall(Inst: MBB.back()),
1503 .IsEHPad: MBB.isEHPad(), .CanFallThrough: const_cast<MachineBasicBlock &>(MBB).canFallThrough(),
1504 .HasIndirectBranch: !MBB.empty() && MBB.rbegin()->isIndirectBranch()}
1505 .encode();
1506}
1507
1508static llvm::object::BBAddrMap::Features
1509getBBAddrMapFeature(const MachineFunction &MF, int NumMBBSectionRanges,
1510 bool HasCalls, const CFGProfile *FuncCFGProfile) {
1511 // Ensure that the user has not passed in additional options while also
1512 // specifying all or none.
1513 auto IsSet = [](PGOMapFeaturesEnum F) {
1514 return is_contained(Range&: PgoAnalysisMapFeatures, Element: F);
1515 };
1516 bool NoFeatures = IsSet(PGOMapFeaturesEnum::None);
1517 bool AllFeatures = IsSet(PGOMapFeaturesEnum::All);
1518 if ((NoFeatures || AllFeatures) && !all_equal(Range&: PgoAnalysisMapFeatures)) {
1519 MF.getFunction().getContext().emitError(
1520 ErrorStr: "-pgo-analysis-map can accept only all or none with no additional "
1521 "values.");
1522 }
1523
1524 bool FuncEntryCountEnabled =
1525 AllFeatures || (!NoFeatures && IsSet(PGOMapFeaturesEnum::FuncEntryCount));
1526 bool BBFreqEnabled =
1527 AllFeatures || (!NoFeatures && IsSet(PGOMapFeaturesEnum::BBFreq));
1528 bool BrProbEnabled =
1529 AllFeatures || (!NoFeatures && IsSet(PGOMapFeaturesEnum::BrProb));
1530 bool PostLinkCfgEnabled = FuncCFGProfile && PgoAnalysisMapEmitBBSectionsCfg;
1531 // Only emit the GUID for functions with local linkage, whose symbol names
1532 // may not be unique across translation units. Other functions can be
1533 // identified by their symbol names.
1534 bool FuncGUIDEnabled =
1535 BBAddrMapEmitFuncGUID && MF.getFunction().hasLocalLinkage();
1536
1537 if ((BBFreqEnabled || BrProbEnabled) && BBAddrMapSkipEmitBBEntries) {
1538 MF.getFunction().getContext().emitError(
1539 ErrorStr: "BB entries info is required for BBFreq and BrProb features");
1540 }
1541 return {.FuncEntryCount: FuncEntryCountEnabled, .BBFreq: BBFreqEnabled, .BrProb: BrProbEnabled,
1542 .MultiBBRange: MF.hasBBSections() && NumMBBSectionRanges > 1,
1543 // Use static_cast to avoid breakage of tests on windows.
1544 .OmitBBEntries: static_cast<bool>(BBAddrMapSkipEmitBBEntries), .CallsiteEndOffsets: HasCalls,
1545 .BBHash: shouldEmitBBHash(), .PostLinkCfg: PostLinkCfgEnabled, .FuncGUID: FuncGUIDEnabled};
1546}
1547
1548void AsmPrinter::emitBBAddrMapSection(const MachineFunction &MF) {
1549 MCSection *BBAddrMapSection =
1550 getObjFileLowering().getBBAddrMapSection(TextSec: *MF.getSection());
1551 assert(BBAddrMapSection && ".llvm_bb_addr_map section is not initialized.");
1552 bool HasCalls = !CurrentFnCallsiteEndSymbols.empty();
1553
1554 const BasicBlockSectionsProfileReader *BBSPR = GetBBSPR(*this->MF);
1555 const CFGProfile *FuncCFGProfile = nullptr;
1556 if (BBSPR)
1557 FuncCFGProfile = BBSPR->getFunctionCFGProfile(FuncName: MF.getFunction().getName());
1558
1559 const MCSymbol *FunctionSymbol = getFunctionBegin();
1560
1561 OutStreamer->pushSection();
1562 OutStreamer->switchSection(Section: BBAddrMapSection);
1563 OutStreamer->AddComment(T: "version");
1564 uint8_t BBAddrMapVersion = OutStreamer->getContext().getBBAddrMapVersion();
1565 OutStreamer->emitInt8(Value: BBAddrMapVersion);
1566 OutStreamer->AddComment(T: "feature");
1567 auto Features = getBBAddrMapFeature(MF, NumMBBSectionRanges: MBBSectionRanges.size(), HasCalls,
1568 FuncCFGProfile);
1569 OutStreamer->emitInt16(Value: Features.encode());
1570 if (Features.FuncGUID) {
1571 // Use the GUID assigned by AssignGUIDPass if available. Otherwise, compute
1572 // it from the source file name and the function name.
1573 OutStreamer->AddComment(T: "function GUID");
1574 OutStreamer->emitInt64(Value: MF.getFunction().getGUIDOrFallback());
1575 }
1576 // Emit BB Information for each basic block in the function.
1577 if (Features.MultiBBRange) {
1578 OutStreamer->AddComment(T: "number of basic block ranges");
1579 OutStreamer->emitULEB128IntValue(Value: MBBSectionRanges.size());
1580 }
1581 // Number of blocks in each MBB section.
1582 DenseMap<MBBSectionID, unsigned> MBBSectionNumBlocks;
1583 const MCSymbol *PrevMBBEndSymbol = nullptr;
1584 if (!Features.MultiBBRange) {
1585 OutStreamer->AddComment(T: "function address");
1586 OutStreamer->emitSymbolValue(Sym: FunctionSymbol, Size: getPointerSize());
1587 OutStreamer->AddComment(T: "number of basic blocks");
1588 OutStreamer->emitULEB128IntValue(Value: MF.size());
1589 PrevMBBEndSymbol = FunctionSymbol;
1590 } else {
1591 unsigned BBCount = 0;
1592 for (const MachineBasicBlock &MBB : MF) {
1593 BBCount++;
1594 if (MBB.isEndSection()) {
1595 // Store each section's basic block count when it ends.
1596 MBBSectionNumBlocks[MBB.getSectionID()] = BBCount;
1597 // Reset the count for the next section.
1598 BBCount = 0;
1599 }
1600 }
1601 }
1602 // Emit the BB entry for each basic block in the function.
1603 for (const MachineBasicBlock &MBB : MF) {
1604 const MCSymbol *MBBSymbol =
1605 MBB.isEntryBlock() ? FunctionSymbol : MBB.getSymbol();
1606 bool IsBeginSection =
1607 Features.MultiBBRange && (MBB.isBeginSection() || MBB.isEntryBlock());
1608 if (IsBeginSection) {
1609 OutStreamer->AddComment(T: "base address");
1610 OutStreamer->emitSymbolValue(Sym: MBBSymbol, Size: getPointerSize());
1611 OutStreamer->AddComment(T: "number of basic blocks");
1612 OutStreamer->emitULEB128IntValue(Value: MBBSectionNumBlocks[MBB.getSectionID()]);
1613 PrevMBBEndSymbol = MBBSymbol;
1614 }
1615
1616 const MachineBlockHashInfoResult *MBHI =
1617 Features.BBHash ? GetMBHI(*this->MF) : nullptr;
1618
1619 if (!Features.OmitBBEntries) {
1620 OutStreamer->AddComment(T: "BB id");
1621 // Emit the BB ID for this basic block.
1622 // We only emit BaseID since CloneID is unset for
1623 // -basic-block-adress-map.
1624 // TODO: Emit the full BBID when labels and sections can be mixed
1625 // together.
1626 OutStreamer->emitULEB128IntValue(Value: MBB.getBBID()->BaseID);
1627 // Emit the basic block offset relative to the end of the previous block.
1628 // This is zero unless the block is padded due to alignment.
1629 emitLabelDifferenceAsULEB128(Hi: MBBSymbol, Lo: PrevMBBEndSymbol);
1630 const MCSymbol *CurrentLabel = MBBSymbol;
1631 if (HasCalls) {
1632 auto CallsiteEndSymbols = CurrentFnCallsiteEndSymbols.lookup(Val: &MBB);
1633 OutStreamer->AddComment(T: "number of callsites");
1634 OutStreamer->emitULEB128IntValue(Value: CallsiteEndSymbols.size());
1635 for (const MCSymbol *CallsiteEndSymbol : CallsiteEndSymbols) {
1636 // Emit the callsite offset.
1637 emitLabelDifferenceAsULEB128(Hi: CallsiteEndSymbol, Lo: CurrentLabel);
1638 CurrentLabel = CallsiteEndSymbol;
1639 }
1640 }
1641 // Emit the offset to the end of the block, which can be used to compute
1642 // the total block size.
1643 emitLabelDifferenceAsULEB128(Hi: MBB.getEndSymbol(), Lo: CurrentLabel);
1644 // Emit the Metadata.
1645 OutStreamer->emitULEB128IntValue(Value: getBBAddrMapMetadata(MBB));
1646 // Emit the Hash.
1647 if (MBHI) {
1648 OutStreamer->emitInt64(Value: MBHI->getMBBHash(MBB));
1649 }
1650 }
1651 PrevMBBEndSymbol = MBB.getEndSymbol();
1652 }
1653
1654 if (Features.hasPGOAnalysis()) {
1655 assert(BBAddrMapVersion >= 2 &&
1656 "PGOAnalysisMap only supports version 2 or later");
1657
1658 if (Features.FuncEntryCount) {
1659 OutStreamer->AddComment(T: "function entry count");
1660 auto MaybeEntryCount = MF.getFunction().getEntryCount();
1661 OutStreamer->emitULEB128IntValue(Value: MaybeEntryCount ? *MaybeEntryCount : 0);
1662 }
1663 const MachineBlockFrequencyInfo *MBFI =
1664 Features.BBFreq ? GetMBFI(*this->MF) : nullptr;
1665 const MachineBranchProbabilityInfo *MBPI =
1666 Features.BrProb ? GetMBPI(*this->MF) : nullptr;
1667
1668 if (Features.BBFreq || Features.BrProb) {
1669 for (const MachineBasicBlock &MBB : MF) {
1670 if (Features.BBFreq) {
1671 OutStreamer->AddComment(T: "basic block frequency");
1672 OutStreamer->emitULEB128IntValue(
1673 Value: MBFI->getBlockFreq(MBB: &MBB).getFrequency());
1674 if (Features.PostLinkCfg) {
1675 OutStreamer->AddComment(T: "basic block frequency (propeller)");
1676 OutStreamer->emitULEB128IntValue(
1677 Value: FuncCFGProfile->getBlockCount(BBID: *MBB.getBBID()));
1678 }
1679 }
1680 if (Features.BrProb) {
1681 unsigned SuccCount = MBB.succ_size();
1682 OutStreamer->AddComment(T: "basic block successor count");
1683 OutStreamer->emitULEB128IntValue(Value: SuccCount);
1684 for (const MachineBasicBlock *SuccMBB : MBB.successors()) {
1685 OutStreamer->AddComment(T: "successor BB ID");
1686 OutStreamer->emitULEB128IntValue(Value: SuccMBB->getBBID()->BaseID);
1687 OutStreamer->AddComment(T: "successor branch probability");
1688 OutStreamer->emitULEB128IntValue(
1689 Value: MBPI->getEdgeProbability(Src: &MBB, Dst: SuccMBB).getNumerator());
1690 if (Features.PostLinkCfg) {
1691 OutStreamer->AddComment(T: "successor branch frequency (propeller)");
1692 OutStreamer->emitULEB128IntValue(Value: FuncCFGProfile->getEdgeCount(
1693 SrcBBID: *MBB.getBBID(), SinkBBID: *SuccMBB->getBBID()));
1694 }
1695 }
1696 }
1697 }
1698 }
1699 }
1700
1701 OutStreamer->popSection();
1702}
1703
1704void AsmPrinter::emitKCFITrapEntry(const MachineFunction &MF,
1705 const MCSymbol *Symbol) {
1706 MCSection *Section =
1707 getObjFileLowering().getKCFITrapSection(TextSec: *MF.getSection());
1708 if (!Section)
1709 return;
1710
1711 OutStreamer->pushSection();
1712 OutStreamer->switchSection(Section);
1713
1714 MCSymbol *Loc = OutContext.createLinkerPrivateTempSymbol();
1715 OutStreamer->emitLabel(Symbol: Loc);
1716 OutStreamer->emitAbsoluteSymbolDiff(Hi: Symbol, Lo: Loc, Size: 4);
1717
1718 OutStreamer->popSection();
1719}
1720
1721void AsmPrinter::emitKCFITypeId(const MachineFunction &MF) {
1722 const Function &F = MF.getFunction();
1723 if (const MDNode *MD = F.getMetadata(KindID: LLVMContext::MD_kcfi_type))
1724 emitGlobalConstant(DL: F.getDataLayout(),
1725 CV: mdconst::extract<ConstantInt>(MD: MD->getOperand(I: 0)));
1726}
1727
1728void AsmPrinter::emitPseudoProbe(const MachineInstr &MI) {
1729 if (PP) {
1730 auto GUID = MI.getOperand(i: 0).getImm();
1731 auto Index = MI.getOperand(i: 1).getImm();
1732 auto Type = MI.getOperand(i: 2).getImm();
1733 auto Attr = MI.getOperand(i: 3).getImm();
1734 DILocation *DebugLoc = MI.getDebugLoc();
1735 PP->emitPseudoProbe(Guid: GUID, Index, Type, Attr, DebugLoc);
1736 }
1737}
1738
1739void AsmPrinter::emitStackSizeSection(const MachineFunction &MF) {
1740 if (!MF.getTarget().Options.EmitStackSizeSection)
1741 return;
1742
1743 MCSection *StackSizeSection =
1744 getObjFileLowering().getStackSizesSection(TextSec: *MF.getSection());
1745 if (!StackSizeSection)
1746 return;
1747
1748 const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1749 // Don't emit functions with dynamic stack allocations.
1750 if (FrameInfo.hasVarSizedObjects())
1751 return;
1752
1753 OutStreamer->pushSection();
1754 OutStreamer->switchSection(Section: StackSizeSection);
1755
1756 const MCSymbol *FunctionSymbol = getFunctionBegin();
1757 uint64_t StackSize =
1758 FrameInfo.getStackSize() + FrameInfo.getUnsafeStackSize();
1759 const DataLayout &DL = getDataLayout();
1760 OutStreamer->emitSymbolValue(Sym: FunctionSymbol,
1761 Size: DL.getPointerSize(AS: DL.getProgramAddressSpace()));
1762 OutStreamer->emitULEB128IntValue(Value: StackSize);
1763
1764 OutStreamer->popSection();
1765}
1766
1767void AsmPrinter::emitStackUsage(const MachineFunction &MF) {
1768 const std::string OutputFilename =
1769 !StackUsageFile.empty() ? StackUsageFile
1770 : MF.getTarget().Options.StackUsageFile;
1771
1772 // OutputFilename empty implies -fstack-usage is not passed.
1773 if (OutputFilename.empty())
1774 return;
1775
1776 const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1777 uint64_t StackSize =
1778 FrameInfo.getStackSize() + FrameInfo.getUnsafeStackSize();
1779
1780 if (StackUsageStream == nullptr) {
1781 std::error_code EC;
1782 StackUsageStream =
1783 std::make_unique<raw_fd_ostream>(args: OutputFilename, args&: EC, args: sys::fs::OF_Text);
1784 if (EC) {
1785 errs() << "Could not open file: " << EC.message();
1786 return;
1787 }
1788 }
1789
1790 if (const DISubprogram *DSP = MF.getFunction().getSubprogram())
1791 *StackUsageStream << DSP->getFilename() << ':' << DSP->getLine();
1792 else
1793 *StackUsageStream << MF.getFunction().getParent()->getName();
1794
1795 *StackUsageStream << ':' << MF.getName() << '\t' << StackSize << '\t';
1796 if (FrameInfo.hasVarSizedObjects())
1797 *StackUsageStream << "dynamic\n";
1798 else
1799 *StackUsageStream << "static\n";
1800}
1801
1802/// Extracts a numeric type identifier of a Function's type from
1803/// callgraph metadata. Returns null if metadata cannot be found.
1804static ConstantInt *extractNumericCGTypeId(const Function &F) {
1805 SmallVector<MDNode *, 2> Types;
1806 F.getMetadata(KindID: LLVMContext::MD_callgraph, MDs&: Types);
1807 for (const auto &Type : Types) {
1808 if (Type->getNumOperands() == 1 && isa<MDString>(Val: Type->getOperand(I: 0))) {
1809 MDString *MDTypeId = cast<MDString>(Val: Type->getOperand(I: 0));
1810 uint64_t TypeIdVal = llvm::MD5Hash(Str: MDTypeId->getString());
1811 IntegerType *Int64Ty = Type::getInt64Ty(C&: F.getContext());
1812 return ConstantInt::get(Ty: Int64Ty, V: TypeIdVal);
1813 }
1814 }
1815 return nullptr;
1816}
1817
1818/// Emits .llvm.callgraph section.
1819void AsmPrinter::emitCallGraphSection(const MachineFunction &MF,
1820 FunctionCallGraphInfo &FuncCGInfo) {
1821 if (!MF.getTarget().Options.EmitCallGraphSection)
1822 return;
1823
1824 // Switch to the call graph section for the function
1825 MCSection *FuncCGSection =
1826 getObjFileLowering().getCallGraphSection(TextSec: *getCurrentSection());
1827 assert(FuncCGSection && "null callgraph section");
1828 OutStreamer->pushSection();
1829 OutStreamer->switchSection(Section: FuncCGSection);
1830
1831 const Function &F = MF.getFunction();
1832 // If this function has external linkage or has its address taken and
1833 // it is not a callback, then anything could call it.
1834 bool IsIndirectTarget =
1835 !F.hasLocalLinkage() || F.hasAddressTaken(nullptr,
1836 /*IgnoreCallbackUses=*/true,
1837 /*IgnoreAssumeLikeCalls=*/true,
1838 /*IgnoreLLVMUsed=*/IngoreLLVMUsed: false);
1839
1840 const auto &DirectCallees = FuncCGInfo.DirectCallees;
1841 const auto &IndirectCalleeTypeIDs = FuncCGInfo.IndirectCalleeTypeIDs;
1842
1843 using namespace callgraph;
1844 Flags CGFlags = Flags::None;
1845 if (IsIndirectTarget)
1846 CGFlags |= Flags::IsIndirectTarget;
1847 if (DirectCallees.size() > 0)
1848 CGFlags |= Flags::HasDirectCallees;
1849 if (IndirectCalleeTypeIDs.size() > 0)
1850 CGFlags |= Flags::HasIndirectCallees;
1851
1852 // Emit function's call graph information.
1853 // 1) CallGraphSectionFormatVersion
1854 // 2) Flags
1855 // a. LSB bit 0 is set to 1 if the function is a potential indirect
1856 // target.
1857 // b. LSB bit 1 is set to 1 if there are direct callees.
1858 // c. LSB bit 2 is set to 1 if there are indirect callees.
1859 // d. Rest of the 5 bits in Flags are reserved for any future use.
1860 // 3) Function entry PC.
1861 // 4) FunctionTypeID if the function is indirect target and its type id
1862 // is known, otherwise it is set to 0.
1863 // 5) Number of unique direct callees, if at least one exists.
1864 // 6) For each unique direct callee, the callee's PC.
1865 // 7) Number of unique indirect target type IDs, if at least one exists.
1866 // 8) Each unique indirect target type id.
1867 const DataLayout &DL = getDataLayout();
1868 unsigned ProgramPointerSize = DL.getPointerSize(AS: DL.getProgramAddressSpace());
1869 OutStreamer->emitInt8(Value: CallGraphSectionFormatVersion::V_0);
1870 OutStreamer->emitInt8(Value: static_cast<uint8_t>(CGFlags));
1871 OutStreamer->emitSymbolValue(Sym: getSymbol(GV: &F), Size: ProgramPointerSize);
1872 const auto *TypeId = extractNumericCGTypeId(F);
1873 if (IsIndirectTarget && TypeId)
1874 OutStreamer->emitInt64(Value: TypeId->getZExtValue());
1875 else
1876 OutStreamer->emitInt64(Value: 0);
1877
1878 if (DirectCallees.size() > 0) {
1879 OutStreamer->emitULEB128IntValue(Value: DirectCallees.size());
1880 for (const auto &CalleeSymbol : DirectCallees)
1881 OutStreamer->emitSymbolValue(Sym: CalleeSymbol, Size: ProgramPointerSize);
1882 FuncCGInfo.DirectCallees.clear();
1883 }
1884 if (IndirectCalleeTypeIDs.size() > 0) {
1885 OutStreamer->emitULEB128IntValue(Value: IndirectCalleeTypeIDs.size());
1886 for (const auto &CalleeTypeId : IndirectCalleeTypeIDs)
1887 OutStreamer->emitInt64(Value: CalleeTypeId);
1888 FuncCGInfo.IndirectCalleeTypeIDs.clear();
1889 }
1890 // End of emitting call graph section contents.
1891 OutStreamer->popSection();
1892}
1893
1894void AsmPrinter::emitPCSectionsLabel(const MachineFunction &MF,
1895 const MDNode &MD) {
1896 MCSymbol *S = MF.getContext().createTempSymbol(Name: "pcsection");
1897 OutStreamer->emitLabel(Symbol: S);
1898 PCSectionsSymbols[&MD].emplace_back(Args&: S);
1899}
1900
1901void AsmPrinter::emitPCSections(const MachineFunction &MF) {
1902 const Function &F = MF.getFunction();
1903 if (PCSectionsSymbols.empty() && !F.hasMetadata(KindID: LLVMContext::MD_pcsections))
1904 return;
1905
1906 const CodeModel::Model CM = MF.getTarget().getCodeModel();
1907 const unsigned RelativeRelocSize =
1908 (CM == CodeModel::Medium || CM == CodeModel::Large) ? getPointerSize()
1909 : 4;
1910
1911 // Switch to PCSection, short-circuiting the common case where the current
1912 // section is still valid (assume most MD_pcsections contain just 1 section).
1913 auto SwitchSection = [&, Prev = StringRef()](const StringRef &Sec) mutable {
1914 if (Sec == Prev)
1915 return;
1916 MCSection *S = getObjFileLowering().getPCSection(Name: Sec, TextSec: MF.getSection());
1917 assert(S && "PC section is not initialized");
1918 OutStreamer->switchSection(Section: S);
1919 Prev = Sec;
1920 };
1921 // Emit records into sections as specified in the pcsections MDNode. A record
1922 // is the PC of an instruction, or the start and size of a function, followed
1923 // by the auxiliary data of the section.
1924 auto EmitForMD = [&](const MDNode &MD, ArrayRef<const MCSymbol *> Syms,
1925 bool IsFunction) {
1926 // Expect the first operand to be a section name. After that, a tuple of
1927 // constants may appear, which will simply be emitted into the current
1928 // section (the user of MD_pcsections decides the format of encoded data).
1929 assert(isa<MDString>(MD.getOperand(0)) && "first operand not a string");
1930 const ArrayRef<MDOperand> Ops = MD.operands();
1931 for (size_t I = 0; I < Ops.size();) {
1932 // Found string, start of new section!
1933 // Find options for this section "<section>!<opts>" - supported options:
1934 // C = Compress constant integers of size 2-8 bytes as ULEB128.
1935 const StringRef SecWithOpt = cast<MDString>(Val: Ops[I++])->getString();
1936 const size_t OptStart = SecWithOpt.find(C: '!'); // likely npos
1937 const StringRef Sec = SecWithOpt.substr(Start: 0, N: OptStart);
1938 const StringRef Opts = SecWithOpt.substr(Start: OptStart); // likely empty
1939 const bool ConstULEB128 = Opts.contains(C: 'C');
1940#ifndef NDEBUG
1941 for (char O : Opts)
1942 assert((O == '!' || O == 'C') && "Invalid !pcsections options");
1943#endif
1944 // The auxiliary data of this section are the tuples up to the next
1945 // section name.
1946 const size_t AuxBegin = I;
1947 while (I < Ops.size() && !isa<MDString>(Val: Ops[I]))
1948 ++I;
1949 const ArrayRef<MDOperand> Aux = Ops.slice(N: AuxBegin, M: I - AuxBegin);
1950
1951 // Metadata does not keep globals alive, and passes such as ThinLTO
1952 // function import do not follow references from metadata, so a constant
1953 // may have been dropped (nulled). Omit the records rather than emit them
1954 // without their auxiliary data.
1955 if (any_of(Range: Aux, P: [](const MDOperand &MDO) {
1956 const auto *AuxMDs = dyn_cast<MDNode>(Val: MDO);
1957 return AuxMDs && is_contained(Range: AuxMDs->operands(), Element: nullptr);
1958 }))
1959 continue;
1960
1961 auto EmitAux = [&] {
1962 for (const MDOperand &MDO : Aux) {
1963 assert(isa<MDNode>(MDO) && "expecting either string or tuple");
1964 for (const MDOperand &AuxMDO : cast<MDNode>(Val: MDO)->operands()) {
1965 assert(isa<ConstantAsMetadata>(AuxMDO) && "expecting a constant");
1966 const Constant *C = cast<ConstantAsMetadata>(Val: AuxMDO)->getValue();
1967 const DataLayout &DL = F.getDataLayout();
1968 const uint64_t Size = DL.getTypeStoreSize(Ty: C->getType());
1969
1970 if (auto *CI = dyn_cast<ConstantInt>(Val: C);
1971 CI && ConstULEB128 && Size > 1 && Size <= 8) {
1972 emitULEB128(Value: CI->getZExtValue());
1973 } else {
1974 emitGlobalConstant(DL, CV: C);
1975 }
1976 }
1977 }
1978 };
1979 // Emit the address of Sym relative to the entry itself, which avoids a
1980 // dynamic relocation in the final binary. User will get the address with
1981 // `base + addr`.
1982 auto EmitRelativePC = [&](const MCSymbol *Sym) {
1983 MCSymbol *Base = MF.getContext().createTempSymbol(Name: "pcsection_base");
1984 OutStreamer->emitLabel(Symbol: Base);
1985 emitLabelDifference(Hi: Sym, Lo: Base, Size: RelativeRelocSize);
1986 };
1987
1988 SwitchSection(Sec);
1989 if (IsFunction) {
1990 // One record: function start, function size, auxiliary data.
1991 assert(Syms.size() == 2 && "expecting function begin and end");
1992 EmitRelativePC(Syms[0]);
1993 if (ConstULEB128)
1994 emitLabelDifferenceAsULEB128(Hi: Syms[1], Lo: Syms[0]);
1995 else
1996 emitLabelDifference(Hi: Syms[1], Lo: Syms[0], Size: 4);
1997 EmitAux();
1998 } else {
1999 // One record per instruction: PC, auxiliary data.
2000 for (const MCSymbol *Sym : Syms) {
2001 EmitRelativePC(Sym);
2002 EmitAux();
2003 }
2004 }
2005 }
2006 };
2007
2008 OutStreamer->pushSection();
2009 // Emit PCs for function start and function size.
2010 if (const MDNode *MD = F.getMetadata(KindID: LLVMContext::MD_pcsections))
2011 EmitForMD(*MD, {getFunctionBegin(), getFunctionEnd()}, true);
2012 // Emit PCs for instructions collected.
2013 for (const auto &MS : PCSectionsSymbols)
2014 EmitForMD(*MS.first, MS.second, false);
2015 OutStreamer->popSection();
2016 PCSectionsSymbols.clear();
2017}
2018
2019/// Returns true if function begin and end labels should be emitted.
2020static bool needFuncLabels(const MachineFunction &MF, const AsmPrinter &Asm) {
2021 if (Asm.hasDebugInfo() || !MF.getLandingPads().empty() ||
2022 MF.hasEHFunclets() ||
2023 MF.getFunction().hasMetadata(KindID: LLVMContext::MD_pcsections))
2024 return true;
2025
2026 // We might emit an EH table that uses function begin and end labels even if
2027 // we don't have any landingpads.
2028 if (!MF.getFunction().hasPersonalityFn())
2029 return false;
2030 return !isNoOpWithoutInvoke(
2031 Pers: classifyEHPersonality(Pers: MF.getFunction().getPersonalityFn()));
2032}
2033
2034// Return the mnemonic of a MachineInstr if available, or the MachineInstr
2035// opcode name otherwise.
2036static StringRef getMIMnemonic(const MachineInstr &MI, MCStreamer &Streamer) {
2037 const TargetInstrInfo *TII =
2038 MI.getParent()->getParent()->getSubtarget().getInstrInfo();
2039 MCInst MCI;
2040 MCI.setOpcode(MI.getOpcode());
2041 if (StringRef Name = Streamer.getMnemonic(MI: MCI); !Name.empty())
2042 return Name;
2043 StringRef Name = TII->getName(Opcode: MI.getOpcode());
2044 assert(!Name.empty() && "Missing mnemonic and name for opcode");
2045 return Name;
2046}
2047
2048void AsmPrinter::handleCallsiteForCallgraph(
2049 FunctionCallGraphInfo &FuncCGInfo,
2050 const MachineFunction::CallSiteInfoMap &CallSitesInfoMap,
2051 const MachineInstr &MI) {
2052 assert(MI.isCall() && "This method is meant for call instructions only.");
2053 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
2054 const MachineOperand &CalleeOperand = TII->getCalleeOperand(MI);
2055 if (CalleeOperand.isGlobal() || CalleeOperand.isSymbol()) {
2056 // Handle direct calls.
2057 MCSymbol *CalleeSymbol = nullptr;
2058 switch (CalleeOperand.getType()) {
2059 case llvm::MachineOperand::MO_GlobalAddress:
2060 CalleeSymbol = getSymbol(GV: CalleeOperand.getGlobal());
2061 break;
2062 case llvm::MachineOperand::MO_ExternalSymbol:
2063 CalleeSymbol = GetExternalSymbolSymbol(Sym: CalleeOperand.getSymbolName());
2064 break;
2065 default:
2066 llvm_unreachable(
2067 "Expected to only handle direct call instructions here.");
2068 }
2069 FuncCGInfo.DirectCallees.insert(X: CalleeSymbol);
2070 return; // Early exit after handling the direct call instruction.
2071 }
2072 const auto &CallSiteInfo = CallSitesInfoMap.find(Val: &MI);
2073 if (CallSiteInfo == CallSitesInfoMap.end())
2074 return;
2075 // Handle indirect callsite info.
2076 // Only indirect calls have type identifiers set.
2077 for (ConstantInt *CalleeTypeId : CallSiteInfo->second.CalleeTypeIds) {
2078 uint64_t CalleeTypeIdVal = CalleeTypeId->getZExtValue();
2079 FuncCGInfo.IndirectCalleeTypeIDs.insert(X: CalleeTypeIdVal);
2080 }
2081}
2082
2083/// Helper to emit a symbol for the prefetch target associated with the given
2084/// BBID and callsite index.
2085void AsmPrinter::emitPrefetchTargetSymbol(const UniqueBBID &BBID,
2086 unsigned CallsiteIndex) {
2087 SmallString<128> FunctionName;
2088 getNameWithPrefix(Name&: FunctionName, GV: &MF->getFunction());
2089 MCSymbol *PrefetchTargetSymbol = OutContext.getOrCreateSymbol(
2090 Name: getPrefetchTargetSymbolName(FunctionName, BBID, CallsiteIndex));
2091 // If the function is weak-linkage it may be replaced by a strong
2092 // version, in which case the prefetch targets should also be replaced.
2093 OutStreamer->emitSymbolAttribute(
2094 Symbol: PrefetchTargetSymbol,
2095 Attribute: MF->getFunction().isWeakForLinker() ? MCSA_Weak : MCSA_Global);
2096 OutStreamer->emitLabel(Symbol: PrefetchTargetSymbol);
2097}
2098
2099/// Emit dangling prefetch targets that were not mapped to any basic block.
2100void AsmPrinter::emitDanglingPrefetchTargets() {
2101 const DenseMap<UniqueBBID, SmallVector<unsigned>> &MFPrefetchTargets =
2102 MF->getPrefetchTargets();
2103 if (MFPrefetchTargets.empty())
2104 return;
2105 DenseSet<UniqueBBID> MFBBIDs;
2106 for (const MachineBasicBlock &MBB : *MF)
2107 if (std::optional<UniqueBBID> BBID = MBB.getBBID())
2108 MFBBIDs.insert(V: *BBID);
2109
2110 for (const auto &[BBID, CallsiteIndexes] : MFPrefetchTargets) {
2111 if (MFBBIDs.contains(V: BBID))
2112 continue;
2113 for (unsigned CallsiteIndex : CallsiteIndexes)
2114 emitPrefetchTargetSymbol(BBID, CallsiteIndex);
2115 }
2116}
2117
2118/// EmitFunctionBody - This method emits the body and trailer for a
2119/// function.
2120void AsmPrinter::emitFunctionBody() {
2121 emitFunctionHeader();
2122
2123 // Emit target-specific gunk before the function body.
2124 emitFunctionBodyStart();
2125
2126 if (isVerbose()) {
2127 MDT = GetMDT(*MF);
2128 // Get MachineLoopInfo or compute it on the fly if it's unavailable, which
2129 // needs a MachineDominatorTree only for an irreducible CFG.
2130 MLI = GetMLI(*MF);
2131 if (!MLI) {
2132 OwnedMLI = std::make_unique<MachineLoopInfo>();
2133 OwnedMLI->calculate(MF&: *MF, GetDomTree: [&]() -> const MachineDominatorTree & {
2134 if (!MDT) {
2135 OwnedMDT = std::make_unique<MachineDominatorTree>();
2136 OwnedMDT->recalculate(Func&: *MF);
2137 MDT = OwnedMDT.get();
2138 }
2139 return *MDT;
2140 });
2141 MLI = OwnedMLI.get();
2142 }
2143 }
2144
2145 // Print out code for the function.
2146 bool HasAnyRealCode = false;
2147 int NumInstsInFunction = 0;
2148 // Only x86 needs this padding; the Arm unwinders back the PC up themselves.
2149 const Module *M = MMI->getModule();
2150 bool NeedsEHaNops =
2151 M->getTargetTriple().isX86() && M->getModuleFlag(Key: "eh-asynch");
2152
2153 const MCSubtargetInfo *STI = nullptr;
2154 if (this->MF)
2155 STI = &getSubtargetInfo();
2156 else
2157 STI = &TM.getMCSubtargetInfo();
2158
2159 bool CanDoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
2160 // Create a slot for the entry basic block section so that the section
2161 // order is preserved when iterating over MBBSectionRanges.
2162 if (!MF->empty())
2163 MBBSectionRanges[MF->front().getSectionID()] =
2164 MBBSectionRange{.BeginLabel: CurrentFnBegin, .EndLabel: nullptr};
2165
2166 FunctionCallGraphInfo FuncCGInfo;
2167 const auto &CallSitesInfoMap = MF->getCallSitesInfo();
2168
2169 // Dangling targets are not mapped to any blocks and must be emitted at the
2170 // beginning of the function.
2171 emitDanglingPrefetchTargets();
2172
2173 const auto &MFPrefetchTargets = MF->getPrefetchTargets();
2174 for (auto &MBB : *MF) {
2175 // Print a label for the basic block.
2176 emitBasicBlockStart(MBB);
2177 DenseMap<StringRef, unsigned> MnemonicCounts;
2178
2179 const SmallVector<unsigned> *PrefetchTargets = nullptr;
2180 if (auto BBID = MBB.getBBID()) {
2181 auto R = MFPrefetchTargets.find(Val: *BBID);
2182 if (R != MFPrefetchTargets.end())
2183 PrefetchTargets = &R->second;
2184 }
2185 auto PrefetchTargetIt =
2186 PrefetchTargets ? PrefetchTargets->begin() : nullptr;
2187 auto PrefetchTargetEnd = PrefetchTargets ? PrefetchTargets->end() : nullptr;
2188 unsigned LastCallsiteIndex = 0;
2189
2190 for (auto &MI : MBB) {
2191 if (PrefetchTargetIt != PrefetchTargetEnd &&
2192 *PrefetchTargetIt == LastCallsiteIndex) {
2193 emitPrefetchTargetSymbol(BBID: *MBB.getBBID(), CallsiteIndex: *PrefetchTargetIt);
2194 ++PrefetchTargetIt;
2195 }
2196
2197 // Print the assembly for the instruction.
2198 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
2199 !MI.isDebugInstr()) {
2200 HasAnyRealCode = true;
2201 }
2202
2203 // If there is a pre-instruction symbol, emit a label for it here.
2204 if (MCSymbol *S = MI.getPreInstrSymbol())
2205 OutStreamer->emitLabel(Symbol: S);
2206
2207 if (MDNode *MD = MI.getPCSections())
2208 emitPCSectionsLabel(MF: *MF, MD: *MD);
2209
2210 for (auto &Handler : Handlers)
2211 Handler->beginInstruction(MI: &MI);
2212
2213 if (isVerbose())
2214 emitComments(MI, STI, CommentOS&: OutStreamer->getCommentOS());
2215
2216#ifndef NDEBUG
2217 MCFragment *OldFragment = OutStreamer->getCurrentFragment();
2218 size_t OldFragSize = OldFragment->getFixedSize();
2219#endif
2220
2221 switch (MI.getOpcode()) {
2222 case TargetOpcode::CFI_INSTRUCTION:
2223 emitCFIInstruction(MI);
2224 break;
2225 case TargetOpcode::LOCAL_ESCAPE:
2226 emitFrameAlloc(MI);
2227 break;
2228 case TargetOpcode::ANNOTATION_LABEL:
2229 case TargetOpcode::GC_LABEL:
2230 OutStreamer->emitLabel(Symbol: MI.getOperand(i: 0).getMCSymbol());
2231 break;
2232 case TargetOpcode::EH_LABEL:
2233 OutStreamer->AddComment(T: "EH_LABEL");
2234 OutStreamer->emitLabel(Symbol: MI.getOperand(i: 0).getMCSymbol());
2235 // For AsynchEH, insert a Nop if followed by a trap inst
2236 // Or the exception won't be caught.
2237 // (see MCConstantExpr::create(1,..) in WinException.cpp)
2238 // Ignore SDiv/UDiv because a DIV with Const-0 divisor
2239 // must have being turned into an UndefValue.
2240 // Div with variable opnds won't be the first instruction in
2241 // an EH region as it must be led by at least a Load
2242 {
2243 auto MI2 = std::next(x: MI.getIterator());
2244 if (NeedsEHaNops && MI2 != MBB.end() &&
2245 (MI2->mayLoadOrStore() || MI2->mayRaiseFPException()))
2246 emitNops(N: 1);
2247 }
2248 break;
2249 case TargetOpcode::INLINEASM:
2250 case TargetOpcode::INLINEASM_BR:
2251 emitInlineAsm(MI: &MI);
2252 break;
2253 case TargetOpcode::DBG_VALUE:
2254 case TargetOpcode::DBG_VALUE_LIST:
2255 if (isVerbose()) {
2256 if (!emitDebugValueComment(MI: &MI, AP&: *this))
2257 emitInstruction(&MI);
2258 }
2259 break;
2260 case TargetOpcode::DBG_INSTR_REF:
2261 // This instruction reference will have been resolved to a machine
2262 // location, and a nearby DBG_VALUE created. We can safely ignore
2263 // the instruction reference.
2264 break;
2265 case TargetOpcode::DBG_PHI:
2266 // This instruction is only used to label a program point, it's purely
2267 // meta information.
2268 break;
2269 case TargetOpcode::DBG_LABEL:
2270 if (isVerbose()) {
2271 if (!emitDebugLabelComment(MI: &MI, AP&: *this))
2272 emitInstruction(&MI);
2273 }
2274 break;
2275 case TargetOpcode::IMPLICIT_DEF:
2276 if (isVerbose()) emitImplicitDef(MI: &MI);
2277 break;
2278 case TargetOpcode::KILL:
2279 if (isVerbose()) emitKill(MI: &MI, AP&: *this);
2280 break;
2281 case TargetOpcode::FAKE_USE:
2282 if (isVerbose())
2283 emitFakeUse(MI: &MI, AP&: *this);
2284 break;
2285 case TargetOpcode::PSEUDO_PROBE:
2286 emitPseudoProbe(MI);
2287 break;
2288 case TargetOpcode::ARITH_FENCE:
2289 if (isVerbose())
2290 OutStreamer->emitRawComment(T: "ARITH_FENCE");
2291 break;
2292 case TargetOpcode::MEMBARRIER:
2293 OutStreamer->emitRawComment(T: "MEMBARRIER");
2294 break;
2295 case TargetOpcode::JUMP_TABLE_DEBUG_INFO:
2296 // This instruction is only used to note jump table debug info, it's
2297 // purely meta information.
2298 break;
2299 case TargetOpcode::INIT_UNDEF:
2300 // This is only used to influence register allocation behavior, no
2301 // actual initialization is needed.
2302 break;
2303 case TargetOpcode::FREEZE:
2304 // Only a FREEZE of an undefined value is left. Whatever the register
2305 // holds is a valid frozen value.
2306 if (isVerbose())
2307 emitFreeze(MI: &MI, AP&: *this);
2308 break;
2309 case TargetOpcode::RELOC_NONE: {
2310 // Generate a temporary label for the current PC.
2311 MCSymbol *Sym = OutContext.createTempSymbol(Name: "reloc_none");
2312 OutStreamer->emitLabel(Symbol: Sym);
2313 const MCExpr *Dot = MCSymbolRefExpr::create(Symbol: Sym, Ctx&: OutContext);
2314 const MCExpr *Value = MCSymbolRefExpr::create(
2315 Symbol: OutContext.getOrCreateSymbol(Name: MI.getOperand(i: 0).getSymbolName()),
2316 Ctx&: OutContext);
2317 OutStreamer->emitRelocDirective(Offset: *Dot, Name: "BFD_RELOC_NONE", Expr: Value, Loc: SMLoc());
2318 break;
2319 }
2320 default:
2321 emitInstruction(&MI);
2322
2323 auto CountInstruction = [&](const MachineInstr &MI) {
2324 // Skip Meta instructions inside bundles.
2325 if (MI.isMetaInstruction())
2326 return;
2327 ++NumInstsInFunction;
2328 if (CanDoExtraAnalysis) {
2329 StringRef Name = getMIMnemonic(MI, Streamer&: *OutStreamer);
2330 ++MnemonicCounts[Name];
2331 }
2332 };
2333 if (!MI.isBundle()) {
2334 CountInstruction(MI);
2335 break;
2336 }
2337 // Separately count all the instructions in a bundle.
2338 for (auto It = std::next(x: MI.getIterator());
2339 It != MBB.end() && It->isInsideBundle(); ++It) {
2340 CountInstruction(*It);
2341 }
2342 break;
2343 }
2344
2345#ifndef NDEBUG
2346 // Verify that the instruction size reported by InstrInfo matches the
2347 // actually emitted size. Many backends performing branch relaxation
2348 // on the MIR level rely on this for correctness.
2349 // TODO: We currently can't distinguish whether a parse error occurred
2350 // when handling INLINEASM.
2351 if (OutStreamer->isObj() && !OutContext.hadError() &&
2352 (MI.getOpcode() != TargetOpcode::INLINEASM &&
2353 MI.getOpcode() != TargetOpcode::INLINEASM_BR)) {
2354 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
2355 TargetInstrInfo::InstSizeVerifyMode Mode =
2356 TII->getInstSizeVerifyMode(MI);
2357 if (Mode != TargetInstrInfo::InstSizeVerifyMode::NoVerify) {
2358 unsigned ExpectedSize = TII->getInstSizeInBytes(MI);
2359 MCFragment *NewFragment = OutStreamer->getCurrentFragment();
2360 unsigned ActualSize;
2361 if (OldFragment == NewFragment) {
2362 ActualSize = NewFragment->getFixedSize() - OldFragSize;
2363 } else {
2364 ActualSize = OldFragment->getFixedSize() - OldFragSize;
2365 const MCFragment *F = OldFragment->getNext();
2366 for (; F != NewFragment; F = F->getNext())
2367 ActualSize += F->getFixedSize();
2368 ActualSize += NewFragment->getFixedSize();
2369 }
2370 bool AllowOverEstimate =
2371 Mode == TargetInstrInfo::InstSizeVerifyMode::AllowOverEstimate;
2372 bool Valid = AllowOverEstimate ? ActualSize <= ExpectedSize
2373 : ActualSize == ExpectedSize;
2374 if (!Valid) {
2375 dbgs() << "In function: " << MF->getName() << "\n";
2376 dbgs() << "Size mismatch for: " << MI;
2377 if (MI.isBundled()) {
2378 dbgs() << "{\n";
2379 auto It = MI.getIterator(), End = MBB.instr_end();
2380 for (++It; It != End && It->isInsideBundle(); ++It)
2381 dbgs().indent(2) << *It;
2382 dbgs() << "}\n";
2383 }
2384 dbgs() << "Expected " << (AllowOverEstimate ? "maximum" : "exact")
2385 << " size: " << ExpectedSize << "\n";
2386 dbgs() << "Actual size: " << ActualSize << "\n";
2387 abort();
2388 }
2389 }
2390 }
2391#endif
2392
2393 if (MI.isCall()) {
2394 if (MF->getTarget().Options.BBAddrMap)
2395 OutStreamer->emitLabel(Symbol: createCallsiteEndSymbol(MBB));
2396 LastCallsiteIndex++;
2397 }
2398
2399 if (TM.Options.EmitCallGraphSection && MI.isCall())
2400 handleCallsiteForCallgraph(FuncCGInfo, CallSitesInfoMap, MI);
2401
2402 // If there is a post-instruction symbol, emit a label for it here.
2403 if (MCSymbol *S = MI.getPostInstrSymbol()) {
2404 // Emit the weak symbol attribute used for the prefetch target fallback.
2405 if (M->getTargetTriple().isOSBinFormatELF()) {
2406 MCSymbolELF *ESym = static_cast<MCSymbolELF *>(S);
2407 if (ESym->getBinding() == ELF::STB_WEAK)
2408 OutStreamer->emitSymbolAttribute(Symbol: S, Attribute: MCSA_Weak);
2409 }
2410 OutStreamer->emitLabel(Symbol: S);
2411 }
2412
2413 for (auto &Handler : Handlers)
2414 Handler->endInstruction();
2415 }
2416 // Emit the remaining prefetch targets for this block. This includes
2417 // nonexisting callsite indexes.
2418 while (PrefetchTargetIt != PrefetchTargetEnd) {
2419 emitPrefetchTargetSymbol(BBID: *MBB.getBBID(), CallsiteIndex: *PrefetchTargetIt);
2420 ++PrefetchTargetIt;
2421 }
2422
2423 // We must emit temporary symbol for the end of this basic block, if either
2424 // we have BBLabels enabled or if this basic blocks marks the end of a
2425 // section.
2426 if (MF->getTarget().Options.BBAddrMap ||
2427 (MAI.hasDotTypeDotSizeDirective() && MBB.isEndSection()))
2428 OutStreamer->emitLabel(Symbol: MBB.getEndSymbol());
2429
2430 if (MBB.isEndSection()) {
2431 // The size directive for the section containing the entry block is
2432 // handled separately by the function section.
2433 if (!MBB.sameSection(MBB: &MF->front())) {
2434 if (MAI.hasDotTypeDotSizeDirective()) {
2435 // Emit the size directive for the basic block section.
2436 const MCExpr *SizeExp = MCBinaryExpr::createSub(
2437 LHS: MCSymbolRefExpr::create(Symbol: MBB.getEndSymbol(), Ctx&: OutContext),
2438 RHS: MCSymbolRefExpr::create(Symbol: CurrentSectionBeginSym, Ctx&: OutContext),
2439 Ctx&: OutContext);
2440 OutStreamer->emitELFSize(Symbol: CurrentSectionBeginSym, Value: SizeExp);
2441 }
2442 assert(!MBBSectionRanges.contains(MBB.getSectionID()) &&
2443 "Overwrite section range");
2444 MBBSectionRanges[MBB.getSectionID()] =
2445 MBBSectionRange{.BeginLabel: CurrentSectionBeginSym, .EndLabel: MBB.getEndSymbol()};
2446 }
2447 }
2448 emitBasicBlockEnd(MBB);
2449
2450 if (CanDoExtraAnalysis) {
2451 // Skip empty blocks.
2452 if (MBB.empty())
2453 continue;
2454
2455 MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionMix",
2456 MBB.begin()->getDebugLoc(), &MBB);
2457
2458 // Generate instruction mix remark. First, sort counts in descending order
2459 // by count and name.
2460 SmallVector<std::pair<StringRef, unsigned>, 128> MnemonicVec;
2461 for (auto &KV : MnemonicCounts)
2462 MnemonicVec.emplace_back(Args&: KV.first, Args&: KV.second);
2463
2464 sort(C&: MnemonicVec, Comp: [](const std::pair<StringRef, unsigned> &A,
2465 const std::pair<StringRef, unsigned> &B) {
2466 if (A.second > B.second)
2467 return true;
2468 if (A.second == B.second)
2469 return StringRef(A.first) < StringRef(B.first);
2470 return false;
2471 });
2472 R << "BasicBlock: " << ore::NV("BasicBlock", MBB.getName()) << "\n";
2473 for (auto &KV : MnemonicVec) {
2474 auto Name = (Twine("INST_") + getToken(Source: KV.first.trim()).first).str();
2475 R << KV.first << ": " << ore::NV(Name, KV.second) << "\n";
2476 }
2477 ORE->emit(OptDiag&: R);
2478 }
2479 }
2480
2481 EmittedInsts += NumInstsInFunction;
2482 MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionCount",
2483 MF->getFunction().getSubprogram(),
2484 &MF->front());
2485 R << ore::NV("NumInstructions", NumInstsInFunction)
2486 << " instructions in function";
2487 ORE->emit(OptDiag&: R);
2488
2489 if (ORE->allowExtraAnalysis(PassName: "target-features")) {
2490 const Function &F = MF->getFunction();
2491 std::string FunctionName;
2492 raw_string_ostream OS(FunctionName);
2493 F.printAsOperand(O&: OS, /*PrintType=*/false);
2494
2495 MachineOptimizationRemarkAnalysis Remark(
2496 "target-features", "EnabledFeatures", F.getSubprogram(), &MF->front());
2497 Remark << "Enabled features for " << ore::NV("Function", FunctionName)
2498 << ": ";
2499 // The processor feature table is sorted by feature name.
2500 ListSeparator LS(",");
2501 for (const auto *Feature : MF->getSubtarget().getEnabledProcessorFeatures())
2502 Remark << LS << ore::NV("Feature", Feature->key());
2503 ORE->emit(OptDiag&: Remark);
2504 }
2505
2506 // If the function is empty and the object file uses .subsections_via_symbols,
2507 // then we need to emit *something* to the function body to prevent the
2508 // labels from collapsing together. Just emit a noop.
2509 // Similarly, don't emit empty functions on Windows either. It can lead to
2510 // duplicate entries (two functions with the same RVA) in the Guard CF Table
2511 // after linking, causing the kernel not to load the binary:
2512 // https://developercommunity.visualstudio.com/content/problem/45366/vc-linker-creates-invalid-dll-with-clang-cl.html
2513 // FIXME: Hide this behind some API in e.g. MCAsmInfo or MCTargetStreamer.
2514 const Triple &TT = M->getTargetTriple();
2515 if (!HasAnyRealCode && (MAI.hasSubsectionsViaSymbols() ||
2516 (TT.isOSWindows() && TT.isOSBinFormatCOFF()))) {
2517 MCInst Noop = MF->getSubtarget().getInstrInfo()->getNop();
2518
2519 // Targets can opt-out of emitting the noop here by leaving the opcode
2520 // unspecified.
2521 if (Noop.getOpcode()) {
2522 OutStreamer->AddComment(T: "avoids zero-length function");
2523 emitNops(N: 1);
2524 }
2525 }
2526
2527 // Switch to the original section in case basic block sections was used.
2528 OutStreamer->switchSection(Section: MF->getSection());
2529
2530 const Function &F = MF->getFunction();
2531 for (const auto &BB : F) {
2532 if (!BB.hasAddressTaken())
2533 continue;
2534 MCSymbol *Sym = GetBlockAddressSymbol(BB: &BB);
2535 if (Sym->isDefined())
2536 continue;
2537 OutStreamer->AddComment(T: "Address of block that was removed by CodeGen");
2538 OutStreamer->emitLabel(Symbol: Sym);
2539 }
2540
2541 // Emit target-specific gunk after the function body.
2542 emitFunctionBodyEnd();
2543
2544 // Tail-pad functions that want it.
2545 if (F.hasFnAttribute(Kind: "tail-pad-to-size")) {
2546 auto *FnEndSym = createTempSymbol(Name: "tail_pad_start");
2547 OutStreamer->emitLabel(Symbol: FnEndSym);
2548
2549 uint64_t PadToSize = F.getFnAttributeAsParsedInteger(Kind: "tail-pad-to-size");
2550 uint64_t FillValue =
2551 PadToSize ? F.getFnAttributeAsParsedInteger(Kind: "tail-pad-value") : 0;
2552
2553 // .fill ((PadToSize - FuncSize) & (PadToSize - FuncSize >= 0)) FillValue
2554 const MCExpr *FuncSize = MCBinaryExpr::createSub(
2555 LHS: MCSymbolRefExpr::create(Symbol: FnEndSym, Ctx&: OutContext),
2556 RHS: MCSymbolRefExpr::create(Symbol: CurrentFnSymForSize, Ctx&: OutContext), Ctx&: OutContext);
2557 const MCExpr *SizeConst = MCConstantExpr::create(Value: PadToSize, Ctx&: OutContext);
2558 const MCExpr *Zero = MCConstantExpr::create(Value: 0, Ctx&: OutContext);
2559 const MCExpr *SubExpr =
2560 MCBinaryExpr::createSub(LHS: SizeConst, RHS: FuncSize, Ctx&: OutContext);
2561 const MCExpr *Cmp = MCBinaryExpr::createGTE(LHS: SubExpr, RHS: Zero, Ctx&: OutContext);
2562 const MCExpr *FillExpr = MCBinaryExpr::createAnd(LHS: SubExpr, RHS: Cmp, Ctx&: OutContext);
2563 OutStreamer->emitFill(NumBytes: *FillExpr, FillValue);
2564 }
2565
2566 // Even though wasm supports .type and .size in general, function symbols
2567 // are automatically sized.
2568 bool EmitFunctionSize = MAI.hasDotTypeDotSizeDirective() && !TT.isWasm();
2569
2570 // SPIR-V supports label instructions only inside a block, not after the
2571 // function body.
2572 if (TT.getObjectFormat() != Triple::SPIRV &&
2573 (EmitFunctionSize || needFuncLabels(MF: *MF, Asm: *this) || CurrentFnEnd)) {
2574 // Create a symbol for the end of function, if not already pre-created
2575 // (e.g. for .prefalign directive).
2576 if (!CurrentFnEnd)
2577 CurrentFnEnd = createTempSymbol(Name: "func_end");
2578 OutStreamer->emitLabel(Symbol: CurrentFnEnd);
2579 }
2580
2581 // If the target wants a .size directive for the size of the function, emit
2582 // it.
2583 if (EmitFunctionSize) {
2584 // We can get the size as difference between the function label and the
2585 // temp label.
2586 const MCExpr *SizeExp = MCBinaryExpr::createSub(
2587 LHS: MCSymbolRefExpr::create(Symbol: CurrentFnEnd, Ctx&: OutContext),
2588 RHS: MCSymbolRefExpr::create(Symbol: CurrentFnSymForSize, Ctx&: OutContext), Ctx&: OutContext);
2589 OutStreamer->emitELFSize(Symbol: CurrentFnSym, Value: SizeExp);
2590 if (CurrentFnBeginLocal)
2591 OutStreamer->emitELFSize(Symbol: CurrentFnBeginLocal, Value: SizeExp);
2592 }
2593
2594 // Call endBasicBlockSection on the last block now, if it wasn't already
2595 // called.
2596 if (!MF->back().isEndSection()) {
2597 for (auto &Handler : Handlers)
2598 Handler->endBasicBlockSection(MBB: MF->back());
2599 for (auto &Handler : EHHandlers)
2600 Handler->endBasicBlockSection(MBB: MF->back());
2601 }
2602 for (auto &Handler : Handlers)
2603 Handler->markFunctionEnd();
2604 for (auto &Handler : EHHandlers)
2605 Handler->markFunctionEnd();
2606 // Update the end label of the entry block's section.
2607 MBBSectionRanges[MF->front().getSectionID()].EndLabel = CurrentFnEnd;
2608
2609 // Print out jump tables referenced by the function.
2610 emitJumpTableInfo();
2611
2612 // Emit post-function debug and/or EH information.
2613 for (auto &Handler : Handlers)
2614 Handler->endFunction(MF);
2615 for (auto &Handler : EHHandlers)
2616 Handler->endFunction(MF);
2617
2618 // Emit section containing BB address offsets and their metadata, when
2619 // BB labels are requested for this function. Skip empty functions.
2620 if (HasAnyRealCode) {
2621 if (MF->getTarget().Options.BBAddrMap)
2622 emitBBAddrMapSection(MF: *MF);
2623 else if (!PgoAnalysisMapFeatures.empty())
2624 MF->getContext().reportWarning(
2625 L: SMLoc(), Msg: "pgo-analysis-map is enabled for function " + MF->getName() +
2626 " but it does not have labels");
2627 }
2628
2629 // Emit sections containing instruction and function PCs.
2630 emitPCSections(MF: *MF);
2631
2632 // Emit section containing stack size metadata.
2633 emitStackSizeSection(MF: *MF);
2634
2635 // Emit section containing call graph metadata.
2636 emitCallGraphSection(MF: *MF, FuncCGInfo);
2637
2638 // Emit .su file containing function stack size information.
2639 emitStackUsage(MF: *MF);
2640
2641 emitPatchableFunctionEntries();
2642
2643 if (isVerbose())
2644 OutStreamer->getCommentOS() << "-- End function\n";
2645
2646 OutStreamer->addBlankLine();
2647}
2648
2649/// Compute the number of Global Variables that uses a Constant.
2650static unsigned getNumGlobalVariableUses(const Constant *C,
2651 bool &HasNonGlobalUsers) {
2652 if (!C) {
2653 HasNonGlobalUsers = true;
2654 return 0;
2655 }
2656
2657 if (isa<GlobalVariable>(Val: C))
2658 return 1;
2659
2660 unsigned NumUses = 0;
2661 for (const auto *CU : C->users())
2662 NumUses +=
2663 getNumGlobalVariableUses(C: dyn_cast<Constant>(Val: CU), HasNonGlobalUsers);
2664
2665 return NumUses;
2666}
2667
2668/// Only consider global GOT equivalents if at least one user is a
2669/// cstexpr inside an initializer of another global variables. Also, don't
2670/// handle cstexpr inside instructions. During global variable emission,
2671/// candidates are skipped and are emitted later in case at least one cstexpr
2672/// isn't replaced by a PC relative GOT entry access.
2673static bool isGOTEquivalentCandidate(const GlobalVariable *GV,
2674 unsigned &NumGOTEquivUsers,
2675 bool &HasNonGlobalUsers) {
2676 // Global GOT equivalents are unnamed private globals with a constant
2677 // pointer initializer to another global symbol. They must point to a
2678 // GlobalVariable or Function, i.e., as GlobalValue.
2679 if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() ||
2680 !GV->isConstant() || !GV->isDiscardableIfUnused() ||
2681 !isa<GlobalValue>(Val: GV->getOperand(i_nocapture: 0)))
2682 return false;
2683
2684 // To be a got equivalent, at least one of its users need to be a constant
2685 // expression used by another global variable.
2686 for (const auto *U : GV->users())
2687 NumGOTEquivUsers +=
2688 getNumGlobalVariableUses(C: dyn_cast<Constant>(Val: U), HasNonGlobalUsers);
2689
2690 return NumGOTEquivUsers > 0;
2691}
2692
2693/// Unnamed constant global variables solely contaning a pointer to
2694/// another globals variable is equivalent to a GOT table entry; it contains the
2695/// the address of another symbol. Optimize it and replace accesses to these
2696/// "GOT equivalents" by using the GOT entry for the final global instead.
2697/// Compute GOT equivalent candidates among all global variables to avoid
2698/// emitting them if possible later on, after it use is replaced by a GOT entry
2699/// access.
2700void AsmPrinter::computeGlobalGOTEquivs(Module &M) {
2701 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
2702 return;
2703
2704 for (const auto &G : M.globals()) {
2705 unsigned NumGOTEquivUsers = 0;
2706 bool HasNonGlobalUsers = false;
2707 if (!isGOTEquivalentCandidate(GV: &G, NumGOTEquivUsers, HasNonGlobalUsers))
2708 continue;
2709 // If non-global variables use it, we still need to emit it.
2710 // Add 1 here, then emit it in `emitGlobalGOTEquivs`.
2711 if (HasNonGlobalUsers)
2712 NumGOTEquivUsers += 1;
2713 const MCSymbol *GOTEquivSym = getSymbol(GV: &G);
2714 GlobalGOTEquivs[GOTEquivSym] = std::make_pair(x: &G, y&: NumGOTEquivUsers);
2715 }
2716}
2717
2718/// Constant expressions using GOT equivalent globals may not be eligible
2719/// for PC relative GOT entry conversion, in such cases we need to emit such
2720/// globals we previously omitted in EmitGlobalVariable.
2721void AsmPrinter::emitGlobalGOTEquivs() {
2722 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
2723 return;
2724
2725 SmallVector<const GlobalVariable *, 8> FailedCandidates;
2726 for (auto &I : GlobalGOTEquivs) {
2727 const GlobalVariable *GV = I.second.first;
2728 unsigned Cnt = I.second.second;
2729 if (Cnt)
2730 FailedCandidates.push_back(Elt: GV);
2731 }
2732 GlobalGOTEquivs.clear();
2733
2734 for (const auto *GV : FailedCandidates)
2735 emitGlobalVariable(GV);
2736}
2737
2738void AsmPrinter::emitGlobalAlias(const Module &M, const GlobalAlias &GA) {
2739 MCSymbol *Name = getSymbol(GV: &GA);
2740 const GlobalObject *BaseObject = GA.getAliaseeObject();
2741
2742 bool IsFunction = GA.getValueType()->isFunctionTy();
2743 // Treat bitcasts of functions as functions also. This is important at least
2744 // on WebAssembly where object and function addresses can't alias each other.
2745 if (!IsFunction)
2746 IsFunction = isa_and_nonnull<Function>(Val: BaseObject);
2747
2748 // AIX's assembly directive `.set` is not usable for aliasing purpose,
2749 // so AIX has to use the extra-label-at-definition strategy. At this
2750 // point, all the extra label is emitted, we just have to emit linkage for
2751 // those labels.
2752 if (M.getTargetTriple().isOSBinFormatXCOFF()) {
2753 // Linkage for alias of global variable has been emitted.
2754 if (isa_and_nonnull<GlobalVariable>(Val: BaseObject))
2755 return;
2756
2757 emitLinkage(GV: &GA, GVSym: Name);
2758 // If it's a function, also emit linkage for aliases of function entry
2759 // point.
2760 if (IsFunction)
2761 emitLinkage(GV: &GA,
2762 GVSym: getObjFileLowering().getFunctionEntryPointSymbol(Func: &GA, TM));
2763 return;
2764 }
2765
2766 if (GA.hasExternalLinkage() || !MAI.getWeakRefDirective())
2767 OutStreamer->emitSymbolAttribute(Symbol: Name, Attribute: MCSA_Global);
2768 else if (GA.hasWeakLinkage() || GA.hasLinkOnceLinkage())
2769 OutStreamer->emitSymbolAttribute(Symbol: Name, Attribute: MCSA_WeakReference);
2770 else
2771 assert(GA.hasLocalLinkage() && "Invalid alias linkage");
2772
2773 // Set the symbol type to function if the alias has a function type.
2774 // This affects codegen when the aliasee is not a function.
2775 if (IsFunction) {
2776 OutStreamer->emitSymbolAttribute(Symbol: Name, Attribute: MCSA_ELF_TypeFunction);
2777 if (M.getTargetTriple().isOSBinFormatCOFF()) {
2778 OutStreamer->beginCOFFSymbolDef(Symbol: Name);
2779 OutStreamer->emitCOFFSymbolStorageClass(
2780 StorageClass: GA.hasLocalLinkage() ? COFF::IMAGE_SYM_CLASS_STATIC
2781 : COFF::IMAGE_SYM_CLASS_EXTERNAL);
2782 OutStreamer->emitCOFFSymbolType(Type: COFF::IMAGE_SYM_DTYPE_FUNCTION
2783 << COFF::SCT_COMPLEX_TYPE_SHIFT);
2784 OutStreamer->endCOFFSymbolDef();
2785 }
2786 }
2787
2788 emitVisibility(Sym: Name, Visibility: GA.getVisibility());
2789
2790 const MCExpr *Expr = lowerConstant(CV: GA.getAliasee());
2791
2792 if (MAI.isMachO() && isa<MCBinaryExpr>(Val: Expr))
2793 OutStreamer->emitSymbolAttribute(Symbol: Name, Attribute: MCSA_AltEntry);
2794
2795 // Emit the directives as assignments aka .set:
2796 OutStreamer->emitAssignment(Symbol: Name, Value: Expr);
2797 MCSymbol *LocalAlias = getSymbolPreferLocal(GV: GA);
2798 if (LocalAlias != Name)
2799 OutStreamer->emitAssignment(Symbol: LocalAlias, Value: Expr);
2800
2801 // If the aliasee does not correspond to a symbol in the output, i.e. the
2802 // alias is not of an object or the aliased object is private, then set the
2803 // size of the alias symbol from the type of the alias. We don't do this in
2804 // other situations as the alias and aliasee having differing types but same
2805 // size may be intentional.
2806 if (MAI.hasDotTypeDotSizeDirective() && GA.getValueType()->isSized() &&
2807 (!BaseObject || BaseObject->hasPrivateLinkage())) {
2808 const DataLayout &DL = M.getDataLayout();
2809 uint64_t Size = DL.getTypeAllocSize(Ty: GA.getValueType());
2810 OutStreamer->emitELFSize(Symbol: Name, Value: MCConstantExpr::create(Value: Size, Ctx&: OutContext));
2811 }
2812}
2813
2814void AsmPrinter::emitGlobalIFunc(Module &M, const GlobalIFunc &GI) {
2815 auto EmitLinkage = [&](MCSymbol *Sym) {
2816 if (GI.hasExternalLinkage() || !MAI.getWeakRefDirective())
2817 OutStreamer->emitSymbolAttribute(Symbol: Sym, Attribute: MCSA_Global);
2818 else if (GI.hasWeakLinkage() || GI.hasLinkOnceLinkage())
2819 OutStreamer->emitSymbolAttribute(Symbol: Sym, Attribute: MCSA_WeakReference);
2820 else
2821 assert(GI.hasLocalLinkage() && "Invalid ifunc linkage");
2822 };
2823
2824 if (M.getTargetTriple().isOSBinFormatELF()) {
2825 MCSymbol *Name = getSymbol(GV: &GI);
2826 EmitLinkage(Name);
2827 OutStreamer->emitSymbolAttribute(Symbol: Name, Attribute: MCSA_ELF_TypeIndFunction);
2828 emitVisibility(Sym: Name, Visibility: GI.getVisibility());
2829
2830 // Emit the directives as assignments aka .set:
2831 const MCExpr *Expr = lowerConstant(CV: GI.getResolver());
2832 OutStreamer->emitAssignment(Symbol: Name, Value: Expr);
2833 MCSymbol *LocalAlias = getSymbolPreferLocal(GV: GI);
2834 if (LocalAlias != Name)
2835 OutStreamer->emitAssignment(Symbol: LocalAlias, Value: Expr);
2836
2837 return;
2838 }
2839
2840 if (!M.getTargetTriple().isOSBinFormatMachO() || !getIFuncMCSubtargetInfo())
2841 reportFatalUsageError(reason: "IFuncs are not supported on this platform");
2842
2843 // On Darwin platforms, emit a manually-constructed .symbol_resolver that
2844 // implements the symbol resolution duties of the IFunc.
2845 //
2846 // Normally, this would be handled by linker magic, but unfortunately there
2847 // are a few limitations in ld64 and ld-prime's implementation of
2848 // .symbol_resolver that mean we can't always use them:
2849 //
2850 // * resolvers cannot be the target of an alias
2851 // * resolvers cannot have private linkage
2852 // * resolvers cannot have linkonce linkage
2853 // * resolvers cannot appear in executables
2854 // * resolvers cannot appear in bundles
2855 //
2856 // This works around that by emitting a close approximation of what the
2857 // linker would have done.
2858
2859 MCSymbol *LazyPointer =
2860 GetExternalSymbolSymbol(Sym: GI.getName() + ".lazy_pointer");
2861 MCSymbol *StubHelper = GetExternalSymbolSymbol(Sym: GI.getName() + ".stub_helper");
2862
2863 OutStreamer->switchSection(Section: OutContext.getObjectFileInfo()->getDataSection());
2864
2865 const DataLayout &DL = M.getDataLayout();
2866 emitAlignment(Alignment: Align(DL.getPointerSize()));
2867 OutStreamer->emitLabel(Symbol: LazyPointer);
2868 emitVisibility(Sym: LazyPointer, Visibility: GI.getVisibility());
2869 OutStreamer->emitValue(Value: MCSymbolRefExpr::create(Symbol: StubHelper, Ctx&: OutContext), Size: 8);
2870
2871 OutStreamer->switchSection(Section: OutContext.getObjectFileInfo()->getTextSection());
2872
2873 const TargetSubtargetInfo *STI =
2874 TM.getSubtargetImpl(*GI.getResolverFunction());
2875 const TargetLowering *TLI = STI->getTargetLowering();
2876 Align TextAlign(TLI->getMinFunctionAlignment());
2877
2878 MCSymbol *Stub = getSymbol(GV: &GI);
2879 EmitLinkage(Stub);
2880 OutStreamer->emitCodeAlignment(Alignment: TextAlign, STI: *getIFuncMCSubtargetInfo());
2881 OutStreamer->emitLabel(Symbol: Stub);
2882 emitVisibility(Sym: Stub, Visibility: GI.getVisibility());
2883 emitMachOIFuncStubBody(M, GI, LazyPointer);
2884
2885 OutStreamer->emitCodeAlignment(Alignment: TextAlign, STI: *getIFuncMCSubtargetInfo());
2886 OutStreamer->emitLabel(Symbol: StubHelper);
2887 emitVisibility(Sym: StubHelper, Visibility: GI.getVisibility());
2888 emitMachOIFuncStubHelperBody(M, GI, LazyPointer);
2889}
2890
2891void AsmPrinter::emitRemarksSection(remarks::RemarkStreamer &RS) {
2892 if (!RS.wantsSection())
2893 return;
2894 if (!RS.getFilename())
2895 return;
2896
2897 MCSection *RemarksSection =
2898 OutContext.getObjectFileInfo()->getRemarksSection();
2899 if (!RemarksSection && RS.needsSection()) {
2900 OutContext.reportWarning(L: SMLoc(), Msg: "Current object file format does not "
2901 "support remarks sections.");
2902 }
2903 if (!RemarksSection)
2904 return;
2905
2906 SmallString<128> Filename = *RS.getFilename();
2907 assert(!Filename.empty() && "The filename can't be empty.");
2908 assert((Filename == "-" || sys::path::is_absolute(Filename)) &&
2909 "The remarks filename must be absolute.");
2910
2911 std::string Buf;
2912 raw_string_ostream OS(Buf);
2913
2914 remarks::RemarkSerializer &RemarkSerializer = RS.getSerializer();
2915 std::unique_ptr<remarks::MetaSerializer> MetaSerializer =
2916 RemarkSerializer.metaSerializer(OS, ExternalFilename: Filename);
2917 MetaSerializer->emit();
2918
2919 // Switch to the remarks section.
2920 OutStreamer->switchSection(Section: RemarksSection);
2921 OutStreamer->emitBinaryData(Data: Buf);
2922}
2923
2924static uint64_t globalSize(const llvm::GlobalVariable &G) {
2925 const Constant *Initializer = G.getInitializer();
2926 return G.getDataLayout().getTypeAllocSize(Ty: Initializer->getType());
2927}
2928
2929static bool shouldTagGlobal(const llvm::GlobalVariable &G) {
2930 // We used to do this in clang, but there are optimization passes that turn
2931 // non-constant globals into constants. So now, clang only tells us whether
2932 // it would *like* a global to be tagged, but we still make the decision here.
2933 //
2934 // For now, don't instrument constant data, as it'll be in .rodata anyway. It
2935 // may be worth instrumenting these in future to stop them from being used as
2936 // gadgets.
2937 if (G.getName().starts_with(Prefix: "llvm.") || G.isThreadLocal() || G.isConstant())
2938 return false;
2939
2940 // Globals can be placed implicitly or explicitly in sections. There's two
2941 // different types of globals that meet this criteria that cause problems:
2942 // 1. Function pointers that are going into various init arrays (either
2943 // explicitly through `__attribute__((section(<foo>)))` or implicitly
2944 // through `__attribute__((constructor)))`, such as ".(pre)init(_array)",
2945 // ".fini(_array)", ".ctors", and ".dtors". These function pointers end up
2946 // overaligned and overpadded, making iterating over them problematic, and
2947 // each function pointer is individually tagged (so the iteration over
2948 // them causes SIGSEGV/MTE[AS]ERR).
2949 // 2. Global variables put into an explicit section, where the section's name
2950 // is a valid C-style identifier. The linker emits a `__start_<name>` and
2951 // `__stop_<name>` symbol for the section, so that you can iterate over
2952 // globals within this section. Unfortunately, again, these globals would
2953 // be tagged and so iteration causes SIGSEGV/MTE[AS]ERR.
2954 //
2955 // To mitigate both these cases, and because specifying a section is rare
2956 // outside of these two cases, disable MTE protection for globals in any
2957 // section.
2958 if (G.hasSection())
2959 return false;
2960
2961 return globalSize(G) > 0;
2962}
2963
2964static void tagGlobalDefinition(Module &M, GlobalVariable *G) {
2965 uint64_t SizeInBytes = globalSize(G: *G);
2966
2967 uint64_t NewSize = alignTo(Value: SizeInBytes, Align: 16);
2968 if (SizeInBytes != NewSize) {
2969 // Pad the initializer out to the next multiple of 16 bytes.
2970 llvm::SmallVector<uint8_t> Init(NewSize - SizeInBytes, 0);
2971 Constant *Padding = ConstantDataArray::get(Context&: M.getContext(), Elts&: Init);
2972 Constant *Initializer = G->getInitializer();
2973 Initializer = ConstantStruct::getAnon(V: {Initializer, Padding});
2974 auto *NewGV = new GlobalVariable(
2975 M, Initializer->getType(), G->isConstant(), G->getLinkage(),
2976 Initializer, "", G, G->getThreadLocalMode(), G->getAddressSpace());
2977 NewGV->copyAttributesFrom(Src: G);
2978 NewGV->setComdat(G->getComdat());
2979 NewGV->copyMetadata(Src: G, Offset: 0);
2980
2981 NewGV->takeName(V: G);
2982 G->replaceAllUsesWith(V: NewGV);
2983 G->eraseFromParent();
2984 G = NewGV;
2985 }
2986
2987 if (G->getAlign().valueOrOne() < 16)
2988 G->setAlignment(Align(16));
2989
2990 // Ensure that tagged globals don't get merged by ICF - as they should have
2991 // different tags at runtime.
2992 G->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
2993}
2994
2995static void removeMemtagFromGlobal(GlobalVariable &G) {
2996 auto Meta = G.getSanitizerMetadata();
2997 Meta.Memtag = false;
2998 G.setSanitizerMetadata(Meta);
2999}
3000
3001bool AsmPrinter::doFinalization(Module &M) {
3002 // Set the MachineFunction to nullptr so that we can catch attempted
3003 // accesses to MF specific features at the module level and so that
3004 // we can conditionalize accesses based on whether or not it is nullptr.
3005 MF = nullptr;
3006 const Triple &Target = M.getTargetTriple();
3007
3008 std::vector<GlobalVariable *> GlobalsToTag;
3009 for (GlobalVariable &G : M.globals()) {
3010 if (G.isDeclaration() || !G.isTagged())
3011 continue;
3012 if (!shouldTagGlobal(G)) {
3013 assert(G.hasSanitizerMetadata()); // because isTagged.
3014 removeMemtagFromGlobal(G);
3015 assert(!G.isTagged());
3016 continue;
3017 }
3018 GlobalsToTag.push_back(x: &G);
3019 }
3020 for (GlobalVariable *G : GlobalsToTag)
3021 tagGlobalDefinition(M, G);
3022
3023 // Gather all GOT equivalent globals in the module. We really need two
3024 // passes over the globals: one to compute and another to avoid its emission
3025 // in EmitGlobalVariable, otherwise we would not be able to handle cases
3026 // where the got equivalent shows up before its use.
3027 computeGlobalGOTEquivs(M);
3028
3029 // Emit global variables.
3030 for (const auto &G : M.globals())
3031 emitGlobalVariable(GV: &G);
3032
3033 // Emit remaining GOT equivalent globals.
3034 emitGlobalGOTEquivs();
3035
3036 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
3037
3038 // Emit linkage(XCOFF) and visibility info for declarations
3039 for (const Function &F : M) {
3040 if (!F.isDeclarationForLinker())
3041 continue;
3042
3043 MCSymbol *Name = getSymbol(GV: &F);
3044 // Function getSymbol gives us the function descriptor symbol for XCOFF.
3045
3046 if (!Target.isOSBinFormatXCOFF()) {
3047 GlobalValue::VisibilityTypes V = F.getVisibility();
3048 if (V == GlobalValue::DefaultVisibility)
3049 continue;
3050
3051 emitVisibility(Sym: Name, Visibility: V, IsDefinition: false);
3052 continue;
3053 }
3054
3055 if (F.isIntrinsic())
3056 continue;
3057
3058 // Handle the XCOFF case.
3059 // Variable `Name` is the function descriptor symbol (see above). Get the
3060 // function entry point symbol.
3061 MCSymbol *FnEntryPointSym = TLOF.getFunctionEntryPointSymbol(Func: &F, TM);
3062 // Emit linkage for the function entry point.
3063 emitLinkage(GV: &F, GVSym: FnEntryPointSym);
3064
3065 // If a function's address is taken, which means it may be called via a
3066 // function pointer, we need the function descriptor for it.
3067 if (F.hasAddressTaken())
3068 emitLinkage(GV: &F, GVSym: Name);
3069 }
3070
3071 // Emit the remarks section contents.
3072 // FIXME: Figure out when is the safest time to emit this section. It should
3073 // not come after debug info.
3074 if (remarks::RemarkStreamer *RS = M.getContext().getMainRemarkStreamer())
3075 emitRemarksSection(RS&: *RS);
3076
3077 TLOF.emitModuleMetadata(Streamer&: *OutStreamer, M);
3078
3079 // Emit raw section data from llvm.raw.sections metadata. Each operand is
3080 // a tuple of {section_name, alignment, flags, data}.
3081 if (const NamedMDNode *RawSections =
3082 M.getNamedMetadata(Name: "llvm.raw.sections")) {
3083 for (const MDNode *Op : RawSections->operands()) {
3084 auto *SectionName = cast<MDString>(Val: Op->getOperand(I: 0));
3085 auto *AlignCI = mdconst::extract<ConstantInt>(MD: Op->getOperand(I: 1));
3086 auto *Data = cast<MDString>(Val: Op->getOperand(I: 3));
3087
3088 MCSection *Section = TLOF.getNamedSection(Name: SectionName->getString(),
3089 Kind: SectionKind::getMetadata());
3090 if (!Section) {
3091 M.getContext().emitError(ErrorStr: "llvm.raw.sections entry '" +
3092 SectionName->getString() +
3093 "' is not supported on this target");
3094 continue;
3095 }
3096 OutStreamer->pushSection();
3097 OutStreamer->switchSection(Section);
3098 OutStreamer->emitValueToAlignment(Alignment: Align(AlignCI->getZExtValue()));
3099 OutStreamer->emitBytes(Data: Data->getString());
3100 OutStreamer->popSection();
3101 }
3102 }
3103
3104 if (Target.isOSBinFormatELF()) {
3105 MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
3106
3107 // Output stubs for external and common global variables.
3108 MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
3109 if (!Stubs.empty()) {
3110 OutStreamer->switchSection(Section: TLOF.getDataSection());
3111 const DataLayout &DL = M.getDataLayout();
3112
3113 emitAlignment(Alignment: Align(DL.getPointerSize()));
3114 for (const auto &Stub : Stubs) {
3115 OutStreamer->emitLabel(Symbol: Stub.first);
3116 OutStreamer->emitSymbolValue(Sym: Stub.second.getPointer(),
3117 Size: DL.getPointerSize());
3118 }
3119 }
3120 }
3121
3122 if (Target.isOSBinFormatCOFF()) {
3123 MachineModuleInfoCOFF &MMICOFF =
3124 MMI->getObjFileInfo<MachineModuleInfoCOFF>();
3125
3126 // Output stubs for external and common global variables.
3127 MachineModuleInfoCOFF::SymbolListTy Stubs = MMICOFF.GetGVStubList();
3128 if (!Stubs.empty()) {
3129 const DataLayout &DL = M.getDataLayout();
3130
3131 for (const auto &Stub : Stubs) {
3132 SmallString<256> SectionName = StringRef(".rdata$");
3133 SectionName += Stub.first->getName();
3134 OutStreamer->switchSection(Section: OutContext.getCOFFSection(
3135 Section: SectionName,
3136 Characteristics: COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ |
3137 COFF::IMAGE_SCN_LNK_COMDAT,
3138 COMDATSymName: Stub.first->getName(), Selection: COFF::IMAGE_COMDAT_SELECT_ANY));
3139 emitAlignment(Alignment: Align(DL.getPointerSize()));
3140 OutStreamer->emitSymbolAttribute(Symbol: Stub.first, Attribute: MCSA_Global);
3141 OutStreamer->emitLabel(Symbol: Stub.first);
3142 OutStreamer->emitSymbolValue(Sym: Stub.second.getPointer(),
3143 Size: DL.getPointerSize());
3144 }
3145 }
3146 }
3147
3148 // This needs to happen before emitting debug information since that can end
3149 // arbitrary sections.
3150 if (auto *TS = OutStreamer->getTargetStreamer())
3151 TS->emitConstantPools();
3152
3153 // Emit Stack maps before any debug info. Mach-O requires that no data or
3154 // text sections come after debug info has been emitted. This matters for
3155 // stack maps as they are arbitrary data, and may even have a custom format
3156 // through user plugins.
3157 EmitStackMaps(M);
3158
3159 // Print aliases in topological order, that is, for each alias a = b,
3160 // b must be printed before a.
3161 // This is because on some targets (e.g. PowerPC) linker expects aliases in
3162 // such an order to generate correct TOC information.
3163 SmallVector<const GlobalAlias *, 16> AliasStack;
3164 SmallPtrSet<const GlobalAlias *, 16> AliasVisited;
3165 for (const auto &Alias : M.aliases()) {
3166 if (Alias.hasAvailableExternallyLinkage())
3167 continue;
3168 for (const GlobalAlias *Cur = &Alias; Cur;
3169 Cur = dyn_cast<GlobalAlias>(Val: Cur->getAliasee())) {
3170 if (!AliasVisited.insert(Ptr: Cur).second)
3171 break;
3172 AliasStack.push_back(Elt: Cur);
3173 }
3174 for (const GlobalAlias *AncestorAlias : llvm::reverse(C&: AliasStack))
3175 emitGlobalAlias(M, GA: *AncestorAlias);
3176 AliasStack.clear();
3177 }
3178
3179 // IFuncs must come before deubginfo in case the backend decides to emit them
3180 // as actual functions, since on Mach-O targets, we cannot create regular
3181 // sections after DWARF.
3182 for (const auto &IFunc : M.ifuncs())
3183 emitGlobalIFunc(M, GI: IFunc);
3184 if (M.getTargetTriple().isOSBinFormatXCOFF() && hasDebugInfo()) {
3185 // Emit section end. This is used to tell the debug line section where the
3186 // end is for a text section if we don't use .loc to represent the debug
3187 // line.
3188 auto *Sec = OutContext.getObjectFileInfo()->getTextSection();
3189 OutStreamer->switchSectionNoPrint(Section: Sec);
3190 MCSymbol *Sym = Sec->getEndSymbol(Ctx&: OutContext);
3191 OutStreamer->emitLabel(Symbol: Sym);
3192 }
3193
3194 // Finalize debug and EH information.
3195 for (auto &Handler : Handlers)
3196 Handler->endModule();
3197 for (auto &Handler : EHHandlers)
3198 Handler->endModule();
3199
3200 // This deletes all the ephemeral handlers that AsmPrinter added, while
3201 // keeping all the user-added handlers alive until the AsmPrinter is
3202 // destroyed.
3203 EHHandlers.clear();
3204 Handlers.erase(CS: Handlers.begin() + NumUserHandlers, CE: Handlers.end());
3205 DD = nullptr;
3206
3207 // If the target wants to know about weak references, print them all.
3208 if (MAI.getWeakRefDirective()) {
3209 // FIXME: This is not lazy, it would be nice to only print weak references
3210 // to stuff that is actually used. Note that doing so would require targets
3211 // to notice uses in operands (due to constant exprs etc). This should
3212 // happen with the MC stuff eventually.
3213
3214 // Print out module-level global objects here.
3215 for (const auto &GO : M.global_objects()) {
3216 if (!GO.hasExternalWeakLinkage())
3217 continue;
3218 OutStreamer->emitSymbolAttribute(Symbol: getSymbol(GV: &GO), Attribute: MCSA_WeakReference);
3219 }
3220 if (shouldEmitWeakSwiftAsyncExtendedFramePointerFlags()) {
3221 auto SymbolName = "swift_async_extendedFramePointerFlags";
3222 auto Global = M.getGlobalVariable(Name: SymbolName);
3223 if (!Global) {
3224 auto PtrTy = PointerType::getUnqual(C&: M.getContext());
3225 Global = new GlobalVariable(M, PtrTy, false,
3226 GlobalValue::ExternalWeakLinkage, nullptr,
3227 SymbolName);
3228 OutStreamer->emitSymbolAttribute(Symbol: getSymbol(GV: Global), Attribute: MCSA_WeakReference);
3229 }
3230 }
3231 }
3232
3233 FinishGCAssembly(M);
3234
3235 // Emit llvm.ident metadata in an '.ident' directive.
3236 emitModuleIdents(M);
3237
3238 // Emit bytes for llvm.commandline metadata.
3239 // The command line metadata is emitted earlier on XCOFF.
3240 if (!Target.isOSBinFormatXCOFF())
3241 emitModuleCommandLines(M);
3242
3243 // Emit .note.GNU-split-stack and .note.GNU-no-split-stack sections if
3244 // split-stack is used.
3245 if (M.getTargetTriple().isOSBinFormatELF() && HasSplitStack) {
3246 OutStreamer->switchSection(Section: OutContext.getELFSection(Section: ".note.GNU-split-stack",
3247 Type: ELF::SHT_PROGBITS, Flags: 0));
3248 if (HasNoSplitStack)
3249 OutStreamer->switchSection(Section: OutContext.getELFSection(
3250 Section: ".note.GNU-no-split-stack", Type: ELF::SHT_PROGBITS, Flags: 0));
3251 }
3252
3253 // If we don't have any trampolines, then we don't require stack memory
3254 // to be executable. Some targets have a directive to declare this.
3255 Function *InitTrampolineIntrinsic = M.getFunction(Name: "llvm.init.trampoline");
3256 bool HasTrampolineUses =
3257 InitTrampolineIntrinsic && !InitTrampolineIntrinsic->use_empty();
3258 MCSection *S = MAI.getStackSection(Ctx&: OutContext, /*Exec=*/HasTrampolineUses);
3259 if (S)
3260 OutStreamer->switchSection(Section: S);
3261
3262 if (TM.Options.EmitAddrsig && MAI.hasAddrsigDirective()) {
3263 // Emit address-significance attributes for all globals.
3264 OutStreamer->emitAddrsig();
3265 for (const GlobalValue &GV : M.global_values()) {
3266 if (!GV.use_empty() && !GV.isThreadLocal() &&
3267 !GV.hasDLLImportStorageClass() &&
3268 !GV.getName().starts_with(Prefix: "llvm.") &&
3269 !GV.hasAtLeastLocalUnnamedAddr())
3270 OutStreamer->emitAddrsigSym(Sym: getSymbol(GV: &GV));
3271 }
3272 }
3273
3274 // Emit symbol partition specifications (ELF only).
3275 if (Target.isOSBinFormatELF()) {
3276 unsigned UniqueID = 0;
3277 for (const GlobalValue &GV : M.global_values()) {
3278 if (!GV.hasPartition() || GV.isDeclarationForLinker() ||
3279 GV.getVisibility() != GlobalValue::DefaultVisibility)
3280 continue;
3281
3282 OutStreamer->switchSection(
3283 Section: OutContext.getELFSection(Section: ".llvm_sympart", Type: ELF::SHT_LLVM_SYMPART, Flags: 0, EntrySize: 0,
3284 Group: "", IsComdat: false, UniqueID: ++UniqueID, LinkedToSym: nullptr));
3285 OutStreamer->emitBytes(Data: GV.getPartition());
3286 OutStreamer->emitZeros(NumBytes: 1);
3287 OutStreamer->emitValue(
3288 Value: MCSymbolRefExpr::create(Symbol: getSymbol(GV: &GV), Ctx&: OutContext),
3289 Size: MAI.getCodePointerSize());
3290 }
3291 }
3292
3293 // Allow the target to emit any magic that it wants at the end of the file,
3294 // after everything else has gone out.
3295 emitEndOfAsmFile(M);
3296
3297 MMI = nullptr;
3298 AddrLabelSymbols = nullptr;
3299
3300 OutStreamer->finish();
3301 OutStreamer->reset();
3302 OwnedMLI.reset();
3303 OwnedMDT.reset();
3304
3305 return false;
3306}
3307
3308MCSymbol *AsmPrinter::getMBBExceptionSym(const MachineBasicBlock &MBB) {
3309 auto Res = MBBSectionExceptionSyms.try_emplace(Key: MBB.getSectionID());
3310 if (Res.second)
3311 Res.first->second = createTempSymbol(Name: "exception");
3312 return Res.first->second;
3313}
3314
3315MCSymbol *AsmPrinter::createCallsiteEndSymbol(const MachineBasicBlock &MBB) {
3316 MCContext &Ctx = MF->getContext();
3317 MCSymbol *Sym = Ctx.createTempSymbol(Name: "BB" + Twine(MF->getFunctionNumber()) +
3318 "_" + Twine(MBB.getNumber()) + "_CS");
3319 CurrentFnCallsiteEndSymbols[&MBB].push_back(Elt: Sym);
3320 return Sym;
3321}
3322
3323void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
3324 this->MF = &MF;
3325 const Function &F = MF.getFunction();
3326
3327 // Record that there are split-stack functions, so we will emit a special
3328 // section to tell the linker.
3329 if (MF.shouldSplitStack()) {
3330 HasSplitStack = true;
3331
3332 if (!MF.getFrameInfo().needsSplitStackProlog())
3333 HasNoSplitStack = true;
3334 } else
3335 HasNoSplitStack = true;
3336
3337 // Get the function symbol.
3338 if (!MAI.isAIX()) {
3339 CurrentFnSym = getSymbol(GV: &MF.getFunction());
3340 } else {
3341 assert(TM.getTargetTriple().isOSAIX() &&
3342 "Only AIX uses the function descriptor hooks.");
3343 // AIX is unique here in that the name of the symbol emitted for the
3344 // function body does not have the same name as the source function's
3345 // C-linkage name.
3346 assert(CurrentFnDescSym && "The function descriptor symbol needs to be"
3347 " initalized first.");
3348
3349 // Get the function entry point symbol.
3350 CurrentFnSym = getObjFileLowering().getFunctionEntryPointSymbol(Func: &F, TM);
3351 }
3352
3353 CurrentFnSymForSize = CurrentFnSym;
3354 CurrentFnBegin = nullptr;
3355 CurrentFnBeginLocal = nullptr;
3356 CurrentFnEnd = nullptr;
3357 CurrentSectionBeginSym = nullptr;
3358 CurrentFnCallsiteEndSymbols.clear();
3359 MBBSectionRanges.clear();
3360 MBBSectionExceptionSyms.clear();
3361 bool NeedsLocalForSize = MAI.needsLocalForSize();
3362 if (F.hasFnAttribute(Kind: "patchable-function-entry") ||
3363 F.hasFnAttribute(Kind: "tail-pad-to-size") ||
3364 F.hasFnAttribute(Kind: "function-instrument") ||
3365 F.hasFnAttribute(Kind: "xray-instruction-threshold") ||
3366 needFuncLabels(MF, Asm: *this) || NeedsLocalForSize ||
3367 MF.getTarget().Options.EmitStackSizeSection ||
3368 MF.getTarget().Options.EmitCallGraphSection ||
3369 MF.getTarget().Options.BBAddrMap) {
3370 CurrentFnBegin = createTempSymbol(Name: "func_begin");
3371 if (NeedsLocalForSize)
3372 CurrentFnSymForSize = CurrentFnBegin;
3373 }
3374
3375 ORE = GetORE(MF);
3376}
3377
3378namespace {
3379
3380// Keep track the alignment, constpool entries per Section.
3381 struct SectionCPs {
3382 MCSection *S;
3383 Align Alignment;
3384 SmallVector<unsigned, 4> CPEs;
3385
3386 SectionCPs(MCSection *s, Align a) : S(s), Alignment(a) {}
3387 };
3388
3389} // end anonymous namespace
3390
3391StringRef AsmPrinter::getConstantSectionSuffix(const Constant *C) const {
3392 if (TM.Options.EnableStaticDataPartitioning && C && SDPI && PSI)
3393 return SDPI->getConstantSectionPrefix(C, PSI);
3394
3395 return "";
3396}
3397
3398/// EmitConstantPool - Print to the current output stream assembly
3399/// representations of the constants in the constant pool MCP. This is
3400/// used to print out constants which have been "spilled to memory" by
3401/// the code generator.
3402void AsmPrinter::emitConstantPool() {
3403 const MachineConstantPool *MCP = MF->getConstantPool();
3404 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
3405 if (CP.empty()) return;
3406
3407 // Calculate sections for constant pool entries. We collect entries to go into
3408 // the same section together to reduce amount of section switch statements.
3409 SmallVector<SectionCPs, 4> CPSections;
3410 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
3411 const MachineConstantPoolEntry &CPE = CP[i];
3412 Align Alignment = CPE.getAlign();
3413
3414 SectionKind Kind = CPE.getSectionKind(DL: &getDataLayout());
3415
3416 const Constant *C = nullptr;
3417 if (!CPE.isMachineConstantPoolEntry())
3418 C = CPE.Val.ConstVal;
3419
3420 MCSection *S = getObjFileLowering().getSectionForConstant(
3421 DL: getDataLayout(), Kind, C, Alignment, F: &MF->getFunction(),
3422 SectionSuffix: getConstantSectionSuffix(C));
3423
3424 // The number of sections are small, just do a linear search from the
3425 // last section to the first.
3426 bool Found = false;
3427 unsigned SecIdx = CPSections.size();
3428 while (SecIdx != 0) {
3429 if (CPSections[--SecIdx].S == S) {
3430 Found = true;
3431 break;
3432 }
3433 }
3434 if (!Found) {
3435 SecIdx = CPSections.size();
3436 CPSections.push_back(Elt: SectionCPs(S, Alignment));
3437 }
3438
3439 if (Alignment > CPSections[SecIdx].Alignment)
3440 CPSections[SecIdx].Alignment = Alignment;
3441 CPSections[SecIdx].CPEs.push_back(Elt: i);
3442 }
3443
3444 // Now print stuff into the calculated sections.
3445 const MCSection *CurSection = nullptr;
3446 unsigned Offset = 0;
3447 for (const SectionCPs &CPSection : CPSections) {
3448 for (unsigned CPI : CPSection.CPEs) {
3449 MCSymbol *Sym = GetCPISymbol(CPID: CPI);
3450 if (!Sym->isUndefined())
3451 continue;
3452
3453 if (CurSection != CPSection.S) {
3454 OutStreamer->switchSection(Section: CPSection.S);
3455 emitAlignment(Alignment: Align(CPSection.Alignment));
3456 CurSection = CPSection.S;
3457 Offset = 0;
3458 }
3459
3460 MachineConstantPoolEntry CPE = CP[CPI];
3461
3462 // Emit inter-object padding for alignment.
3463 unsigned NewOffset = alignTo(Size: Offset, A: CPE.getAlign());
3464 OutStreamer->emitZeros(NumBytes: NewOffset - Offset);
3465
3466 if (MAI.hasDotTypeDotSizeDirective())
3467 OutStreamer->emitSymbolAttribute(Symbol: Sym, Attribute: MCSA_ELF_TypeObject);
3468 OutStreamer->emitLabel(Symbol: Sym);
3469
3470 if (CPE.isMachineConstantPoolEntry())
3471 emitMachineConstantPoolValue(MCPV: CPE.Val.MachineCPVal);
3472 else
3473 emitGlobalConstant(DL: getDataLayout(), CV: CPE.Val.ConstVal);
3474
3475 unsigned EntrySize = CPE.getSizeInBytes(DL: getDataLayout());
3476 if (MAI.hasDotTypeDotSizeDirective())
3477 OutStreamer->emitELFSize(Symbol: Sym,
3478 Value: MCConstantExpr::create(Value: EntrySize, Ctx&: OutContext));
3479
3480 Offset = NewOffset + EntrySize;
3481 }
3482 }
3483}
3484
3485// Print assembly representations of the jump tables used by the current
3486// function.
3487void AsmPrinter::emitJumpTableInfo() {
3488 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
3489 if (!MJTI) return;
3490
3491 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
3492 if (JT.empty()) return;
3493
3494 if (!TM.Options.EnableStaticDataPartitioning) {
3495 emitJumpTableImpl(MJTI: *MJTI, JumpTableIndices: llvm::to_vector(Range: llvm::seq<unsigned>(Size: JT.size())));
3496 return;
3497 }
3498
3499 SmallVector<unsigned> HotJumpTableIndices, ColdJumpTableIndices;
3500 // When static data partitioning is enabled, collect jump table entries that
3501 // go into the same section together to reduce the amount of section switch
3502 // statements.
3503 for (unsigned JTI = 0, JTSize = JT.size(); JTI < JTSize; ++JTI) {
3504 if (JT[JTI].Hotness == MachineFunctionDataHotness::Cold) {
3505 ColdJumpTableIndices.push_back(Elt: JTI);
3506 } else {
3507 HotJumpTableIndices.push_back(Elt: JTI);
3508 }
3509 }
3510
3511 emitJumpTableImpl(MJTI: *MJTI, JumpTableIndices: HotJumpTableIndices);
3512 emitJumpTableImpl(MJTI: *MJTI, JumpTableIndices: ColdJumpTableIndices);
3513}
3514
3515void AsmPrinter::emitJumpTableImpl(const MachineJumpTableInfo &MJTI,
3516 ArrayRef<unsigned> JumpTableIndices) {
3517 if (MJTI.getEntryKind() == MachineJumpTableInfo::EK_Inline ||
3518 JumpTableIndices.empty())
3519 return;
3520
3521 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
3522 const Function &F = MF->getFunction();
3523 const std::vector<MachineJumpTableEntry> &JT = MJTI.getJumpTables();
3524 MCSection *JumpTableSection = nullptr;
3525
3526 const bool UseLabelDifference =
3527 MJTI.getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
3528 MJTI.getEntryKind() == MachineJumpTableInfo::EK_LabelDifference64;
3529 // Pick the directive to use to print the jump table entries, and switch to
3530 // the appropriate section.
3531 const bool JTInDiffSection =
3532 !TLOF.shouldPutJumpTableInFunctionSection(UsesLabelDifference: UseLabelDifference, F);
3533 if (JTInDiffSection) {
3534 if (TM.Options.EnableStaticDataPartitioning) {
3535 JumpTableSection =
3536 TLOF.getSectionForJumpTable(F, TM, JTE: &JT[JumpTableIndices.front()]);
3537 } else {
3538 JumpTableSection = TLOF.getSectionForJumpTable(F, TM);
3539 }
3540 OutStreamer->switchSection(Section: JumpTableSection);
3541 }
3542
3543 const DataLayout &DL = MF->getDataLayout();
3544 emitAlignment(Alignment: Align(MJTI.getEntryAlignment(TD: DL)));
3545
3546 // Jump tables in code sections are marked with a data_region directive
3547 // where that's supported.
3548 if (!JTInDiffSection)
3549 OutStreamer->emitDataRegion(Kind: MCDR_DataRegionJT32);
3550
3551 for (const unsigned JumpTableIndex : JumpTableIndices) {
3552 ArrayRef<MachineBasicBlock *> JTBBs = JT[JumpTableIndex].MBBs;
3553
3554 // If this jump table was deleted, ignore it.
3555 if (JTBBs.empty())
3556 continue;
3557
3558 // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
3559 /// emit a .set directive for each unique entry.
3560 if (MJTI.getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
3561 MAI.doesSetDirectiveSuppressReloc()) {
3562 SmallPtrSet<const MachineBasicBlock *, 16> EmittedSets;
3563 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
3564 const MCExpr *Base =
3565 TLI->getPICJumpTableRelocBaseExpr(MF, JTI: JumpTableIndex, Ctx&: OutContext);
3566 for (const MachineBasicBlock *MBB : JTBBs) {
3567 if (!EmittedSets.insert(Ptr: MBB).second)
3568 continue;
3569
3570 // .set LJTSet, LBB32-base
3571 const MCExpr *LHS =
3572 MCSymbolRefExpr::create(Symbol: MBB->getSymbol(), Ctx&: OutContext);
3573 OutStreamer->emitAssignment(
3574 Symbol: GetJTSetSymbol(UID: JumpTableIndex, MBBID: MBB->getNumber()),
3575 Value: MCBinaryExpr::createSub(LHS, RHS: Base, Ctx&: OutContext));
3576 }
3577 }
3578
3579 // On some targets (e.g. Darwin) we want to emit two consecutive labels
3580 // before each jump table. The first label is never referenced, but tells
3581 // the assembler and linker the extents of the jump table object. The
3582 // second label is actually referenced by the code.
3583 if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
3584 // FIXME: This doesn't have to have any specific name, just any randomly
3585 // named and numbered local label started with 'l' would work. Simplify
3586 // GetJTISymbol.
3587 OutStreamer->emitLabel(Symbol: GetJTISymbol(JTID: JumpTableIndex, isLinkerPrivate: true));
3588
3589 MCSymbol *JTISymbol = GetJTISymbol(JTID: JumpTableIndex);
3590 if (JTInDiffSection && MAI.hasDotTypeDotSizeDirective())
3591 OutStreamer->emitSymbolAttribute(Symbol: JTISymbol, Attribute: MCSA_ELF_TypeObject);
3592 OutStreamer->emitLabel(Symbol: JTISymbol);
3593
3594 // Defer MCAssembler based constant folding due to a performance issue. The
3595 // label differences will be evaluated at write time.
3596 for (const MachineBasicBlock *MBB : JTBBs)
3597 emitJumpTableEntry(MJTI, MBB, uid: JumpTableIndex);
3598
3599 if (JTInDiffSection && MAI.hasDotTypeDotSizeDirective())
3600 OutStreamer->emitELFSize(
3601 Symbol: JTISymbol, Value: MCConstantExpr::create(
3602 Value: JTBBs.size() * MJTI.getEntrySize(TD: DL), Ctx&: OutContext));
3603 }
3604
3605 if (EmitJumpTableSizesSection)
3606 emitJumpTableSizesSection(MJTI, F: MF->getFunction());
3607
3608 if (!JTInDiffSection)
3609 OutStreamer->emitDataRegion(Kind: MCDR_DataRegionEnd);
3610}
3611
3612void AsmPrinter::emitJumpTableSizesSection(const MachineJumpTableInfo &MJTI,
3613 const Function &F) const {
3614 const std::vector<MachineJumpTableEntry> &JT = MJTI.getJumpTables();
3615
3616 if (JT.empty())
3617 return;
3618
3619 StringRef GroupName = F.hasComdat() ? F.getComdat()->getName() : "";
3620 MCSection *JumpTableSizesSection = nullptr;
3621 StringRef sectionName = ".llvm_jump_table_sizes";
3622
3623 bool isElf = TM.getTargetTriple().isOSBinFormatELF();
3624 bool isCoff = TM.getTargetTriple().isOSBinFormatCOFF();
3625
3626 if (!isCoff && !isElf)
3627 return;
3628
3629 if (isElf) {
3630 auto *LinkedToSym = static_cast<MCSymbolELF *>(CurrentFnSym);
3631 int Flags = F.hasComdat() ? static_cast<int>(ELF::SHF_GROUP) : 0;
3632
3633 JumpTableSizesSection = OutContext.getELFSection(
3634 Section: sectionName, Type: ELF::SHT_LLVM_JT_SIZES, Flags, EntrySize: 0, Group: GroupName, IsComdat: F.hasComdat(),
3635 UniqueID: MCSection::NonUniqueID, LinkedToSym);
3636 } else if (isCoff) {
3637 if (F.hasComdat()) {
3638 JumpTableSizesSection = OutContext.getCOFFSection(
3639 Section: sectionName,
3640 Characteristics: COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ |
3641 COFF::IMAGE_SCN_LNK_COMDAT | COFF::IMAGE_SCN_MEM_DISCARDABLE,
3642 COMDATSymName: F.getComdat()->getName(), Selection: COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
3643 } else {
3644 JumpTableSizesSection = OutContext.getCOFFSection(
3645 Section: sectionName, Characteristics: COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
3646 COFF::IMAGE_SCN_MEM_READ |
3647 COFF::IMAGE_SCN_MEM_DISCARDABLE);
3648 }
3649 }
3650
3651 OutStreamer->switchSection(Section: JumpTableSizesSection);
3652
3653 const DataLayout &DL = getDataLayout();
3654 unsigned ProgramPointerSize = DL.getPointerSize(AS: DL.getProgramAddressSpace());
3655 for (unsigned JTI = 0, E = JT.size(); JTI != E; ++JTI) {
3656 const std::vector<MachineBasicBlock *> &JTBBs = JT[JTI].MBBs;
3657 OutStreamer->emitSymbolValue(Sym: GetJTISymbol(JTID: JTI), Size: ProgramPointerSize);
3658 OutStreamer->emitIntValue(Value: JTBBs.size(), Size: ProgramPointerSize);
3659 }
3660}
3661
3662/// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
3663/// current stream.
3664void AsmPrinter::emitJumpTableEntry(const MachineJumpTableInfo &MJTI,
3665 const MachineBasicBlock *MBB,
3666 unsigned UID) const {
3667 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
3668 const MCExpr *Value = nullptr;
3669 switch (MJTI.getEntryKind()) {
3670 case MachineJumpTableInfo::EK_Inline:
3671 llvm_unreachable("Cannot emit EK_Inline jump table entry");
3672 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
3673 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
3674 llvm_unreachable("MIPS specific");
3675 case MachineJumpTableInfo::EK_Custom32:
3676 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
3677 &MJTI, MBB, UID, OutContext);
3678 break;
3679 case MachineJumpTableInfo::EK_BlockAddress:
3680 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
3681 // .word LBB123
3682 Value = MCSymbolRefExpr::create(Symbol: MBB->getSymbol(), Ctx&: OutContext);
3683 break;
3684
3685 case MachineJumpTableInfo::EK_LabelDifference32:
3686 case MachineJumpTableInfo::EK_LabelDifference64: {
3687 // Each entry is the address of the block minus the address of the jump
3688 // table. This is used for PIC jump tables where gprel32 is not supported.
3689 // e.g.:
3690 // .word LBB123 - LJTI1_2
3691 // If the .set directive avoids relocations, this is emitted as:
3692 // .set L4_5_set_123, LBB123 - LJTI1_2
3693 // .word L4_5_set_123
3694 if (MJTI.getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
3695 MAI.doesSetDirectiveSuppressReloc()) {
3696 Value = MCSymbolRefExpr::create(Symbol: GetJTSetSymbol(UID, MBBID: MBB->getNumber()),
3697 Ctx&: OutContext);
3698 break;
3699 }
3700 Value = MCSymbolRefExpr::create(Symbol: MBB->getSymbol(), Ctx&: OutContext);
3701 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
3702 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, JTI: UID, Ctx&: OutContext);
3703 Value = MCBinaryExpr::createSub(LHS: Value, RHS: Base, Ctx&: OutContext);
3704 break;
3705 }
3706 }
3707
3708 assert(Value && "Unknown entry kind!");
3709
3710 unsigned EntrySize = MJTI.getEntrySize(TD: getDataLayout());
3711 OutStreamer->emitValue(Value, Size: EntrySize);
3712}
3713
3714/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
3715/// special global used by LLVM. If so, emit it and return true, otherwise
3716/// do nothing and return false.
3717bool AsmPrinter::emitSpecialLLVMGlobal(const GlobalVariable *GV) {
3718 if (GV->getName() == "llvm.used") {
3719 if (MAI.hasNoDeadStrip()) // No need to emit this at all.
3720 emitLLVMUsedList(InitList: cast<ConstantArray>(Val: GV->getInitializer()));
3721 return true;
3722 }
3723
3724 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
3725 if (GV->getSection() == "llvm.metadata" ||
3726 GV->hasAvailableExternallyLinkage())
3727 return true;
3728
3729 if (GV->getName() == "llvm.arm64ec.symbolmap") {
3730 // For ARM64EC, print the table that maps between symbols and the
3731 // corresponding thunks to translate between x64 and AArch64 code.
3732 // This table is generated by AArch64Arm64ECCallLowering.
3733 OutStreamer->switchSection(
3734 Section: OutContext.getCOFFSection(Section: ".hybmp$x", Characteristics: COFF::IMAGE_SCN_LNK_INFO));
3735 auto *Arr = cast<ConstantArray>(Val: GV->getInitializer());
3736 for (auto &U : Arr->operands()) {
3737 auto *C = cast<Constant>(Val: U);
3738 auto *Src = cast<GlobalValue>(Val: C->getOperand(i: 0)->stripPointerCasts());
3739 auto *Dst = cast<GlobalValue>(Val: C->getOperand(i: 1)->stripPointerCasts());
3740 int Kind = cast<ConstantInt>(Val: C->getOperand(i: 2))->getZExtValue();
3741
3742 if (Src->hasDLLImportStorageClass()) {
3743 // For now, we assume dllimport functions aren't directly called.
3744 // (We might change this later to match MSVC.)
3745 OutStreamer->emitCOFFSymbolIndex(
3746 Symbol: OutContext.getOrCreateSymbol(Name: "__imp_" + Src->getName()));
3747 OutStreamer->emitCOFFSymbolIndex(Symbol: getSymbol(GV: Dst));
3748 OutStreamer->emitInt32(Value: Kind);
3749 } else {
3750 // FIXME: For non-dllimport functions, MSVC emits the same entry
3751 // twice, for reasons I don't understand. I have to assume the linker
3752 // ignores the redundant entry; there aren't any reasonable semantics
3753 // to attach to it.
3754 OutStreamer->emitCOFFSymbolIndex(Symbol: getSymbol(GV: Src));
3755 OutStreamer->emitCOFFSymbolIndex(Symbol: getSymbol(GV: Dst));
3756 OutStreamer->emitInt32(Value: Kind);
3757 }
3758 }
3759 return true;
3760 }
3761
3762 if (!GV->hasAppendingLinkage()) return false;
3763
3764 assert(GV->hasInitializer() && "Not a special LLVM global!");
3765
3766 if (GV->getName() == "llvm.global_ctors") {
3767 emitXXStructorList(DL: GV->getDataLayout(), List: GV->getInitializer(),
3768 /* isCtor */ IsCtor: true);
3769
3770 return true;
3771 }
3772
3773 if (GV->getName() == "llvm.global_dtors") {
3774 emitXXStructorList(DL: GV->getDataLayout(), List: GV->getInitializer(),
3775 /* isCtor */ IsCtor: false);
3776
3777 return true;
3778 }
3779
3780 GV->getContext().emitError(
3781 ErrorStr: "unknown special variable with appending linkage: " +
3782 GV->getNameOrAsOperand());
3783 return true;
3784}
3785
3786/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
3787/// global in the specified llvm.used list.
3788void AsmPrinter::emitLLVMUsedList(const ConstantArray *InitList) {
3789 // Should be an array of 'i8*'.
3790 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
3791 const GlobalValue *GV =
3792 dyn_cast<GlobalValue>(Val: InitList->getOperand(i_nocapture: i)->stripPointerCasts());
3793 if (GV)
3794 OutStreamer->emitSymbolAttribute(Symbol: getSymbol(GV), Attribute: MCSA_NoDeadStrip);
3795 }
3796}
3797
3798void AsmPrinter::preprocessXXStructorList(const DataLayout &DL,
3799 const Constant *List,
3800 SmallVector<Structor, 8> &Structors) {
3801 // Should be an array of '{ i32, void ()*, i8* }' structs. The first value is
3802 // the init priority.
3803 if (!isa<ConstantArray>(Val: List))
3804 return;
3805
3806 // Gather the structors in a form that's convenient for sorting by priority.
3807 for (Value *O : cast<ConstantArray>(Val: List)->operands()) {
3808 auto *CS = cast<ConstantStruct>(Val: O);
3809 if (CS->getOperand(i_nocapture: 1)->isNullValue())
3810 break; // Found a null terminator, skip the rest.
3811 ConstantInt *Priority = dyn_cast<ConstantInt>(Val: CS->getOperand(i_nocapture: 0));
3812 if (!Priority)
3813 continue; // Malformed.
3814 Structors.push_back(Elt: Structor());
3815 Structor &S = Structors.back();
3816 S.Priority = Priority->getLimitedValue(Limit: 65535);
3817 S.Func = CS->getOperand(i_nocapture: 1);
3818 if (!CS->getOperand(i_nocapture: 2)->isNullValue()) {
3819 if (TM.getTargetTriple().isOSAIX()) {
3820 CS->getContext().emitError(
3821 ErrorStr: "associated data of XXStructor list is not yet supported on AIX");
3822 }
3823
3824 S.ComdatKey =
3825 dyn_cast<GlobalValue>(Val: CS->getOperand(i_nocapture: 2)->stripPointerCasts());
3826 }
3827 }
3828
3829 // Emit the function pointers in the target-specific order
3830 llvm::stable_sort(Range&: Structors, C: [](const Structor &L, const Structor &R) {
3831 return L.Priority < R.Priority;
3832 });
3833}
3834
3835/// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
3836/// priority.
3837void AsmPrinter::emitXXStructorList(const DataLayout &DL, const Constant *List,
3838 bool IsCtor) {
3839 SmallVector<Structor, 8> Structors;
3840 preprocessXXStructorList(DL, List, Structors);
3841 if (Structors.empty())
3842 return;
3843
3844 // Emit the structors in reverse order if we are using the .ctor/.dtor
3845 // initialization scheme.
3846 if (!TM.Options.UseInitArray)
3847 std::reverse(first: Structors.begin(), last: Structors.end());
3848
3849 const Align Align = DL.getPointerPrefAlignment(AS: DL.getProgramAddressSpace());
3850 for (Structor &S : Structors) {
3851 const TargetLoweringObjectFile &Obj = getObjFileLowering();
3852 const MCSymbol *KeySym = nullptr;
3853 if (GlobalValue *GV = S.ComdatKey) {
3854 if (GV->isDeclarationForLinker())
3855 // If the associated variable is not defined in this module
3856 // (it might be available_externally, or have been an
3857 // available_externally definition that was dropped by the
3858 // EliminateAvailableExternally pass), some other TU
3859 // will provide its dynamic initializer.
3860 continue;
3861
3862 KeySym = getSymbol(GV);
3863 }
3864
3865 MCSection *OutputSection =
3866 (IsCtor ? Obj.getStaticCtorSection(Priority: S.Priority, KeySym)
3867 : Obj.getStaticDtorSection(Priority: S.Priority, KeySym));
3868 OutStreamer->switchSection(Section: OutputSection);
3869 if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
3870 emitAlignment(Alignment: Align);
3871 emitXXStructor(DL, CV: S.Func);
3872 }
3873}
3874
3875void AsmPrinter::emitModuleIdents(Module &M) {
3876 if (!MAI.hasIdentDirective())
3877 return;
3878
3879 if (const NamedMDNode *NMD = M.getNamedMetadata(Name: "llvm.ident")) {
3880 for (const MDNode *N : NMD->operands()) {
3881 assert(N->getNumOperands() == 1 &&
3882 "llvm.ident metadata entry can have only one operand");
3883 const MDString *S = cast<MDString>(Val: N->getOperand(I: 0));
3884 OutStreamer->emitIdent(IdentString: S->getString());
3885 }
3886 }
3887}
3888
3889void AsmPrinter::emitModuleCommandLines(Module &M) {
3890 MCSection *CommandLine = getObjFileLowering().getSectionForCommandLines();
3891 if (!CommandLine)
3892 return;
3893
3894 const NamedMDNode *NMD = M.getNamedMetadata(Name: "llvm.commandline");
3895 if (!NMD || !NMD->getNumOperands())
3896 return;
3897
3898 OutStreamer->pushSection();
3899 OutStreamer->switchSection(Section: CommandLine);
3900 OutStreamer->emitZeros(NumBytes: 1);
3901 for (const MDNode *N : NMD->operands()) {
3902 assert(N->getNumOperands() == 1 &&
3903 "llvm.commandline metadata entry can have only one operand");
3904 const MDString *S = cast<MDString>(Val: N->getOperand(I: 0));
3905 OutStreamer->emitBytes(Data: S->getString());
3906 OutStreamer->emitZeros(NumBytes: 1);
3907 }
3908 OutStreamer->popSection();
3909}
3910
3911//===--------------------------------------------------------------------===//
3912// Emission and print routines
3913//
3914
3915/// Emit a byte directive and value.
3916///
3917void AsmPrinter::emitInt8(int Value) const { OutStreamer->emitInt8(Value); }
3918
3919/// Emit a short directive and value.
3920void AsmPrinter::emitInt16(int Value) const { OutStreamer->emitInt16(Value); }
3921
3922/// Emit a long directive and value.
3923void AsmPrinter::emitInt32(int Value) const { OutStreamer->emitInt32(Value); }
3924
3925/// EmitSLEB128 - emit the specified signed leb128 value.
3926void AsmPrinter::emitSLEB128(int64_t Value, const char *Desc) const {
3927 if (isVerbose() && Desc)
3928 OutStreamer->AddComment(T: Desc);
3929
3930 OutStreamer->emitSLEB128IntValue(Value);
3931}
3932
3933void AsmPrinter::emitULEB128(uint64_t Value, const char *Desc,
3934 unsigned PadTo) const {
3935 if (isVerbose() && Desc)
3936 OutStreamer->AddComment(T: Desc);
3937
3938 OutStreamer->emitULEB128IntValue(Value, PadTo);
3939}
3940
3941/// Emit a long long directive and value.
3942void AsmPrinter::emitInt64(uint64_t Value) const {
3943 OutStreamer->emitInt64(Value);
3944}
3945
3946/// Emit something like ".long Hi-Lo" where the size in bytes of the directive
3947/// is specified by Size and Hi/Lo specify the labels. This implicitly uses
3948/// .set if it avoids relocations.
3949void AsmPrinter::emitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
3950 unsigned Size) const {
3951 OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
3952}
3953
3954/// Emit something like ".uleb128 Hi-Lo".
3955void AsmPrinter::emitLabelDifferenceAsULEB128(const MCSymbol *Hi,
3956 const MCSymbol *Lo) const {
3957 OutStreamer->emitAbsoluteSymbolDiffAsULEB128(Hi, Lo);
3958}
3959
3960/// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
3961/// where the size in bytes of the directive is specified by Size and Label
3962/// specifies the label. This implicitly uses .set if it is available.
3963void AsmPrinter::emitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
3964 unsigned Size,
3965 bool IsSectionRelative) const {
3966 if (IsSectionRelative) {
3967 OutStreamer->emitDwarfSectionOffset(Sym: Label, Offset, Size);
3968 return;
3969 }
3970
3971 // Emit Label+Offset (or just Label if Offset is zero)
3972 const MCExpr *Expr = MCSymbolRefExpr::create(Symbol: Label, Ctx&: OutContext);
3973 if (Offset)
3974 Expr = MCBinaryExpr::createAdd(
3975 LHS: Expr, RHS: MCConstantExpr::create(Value: Offset, Ctx&: OutContext), Ctx&: OutContext);
3976
3977 OutStreamer->emitValue(Value: Expr, Size);
3978}
3979
3980//===----------------------------------------------------------------------===//
3981
3982// EmitAlignment - Emit an alignment directive to the specified power of
3983// two boundary. If a global value is specified, and if that global has
3984// an explicit alignment requested, it will override the alignment request
3985// if required for correctness.
3986Align AsmPrinter::emitAlignment(Align Alignment, const GlobalObject *GV,
3987 unsigned MaxBytesToEmit) const {
3988 if (GV)
3989 Alignment = getGVAlignment(GV, DL: GV->getDataLayout(), InAlign: Alignment);
3990
3991 if (Alignment == Align(1))
3992 return Alignment; // 1-byte aligned: no need to emit alignment.
3993
3994 if (getCurrentSection()->isText()) {
3995 const MCSubtargetInfo *STI = nullptr;
3996 if (this->MF)
3997 STI = &getSubtargetInfo();
3998 else
3999 STI = &TM.getMCSubtargetInfo();
4000 OutStreamer->emitCodeAlignment(Alignment, STI: *STI, MaxBytesToEmit);
4001 } else
4002 OutStreamer->emitValueToAlignment(Alignment, Fill: 0, FillLen: 1, MaxBytesToEmit);
4003 return Alignment;
4004}
4005
4006//===----------------------------------------------------------------------===//
4007// Constant emission.
4008//===----------------------------------------------------------------------===//
4009
4010const MCExpr *AsmPrinter::lowerConstant(const Constant *CV,
4011 const Constant *BaseCV,
4012 uint64_t Offset) {
4013 MCContext &Ctx = OutContext;
4014
4015 if (CV->isNullValue() || isa<UndefValue>(Val: CV))
4016 return MCConstantExpr::create(Value: 0, Ctx);
4017
4018 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val: CV))
4019 return MCConstantExpr::create(Value: CI->getZExtValue(), Ctx);
4020
4021 if (const ConstantByte *CB = dyn_cast<ConstantByte>(Val: CV))
4022 return MCConstantExpr::create(Value: CB->getZExtValue(), Ctx);
4023
4024 if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(Val: CV))
4025 return lowerConstantPtrAuth(CPA: *CPA);
4026
4027 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Val: CV))
4028 return MCSymbolRefExpr::create(Symbol: getSymbol(GV), Ctx);
4029
4030 if (const BlockAddress *BA = dyn_cast<BlockAddress>(Val: CV))
4031 return lowerBlockAddressConstant(BA: *BA);
4032
4033 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(Val: CV))
4034 return getObjFileLowering().lowerDSOLocalEquivalent(
4035 LHS: getSymbol(GV: Equiv->getGlobalValue()), RHS: nullptr, Addend: 0, PCRelativeOffset: std::nullopt, TM);
4036
4037 if (const NoCFIValue *NC = dyn_cast<NoCFIValue>(Val: CV))
4038 return MCSymbolRefExpr::create(Symbol: getSymbol(GV: NC->getGlobalValue()), Ctx);
4039
4040 const ConstantExpr *CE = dyn_cast<ConstantExpr>(Val: CV);
4041 if (!CE) {
4042 llvm_unreachable("Unknown constant value to lower!");
4043 }
4044
4045 // The constant expression opcodes are limited to those that are necessary
4046 // to represent relocations on supported targets. Expressions involving only
4047 // constant addresses are constant folded instead.
4048 switch (CE->getOpcode()) {
4049 default:
4050 break; // Error
4051 case Instruction::AddrSpaceCast: {
4052 const Constant *Op = CE->getOperand(i_nocapture: 0);
4053 unsigned DstAS = CE->getType()->getPointerAddressSpace();
4054 unsigned SrcAS = Op->getType()->getPointerAddressSpace();
4055 if (TM.isNoopAddrSpaceCast(DL: getDataLayout(), SrcAS, DestAS: DstAS))
4056 return lowerConstant(CV: Op);
4057
4058 break; // Error
4059 }
4060 case Instruction::GetElementPtr: {
4061 // Generate a symbolic expression for the byte address
4062 APInt OffsetAI(getDataLayout().getIndexTypeSizeInBits(Ty: CE->getType()), 0);
4063 cast<GEPOperator>(Val: CE)->accumulateConstantOffset(DL: getDataLayout(), Offset&: OffsetAI);
4064
4065 const MCExpr *Base = lowerConstant(CV: CE->getOperand(i_nocapture: 0));
4066 if (!OffsetAI)
4067 return Base;
4068
4069 int64_t Offset = OffsetAI.getSExtValue();
4070 return MCBinaryExpr::createAdd(LHS: Base, RHS: MCConstantExpr::create(Value: Offset, Ctx),
4071 Ctx);
4072 }
4073
4074 case Instruction::Trunc:
4075 // We emit the value and depend on the assembler to truncate the generated
4076 // expression properly. This is important for differences between
4077 // blockaddress labels. Since the two labels are in the same function, it
4078 // is reasonable to treat their delta as a 32-bit value.
4079 [[fallthrough]];
4080 case Instruction::BitCast:
4081 return lowerConstant(CV: CE->getOperand(i_nocapture: 0), BaseCV, Offset);
4082
4083 case Instruction::IntToPtr: {
4084 const DataLayout &DL = getDataLayout();
4085
4086 // Handle casts to pointers by changing them into casts to the appropriate
4087 // integer type. This promotes constant folding and simplifies this code.
4088 Constant *Op = CE->getOperand(i_nocapture: 0);
4089 Op = ConstantFoldIntegerCast(C: Op, DestTy: DL.getIntPtrType(CV->getType()),
4090 /*IsSigned*/ false, DL);
4091 if (Op)
4092 return lowerConstant(CV: Op);
4093
4094 break; // Error
4095 }
4096
4097 case Instruction::PtrToAddr:
4098 case Instruction::PtrToInt: {
4099 const DataLayout &DL = getDataLayout();
4100
4101 // Support only foldable casts to/from pointers that can be eliminated by
4102 // changing the pointer to the appropriately sized integer type.
4103 Constant *Op = CE->getOperand(i_nocapture: 0);
4104 Type *Ty = CE->getType();
4105
4106 const MCExpr *OpExpr = lowerConstant(CV: Op);
4107
4108 // We can emit the pointer value into this slot if the slot is an
4109 // integer slot equal to the size of the pointer.
4110 //
4111 // If the pointer is larger than the resultant integer, then
4112 // as with Trunc just depend on the assembler to truncate it.
4113 if (DL.getTypeAllocSize(Ty).getFixedValue() <=
4114 DL.getTypeAllocSize(Ty: Op->getType()).getFixedValue())
4115 return OpExpr;
4116
4117 break; // Error
4118 }
4119
4120 case Instruction::Sub: {
4121 GlobalValue *LHSGV, *RHSGV;
4122 APInt LHSOffset, RHSOffset;
4123 DSOLocalEquivalent *DSOEquiv;
4124 if (IsConstantOffsetFromGlobal(C: CE->getOperand(i_nocapture: 0), GV&: LHSGV, Offset&: LHSOffset,
4125 DL: getDataLayout(), DSOEquiv: &DSOEquiv) &&
4126 IsConstantOffsetFromGlobal(C: CE->getOperand(i_nocapture: 1), GV&: RHSGV, Offset&: RHSOffset,
4127 DL: getDataLayout())) {
4128 auto *LHSSym = getSymbol(GV: LHSGV);
4129 auto *RHSSym = getSymbol(GV: RHSGV);
4130 int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
4131 std::optional<int64_t> PCRelativeOffset;
4132 if (getObjFileLowering().hasPLTPCRelative() && RHSGV == BaseCV)
4133 PCRelativeOffset = Offset;
4134
4135 // Try the generic symbol difference first.
4136 const MCExpr *Res = getObjFileLowering().lowerRelativeReference(
4137 LHS: LHSGV, RHS: RHSGV, Addend, PCRelativeOffset, TM);
4138
4139 // (ELF-specific) If the generic symbol difference does not apply, and
4140 // LHS is a dso_local_equivalent of a function, reference the PLT entry
4141 // instead. Note: A default visibility symbol is by default preemptible
4142 // during linking, and should not be referenced with PC-relative
4143 // relocations. Therefore, use a PLT relocation even if the function is
4144 // dso_local.
4145 if (DSOEquiv && TM.getTargetTriple().isOSBinFormatELF())
4146 Res = getObjFileLowering().lowerDSOLocalEquivalent(
4147 LHS: LHSSym, RHS: RHSSym, Addend, PCRelativeOffset, TM);
4148
4149 // Otherwise, return LHS-RHS+Addend.
4150 if (!Res) {
4151 Res =
4152 MCBinaryExpr::createSub(LHS: MCSymbolRefExpr::create(Symbol: LHSSym, Ctx),
4153 RHS: MCSymbolRefExpr::create(Symbol: RHSSym, Ctx), Ctx);
4154 if (Addend != 0)
4155 Res = MCBinaryExpr::createAdd(
4156 LHS: Res, RHS: MCConstantExpr::create(Value: Addend, Ctx), Ctx);
4157 }
4158 return Res;
4159 }
4160
4161 const MCExpr *LHS = lowerConstant(CV: CE->getOperand(i_nocapture: 0));
4162 const MCExpr *RHS = lowerConstant(CV: CE->getOperand(i_nocapture: 1));
4163 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
4164 break;
4165 }
4166
4167 case Instruction::Add: {
4168 const MCExpr *LHS = lowerConstant(CV: CE->getOperand(i_nocapture: 0));
4169 const MCExpr *RHS = lowerConstant(CV: CE->getOperand(i_nocapture: 1));
4170 return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
4171 }
4172 }
4173
4174 // If the code isn't optimized, there may be outstanding folding
4175 // opportunities. Attempt to fold the expression using DataLayout as a
4176 // last resort before giving up.
4177 Constant *C = ConstantFoldConstant(C: CE, DL: getDataLayout());
4178 if (C != CE)
4179 return lowerConstant(CV: C);
4180
4181 // Otherwise report the problem to the user.
4182 std::string S;
4183 raw_string_ostream OS(S);
4184 OS << "unsupported expression in static initializer: ";
4185 CE->printAsOperand(O&: OS, /*PrintType=*/false,
4186 M: !MF ? nullptr : MF->getFunction().getParent());
4187 CE->getContext().emitError(ErrorStr: S);
4188 return MCConstantExpr::create(Value: 0, Ctx);
4189}
4190
4191static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
4192 AsmPrinter &AP,
4193 const Constant *BaseCV = nullptr,
4194 uint64_t Offset = 0,
4195 AsmPrinter::AliasMapTy *AliasList = nullptr);
4196
4197static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
4198static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP);
4199
4200/// isRepeatedByteSequence - Determine whether the given value is
4201/// composed of a repeated sequence of identical bytes and return the
4202/// byte value. If it is not a repeated sequence, return -1.
4203static int isRepeatedByteSequence(const ConstantDataSequential *V) {
4204 StringRef Data = V->getRawDataValues();
4205 assert(!Data.empty() && "Empty aggregates should be CAZ node");
4206 char C = Data[0];
4207 for (unsigned i = 1, e = Data.size(); i != e; ++i)
4208 if (Data[i] != C) return -1;
4209 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
4210}
4211
4212/// isRepeatedByteSequence - Determine whether the given value is
4213/// composed of a repeated sequence of identical bytes and return the
4214/// byte value. If it is not a repeated sequence, return -1.
4215static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
4216 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val: V)) {
4217 uint64_t Size = DL.getTypeAllocSizeInBits(Ty: V->getType());
4218 assert(Size % 8 == 0);
4219
4220 // Extend the element to take zero padding into account.
4221 APInt Value = CI->getValue().zext(width: Size);
4222 if (!Value.isSplat(SplatSizeInBits: 8))
4223 return -1;
4224
4225 return Value.zextOrTrunc(width: 8).getZExtValue();
4226 }
4227 if (const ConstantArray *CA = dyn_cast<ConstantArray>(Val: V)) {
4228 // Make sure all array elements are sequences of the same repeated
4229 // byte.
4230 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
4231 Constant *Op0 = CA->getOperand(i_nocapture: 0);
4232 int Byte = isRepeatedByteSequence(V: Op0, DL);
4233 if (Byte == -1)
4234 return -1;
4235
4236 // All array elements must be equal.
4237 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
4238 if (CA->getOperand(i_nocapture: i) != Op0)
4239 return -1;
4240 return Byte;
4241 }
4242
4243 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(Val: V))
4244 return isRepeatedByteSequence(V: CDS);
4245
4246 return -1;
4247}
4248
4249static void emitGlobalAliasInline(AsmPrinter &AP, uint64_t Offset,
4250 AsmPrinter::AliasMapTy *AliasList) {
4251 if (AliasList) {
4252 auto AliasIt = AliasList->find(Val: Offset);
4253 if (AliasIt != AliasList->end()) {
4254 for (const GlobalAlias *GA : AliasIt->second)
4255 AP.OutStreamer->emitLabel(Symbol: AP.getSymbol(GV: GA));
4256 AliasList->erase(Val: Offset);
4257 }
4258 }
4259}
4260
4261static void emitGlobalConstantDataSequential(
4262 const DataLayout &DL, const ConstantDataSequential *CDS, AsmPrinter &AP,
4263 AsmPrinter::AliasMapTy *AliasList) {
4264 // See if we can aggregate this into a .fill, if so, emit it as such.
4265 int Value = isRepeatedByteSequence(V: CDS, DL);
4266 if (Value != -1) {
4267 uint64_t Bytes = DL.getTypeAllocSize(Ty: CDS->getType());
4268 // Don't emit a 1-byte object as a .fill.
4269 if (Bytes > 1)
4270 return AP.OutStreamer->emitFill(NumBytes: Bytes, FillValue: Value);
4271 }
4272
4273 // If this can be emitted with .ascii/.asciz, emit it as such.
4274 if (CDS->isString())
4275 return AP.OutStreamer->emitBytes(Data: CDS->getAsString());
4276
4277 // Otherwise, emit the values in successive locations.
4278 uint64_t ElementByteSize = CDS->getElementByteSize();
4279 if (isa<IntegerType>(Val: CDS->getElementType()) ||
4280 isa<ByteType>(Val: CDS->getElementType())) {
4281 for (uint64_t I = 0, E = CDS->getNumElements(); I != E; ++I) {
4282 emitGlobalAliasInline(AP, Offset: ElementByteSize * I, AliasList);
4283 if (AP.isVerbose())
4284 AP.OutStreamer->getCommentOS()
4285 << format(Fmt: "0x%" PRIx64 "\n", Vals: CDS->getElementAsInteger(i: I));
4286 AP.OutStreamer->emitIntValue(Value: CDS->getElementAsInteger(i: I),
4287 Size: ElementByteSize);
4288 }
4289 } else {
4290 Type *ET = CDS->getElementType();
4291 for (uint64_t I = 0, E = CDS->getNumElements(); I != E; ++I) {
4292 emitGlobalAliasInline(AP, Offset: ElementByteSize * I, AliasList);
4293 emitGlobalConstantFP(APF: CDS->getElementAsAPFloat(i: I), ET, AP);
4294 }
4295 }
4296
4297 unsigned Size = DL.getTypeAllocSize(Ty: CDS->getType());
4298 unsigned EmittedSize =
4299 DL.getTypeAllocSize(Ty: CDS->getElementType()) * CDS->getNumElements();
4300 assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!");
4301 if (unsigned Padding = Size - EmittedSize)
4302 AP.OutStreamer->emitZeros(NumBytes: Padding);
4303}
4304
4305static void emitGlobalConstantArray(const DataLayout &DL,
4306 const ConstantArray *CA, AsmPrinter &AP,
4307 const Constant *BaseCV, uint64_t Offset,
4308 AsmPrinter::AliasMapTy *AliasList) {
4309 // See if we can aggregate some values. Make sure it can be
4310 // represented as a series of bytes of the constant value.
4311 int Value = isRepeatedByteSequence(V: CA, DL);
4312
4313 if (Value != -1) {
4314 uint64_t Bytes = DL.getTypeAllocSize(Ty: CA->getType());
4315 AP.OutStreamer->emitFill(NumBytes: Bytes, FillValue: Value);
4316 } else {
4317 for (unsigned I = 0, E = CA->getNumOperands(); I != E; ++I) {
4318 emitGlobalConstantImpl(DL, C: CA->getOperand(i_nocapture: I), AP, BaseCV, Offset,
4319 AliasList);
4320 Offset += DL.getTypeAllocSize(Ty: CA->getOperand(i_nocapture: I)->getType());
4321 }
4322 }
4323}
4324
4325static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP);
4326
4327static void emitGlobalConstantVector(const DataLayout &DL, const Constant *CV,
4328 AsmPrinter &AP,
4329 AsmPrinter::AliasMapTy *AliasList) {
4330 uint64_t AllocSize = DL.getTypeAllocSize(Ty: CV->getType());
4331
4332 if (CV->isNullValue())
4333 return AP.OutStreamer->emitZeros(NumBytes: AllocSize);
4334
4335 auto *VTy = cast<FixedVectorType>(Val: CV->getType());
4336 Type *ElementType = VTy->getElementType();
4337 uint64_t ElementSizeInBits = DL.getTypeSizeInBits(Ty: ElementType);
4338 uint64_t ElementAllocSizeInBits = DL.getTypeAllocSizeInBits(Ty: ElementType);
4339 uint64_t EmittedSize;
4340 if (ElementSizeInBits != ElementAllocSizeInBits) {
4341 // If the allocation size of an element is different from the size in bits,
4342 // printing each element separately will insert incorrect padding.
4343 //
4344 // The general algorithm here is complicated; instead of writing it out
4345 // here, just use the existing code in ConstantFolding.
4346 Type *IntT =
4347 IntegerType::get(C&: CV->getContext(), NumBits: DL.getTypeSizeInBits(Ty: CV->getType()));
4348 ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Val: ConstantFoldConstant(
4349 C: ConstantExpr::getBitCast(C: const_cast<Constant *>(CV), Ty: IntT), DL));
4350 if (!CI) {
4351 report_fatal_error(
4352 reason: "Cannot lower vector global with unusual element type");
4353 }
4354 emitGlobalAliasInline(AP, Offset: 0, AliasList);
4355 emitGlobalConstantLargeInt(CI, AP);
4356 EmittedSize = DL.getTypeStoreSize(Ty: CV->getType());
4357 } else {
4358 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
4359 emitGlobalAliasInline(AP, Offset: AllocSize * I, AliasList);
4360 emitGlobalConstantImpl(DL, C: CV->getAggregateElement(Elt: I), AP);
4361 }
4362 EmittedSize = DL.getTypeAllocSize(Ty: ElementType) * VTy->getNumElements();
4363 }
4364
4365 if (unsigned Padding = AllocSize - EmittedSize)
4366 AP.OutStreamer->emitZeros(NumBytes: Padding);
4367}
4368
4369static void emitGlobalConstantStruct(const DataLayout &DL,
4370 const ConstantStruct *CS, AsmPrinter &AP,
4371 const Constant *BaseCV, uint64_t Offset,
4372 AsmPrinter::AliasMapTy *AliasList) {
4373 // Print the fields in successive locations. Pad to align if needed!
4374 uint64_t Size = DL.getTypeAllocSize(Ty: CS->getType());
4375 const StructLayout *Layout = DL.getStructLayout(Ty: CS->getType());
4376 uint64_t SizeSoFar = 0;
4377 for (unsigned I = 0, E = CS->getNumOperands(); I != E; ++I) {
4378 const Constant *Field = CS->getOperand(i_nocapture: I);
4379
4380 // Print the actual field value.
4381 emitGlobalConstantImpl(DL, C: Field, AP, BaseCV, Offset: Offset + SizeSoFar,
4382 AliasList);
4383
4384 // Check if padding is needed and insert one or more 0s.
4385 uint64_t FieldSize = DL.getTypeAllocSize(Ty: Field->getType());
4386 uint64_t PadSize = ((I == E - 1 ? Size : Layout->getElementOffset(Idx: I + 1)) -
4387 Layout->getElementOffset(Idx: I)) -
4388 FieldSize;
4389 SizeSoFar += FieldSize + PadSize;
4390
4391 // Insert padding - this may include padding to increase the size of the
4392 // current field up to the ABI size (if the struct is not packed) as well
4393 // as padding to ensure that the next field starts at the right offset.
4394 AP.OutStreamer->emitZeros(NumBytes: PadSize);
4395 }
4396 assert(SizeSoFar == Layout->getSizeInBytes() &&
4397 "Layout of constant struct may be incorrect!");
4398}
4399
4400static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) {
4401 assert(ET && "Unknown float type");
4402 APInt API = APF.bitcastToAPInt();
4403
4404 // First print a comment with what we think the original floating-point value
4405 // should have been.
4406 if (AP.isVerbose()) {
4407 SmallString<8> StrVal;
4408 APF.toString(Str&: StrVal);
4409 ET->print(O&: AP.OutStreamer->getCommentOS());
4410 AP.OutStreamer->getCommentOS() << ' ' << StrVal << '\n';
4411 }
4412
4413 // Now iterate through the APInt chunks, emitting them in endian-correct
4414 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
4415 // floats).
4416 unsigned NumBytes = API.getBitWidth() / 8;
4417 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
4418 const uint64_t *p = API.getRawData();
4419
4420 // PPC's long double has odd notions of endianness compared to how LLVM
4421 // handles it: p[0] goes first for *big* endian on PPC.
4422 if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) {
4423 int Chunk = API.getNumWords() - 1;
4424
4425 if (TrailingBytes)
4426 AP.OutStreamer->emitIntValueInHexWithPadding(Value: p[Chunk--], Size: TrailingBytes);
4427
4428 for (; Chunk >= 0; --Chunk)
4429 AP.OutStreamer->emitIntValueInHexWithPadding(Value: p[Chunk], Size: sizeof(uint64_t));
4430 } else {
4431 unsigned Chunk;
4432 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
4433 AP.OutStreamer->emitIntValueInHexWithPadding(Value: p[Chunk], Size: sizeof(uint64_t));
4434
4435 if (TrailingBytes)
4436 AP.OutStreamer->emitIntValueInHexWithPadding(Value: p[Chunk], Size: TrailingBytes);
4437 }
4438
4439 // Emit the tail padding for the long double.
4440 const DataLayout &DL = AP.getDataLayout();
4441 AP.OutStreamer->emitZeros(NumBytes: DL.getTypeAllocSize(Ty: ET) - DL.getTypeStoreSize(Ty: ET));
4442}
4443
4444static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
4445 emitGlobalConstantFP(APF: CFP->getValueAPF(), ET: CFP->getType(), AP);
4446}
4447
4448static void emitGlobalConstantLargeAPInt(const APInt &Val,
4449 uint64_t TypeStoreSize,
4450 AsmPrinter &AP) {
4451 const DataLayout &DL = AP.getDataLayout();
4452 unsigned BitWidth = Val.getBitWidth();
4453
4454 // Copy the value as we may massage the layout for constants whose bit width
4455 // is not a multiple of 64-bits.
4456 APInt Realigned(Val);
4457 uint64_t ExtraBits = 0;
4458 unsigned ExtraBitsSize = BitWidth & 63;
4459
4460 if (ExtraBitsSize) {
4461 // The bit width of the data is not a multiple of 64-bits.
4462 // The extra bits are expected to be at the end of the chunk of the memory.
4463 // Little endian:
4464 // * Nothing to be done, just record the extra bits to emit.
4465 // Big endian:
4466 // * Record the extra bits to emit.
4467 // * Realign the raw data to emit the chunks of 64-bits.
4468 if (DL.isBigEndian()) {
4469 // Basically the structure of the raw data is a chunk of 64-bits cells:
4470 // 0 1 BitWidth / 64
4471 // [chunk1][chunk2] ... [chunkN].
4472 // The most significant chunk is chunkN and it should be emitted first.
4473 // However, due to the alignment issue chunkN contains useless bits.
4474 // Realign the chunks so that they contain only useful information:
4475 // ExtraBits 0 1 (BitWidth / 64) - 1
4476 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
4477 ExtraBitsSize = alignTo(Value: ExtraBitsSize, Align: 8);
4478 ExtraBits =
4479 Realigned.getRawData()[0] & (((uint64_t)-1) >> (64 - ExtraBitsSize));
4480 if (BitWidth >= 64)
4481 Realigned.lshrInPlace(ShiftAmt: ExtraBitsSize);
4482 } else
4483 ExtraBits = Realigned.getRawData()[BitWidth / 64];
4484 }
4485
4486 // We don't expect assemblers to support data directives
4487 // for more than 64 bits, so we emit the data in at most 64-bit
4488 // quantities at a time.
4489 const uint64_t *RawData = Realigned.getRawData();
4490 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
4491 uint64_t ChunkVal = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
4492 AP.OutStreamer->emitIntValue(Value: ChunkVal, Size: 8);
4493 }
4494
4495 if (ExtraBitsSize) {
4496 // Emit the extra bits after the 64-bits chunks.
4497
4498 // Emit a directive that fills the expected size.
4499 uint64_t Size = TypeStoreSize - (BitWidth / 64) * 8;
4500 assert(Size && Size * 8 >= ExtraBitsSize &&
4501 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize))) ==
4502 ExtraBits &&
4503 "Directive too small for extra bits.");
4504 AP.OutStreamer->emitIntValue(Value: ExtraBits, Size);
4505 }
4506}
4507
4508static void emitGlobalConstantLargeByte(const ConstantByte *CB,
4509 AsmPrinter &AP) {
4510 emitGlobalConstantLargeAPInt(
4511 Val: CB->getValue(), TypeStoreSize: AP.getDataLayout().getTypeStoreSize(Ty: CB->getType()), AP);
4512}
4513
4514static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
4515 emitGlobalConstantLargeAPInt(
4516 Val: CI->getValue(), TypeStoreSize: AP.getDataLayout().getTypeStoreSize(Ty: CI->getType()), AP);
4517}
4518
4519/// Transform a not absolute MCExpr containing a reference to a GOT
4520/// equivalent global, by a target specific GOT pc relative access to the
4521/// final symbol.
4522static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
4523 const Constant *BaseCst,
4524 uint64_t Offset) {
4525 // The global @foo below illustrates a global that uses a got equivalent.
4526 //
4527 // @bar = global i32 42
4528 // @gotequiv = private unnamed_addr constant i32* @bar
4529 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
4530 // i64 ptrtoint (i32* @foo to i64))
4531 // to i32)
4532 //
4533 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
4534 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
4535 // form:
4536 //
4537 // foo = cstexpr, where
4538 // cstexpr := <gotequiv> - "." + <cst>
4539 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
4540 //
4541 // After canonicalization by evaluateAsRelocatable `ME` turns into:
4542 //
4543 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
4544 // gotpcrelcst := <offset from @foo base> + <cst>
4545 MCValue MV;
4546 if (!(*ME)->evaluateAsRelocatable(Res&: MV, Asm: nullptr) || MV.isAbsolute())
4547 return;
4548 const MCSymbol *GOTEquivSym = MV.getAddSym();
4549 if (!GOTEquivSym)
4550 return;
4551
4552 // Check that GOT equivalent symbol is cached.
4553 if (!AP.GlobalGOTEquivs.count(Key: GOTEquivSym))
4554 return;
4555
4556 const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(Val: BaseCst);
4557 if (!BaseGV)
4558 return;
4559
4560 // Check for a valid base symbol
4561 const MCSymbol *BaseSym = AP.getSymbol(GV: BaseGV);
4562 const MCSymbol *SymB = MV.getSubSym();
4563
4564 if (!SymB || BaseSym != SymB)
4565 return;
4566
4567 // Make sure to match:
4568 //
4569 // gotpcrelcst := <offset from @foo base> + <cst>
4570 //
4571 int64_t GOTPCRelCst = Offset + MV.getConstant();
4572 if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
4573 return;
4574
4575 // Emit the GOT PC relative to replace the got equivalent global, i.e.:
4576 //
4577 // bar:
4578 // .long 42
4579 // gotequiv:
4580 // .quad bar
4581 // foo:
4582 // .long gotequiv - "." + <cst>
4583 //
4584 // is replaced by the target specific equivalent to:
4585 //
4586 // bar:
4587 // .long 42
4588 // foo:
4589 // .long bar@GOTPCREL+<gotpcrelcst>
4590 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
4591 const GlobalVariable *GV = Result.first;
4592 int NumUses = (int)Result.second;
4593 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(Val: GV->getOperand(i_nocapture: 0));
4594 const MCSymbol *FinalSym = AP.getSymbol(GV: FinalGV);
4595 *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel(
4596 GV: FinalGV, Sym: FinalSym, MV, Offset, MMI: AP.MMI, Streamer&: *AP.OutStreamer);
4597
4598 // Update GOT equivalent usage information
4599 --NumUses;
4600 if (NumUses >= 0)
4601 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(x&: GV, y&: NumUses);
4602}
4603
4604static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
4605 AsmPrinter &AP, const Constant *BaseCV,
4606 uint64_t Offset,
4607 AsmPrinter::AliasMapTy *AliasList) {
4608 assert((!AliasList || AP.TM.getTargetTriple().isOSBinFormatXCOFF()) &&
4609 "AliasList only expected for XCOFF");
4610 emitGlobalAliasInline(AP, Offset, AliasList);
4611 uint64_t Size = DL.getTypeAllocSize(Ty: CV->getType());
4612
4613 // Globals with sub-elements such as combinations of arrays and structs
4614 // are handled recursively by emitGlobalConstantImpl. Keep track of the
4615 // constant symbol base and the current position with BaseCV and Offset.
4616 if (!BaseCV && CV->hasOneUse())
4617 BaseCV = dyn_cast<Constant>(Val: CV->user_back());
4618
4619 if (isa<ConstantAggregateZero>(Val: CV)) {
4620 StructType *structType;
4621 if (AliasList && (structType = llvm::dyn_cast<StructType>(Val: CV->getType()))) {
4622 unsigned numElements = {structType->getNumElements()};
4623 if (numElements != 0) {
4624 // Handle cases of aliases to direct struct elements
4625 const StructLayout *Layout = DL.getStructLayout(Ty: structType);
4626 uint64_t SizeSoFar = 0;
4627 for (unsigned int i = 0; i < numElements - 1; ++i) {
4628 uint64_t GapToNext = Layout->getElementOffset(Idx: i + 1) - SizeSoFar;
4629 AP.OutStreamer->emitZeros(NumBytes: GapToNext);
4630 SizeSoFar += GapToNext;
4631 emitGlobalAliasInline(AP, Offset: Offset + SizeSoFar, AliasList);
4632 }
4633 AP.OutStreamer->emitZeros(NumBytes: Size - SizeSoFar);
4634 return;
4635 }
4636 }
4637 return AP.OutStreamer->emitZeros(NumBytes: Size);
4638 }
4639
4640 if (isa<UndefValue>(Val: CV))
4641 return AP.OutStreamer->emitZeros(NumBytes: Size);
4642
4643 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val: CV)) {
4644 if (isa<VectorType>(Val: CV->getType()))
4645 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4646
4647 const uint64_t StoreSize = DL.getTypeStoreSize(Ty: CV->getType());
4648 if (StoreSize <= 8) {
4649 if (AP.isVerbose())
4650 AP.OutStreamer->getCommentOS()
4651 << format(Fmt: "0x%" PRIx64 "\n", Vals: CI->getZExtValue());
4652 AP.OutStreamer->emitIntValue(Value: CI->getZExtValue(), Size: StoreSize);
4653 } else {
4654 emitGlobalConstantLargeInt(CI, AP);
4655 }
4656
4657 // Emit tail padding if needed
4658 if (Size != StoreSize)
4659 AP.OutStreamer->emitZeros(NumBytes: Size - StoreSize);
4660
4661 return;
4662 }
4663
4664 if (const ConstantByte *CB = dyn_cast<ConstantByte>(Val: CV)) {
4665 if (isa<VectorType>(Val: CV->getType()))
4666 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4667
4668 const uint64_t StoreSize = DL.getTypeStoreSize(Ty: CV->getType());
4669 if (StoreSize <= 8) {
4670 if (AP.isVerbose())
4671 AP.OutStreamer->getCommentOS()
4672 << format(Fmt: "0x%" PRIx64 "\n", Vals: CB->getZExtValue());
4673 AP.OutStreamer->emitIntValue(Value: CB->getZExtValue(), Size: StoreSize);
4674 } else {
4675 emitGlobalConstantLargeByte(CB, AP);
4676 }
4677
4678 // Emit tail padding if needed
4679 if (Size != StoreSize)
4680 AP.OutStreamer->emitZeros(NumBytes: Size - StoreSize);
4681
4682 return;
4683 }
4684
4685 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Val: CV)) {
4686 if (isa<VectorType>(Val: CV->getType()))
4687 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4688 else
4689 return emitGlobalConstantFP(CFP, AP);
4690 }
4691
4692 if (isa<ConstantPointerNull>(Val: CV)) {
4693 if (isa<VectorType>(Val: CV->getType()))
4694 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4695 AP.OutStreamer->emitIntValue(Value: 0, Size);
4696 return;
4697 }
4698
4699 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(Val: CV))
4700 return emitGlobalConstantDataSequential(DL, CDS, AP, AliasList);
4701
4702 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(Val: CV))
4703 return emitGlobalConstantArray(DL, CA: CVA, AP, BaseCV, Offset, AliasList);
4704
4705 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(Val: CV))
4706 return emitGlobalConstantStruct(DL, CS: CVS, AP, BaseCV, Offset, AliasList);
4707
4708 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Val: CV)) {
4709 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
4710 // vectors).
4711 if (CE->getOpcode() == Instruction::BitCast)
4712 return emitGlobalConstantImpl(DL, CV: CE->getOperand(i_nocapture: 0), AP);
4713
4714 if (Size > 8) {
4715 // If the constant expression's size is greater than 64-bits, then we have
4716 // to emit the value in chunks. Try to constant fold the value and emit it
4717 // that way.
4718 Constant *New = ConstantFoldConstant(C: CE, DL);
4719 if (New != CE)
4720 return emitGlobalConstantImpl(DL, CV: New, AP);
4721 }
4722 }
4723
4724 if (isa<ConstantVector>(Val: CV))
4725 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4726
4727 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
4728 // thread the streamer with EmitValue.
4729 const MCExpr *ME = AP.lowerConstant(CV, BaseCV, Offset);
4730
4731 // Since lowerConstant already folded and got rid of all IR pointer and
4732 // integer casts, detect GOT equivalent accesses by looking into the MCExpr
4733 // directly.
4734 if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel())
4735 handleIndirectSymViaGOTPCRel(AP, ME: &ME, BaseCst: BaseCV, Offset);
4736
4737 AP.OutStreamer->emitValue(Value: ME, Size);
4738}
4739
4740/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
4741void AsmPrinter::emitGlobalConstant(const DataLayout &DL, const Constant *CV,
4742 AliasMapTy *AliasList) {
4743 uint64_t Size = DL.getTypeAllocSize(Ty: CV->getType());
4744 if (Size)
4745 emitGlobalConstantImpl(DL, CV, AP&: *this, BaseCV: nullptr, Offset: 0, AliasList);
4746 else if (MAI.hasSubsectionsViaSymbols()) {
4747 // If the global has zero size, emit a single byte so that two labels don't
4748 // look like they are at the same location.
4749 OutStreamer->emitIntValue(Value: 0, Size: 1);
4750 }
4751 if (!AliasList)
4752 return;
4753 // TODO: These remaining aliases are not emitted in the correct location. Need
4754 // to handle the case where the alias offset doesn't refer to any sub-element.
4755 for (auto &AliasPair : *AliasList) {
4756 for (const GlobalAlias *GA : AliasPair.second)
4757 OutStreamer->emitLabel(Symbol: getSymbol(GV: GA));
4758 }
4759}
4760
4761void AsmPrinter::emitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
4762 // Target doesn't support this yet!
4763 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
4764}
4765
4766void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
4767 if (Offset > 0)
4768 OS << '+' << Offset;
4769 else if (Offset < 0)
4770 OS << Offset;
4771}
4772
4773void AsmPrinter::emitNops(unsigned N) {
4774 MCInst Nop = MF->getSubtarget().getInstrInfo()->getNop();
4775 for (; N; --N)
4776 EmitToStreamer(S&: *OutStreamer, Inst: Nop);
4777}
4778
4779//===----------------------------------------------------------------------===//
4780// Symbol Lowering Routines.
4781//===----------------------------------------------------------------------===//
4782
4783MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const {
4784 return OutContext.createTempSymbol(Name, AlwaysAddSuffix: true);
4785}
4786
4787MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
4788 return const_cast<AsmPrinter *>(this)->getAddrLabelSymbol(
4789 BB: BA->getBasicBlock());
4790}
4791
4792MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
4793 return const_cast<AsmPrinter *>(this)->getAddrLabelSymbol(BB);
4794}
4795
4796const MCExpr *AsmPrinter::lowerBlockAddressConstant(const BlockAddress &BA) {
4797 return MCSymbolRefExpr::create(Symbol: GetBlockAddressSymbol(BA: &BA), Ctx&: OutContext);
4798}
4799
4800/// GetCPISymbol - Return the symbol for the specified constant pool entry.
4801MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
4802 if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment() ||
4803 getSubtargetInfo().getTargetTriple().isUEFI()) {
4804 const MachineConstantPoolEntry &CPE =
4805 MF->getConstantPool()->getConstants()[CPID];
4806 if (!CPE.isMachineConstantPoolEntry()) {
4807 const DataLayout &DL = MF->getDataLayout();
4808 SectionKind Kind = CPE.getSectionKind(DL: &DL);
4809 const Constant *C = CPE.Val.ConstVal;
4810 Align Alignment = CPE.Alignment;
4811 auto *S = getObjFileLowering().getSectionForConstant(
4812 DL, Kind, C, Alignment, F: &MF->getFunction());
4813 if (S && TM.getTargetTriple().isOSBinFormatCOFF()) {
4814 if (MCSymbol *Sym =
4815 static_cast<const MCSectionCOFF *>(S)->getCOMDATSymbol()) {
4816 if (Sym->isUndefined())
4817 OutStreamer->emitSymbolAttribute(Symbol: Sym, Attribute: MCSA_Global);
4818 return Sym;
4819 }
4820 }
4821 }
4822 }
4823
4824 const DataLayout &DL = getDataLayout();
4825 return OutContext.getOrCreateSymbol(Name: Twine(DL.getInternalSymbolPrefix()) +
4826 "CPI" + Twine(getFunctionNumber()) + "_" +
4827 Twine(CPID));
4828}
4829
4830/// GetJTISymbol - Return the symbol for the specified jump table entry.
4831MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
4832 return MF->getJTISymbol(JTI: JTID, Ctx&: OutContext, isLinkerPrivate);
4833}
4834
4835/// GetJTSetSymbol - Return the symbol for the specified jump table .set
4836/// FIXME: privatize to AsmPrinter.
4837MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
4838 const DataLayout &DL = getDataLayout();
4839 return OutContext.getOrCreateSymbol(Name: Twine(DL.getInternalSymbolPrefix()) +
4840 Twine(getFunctionNumber()) + "_" +
4841 Twine(UID) + "_set_" + Twine(MBBID));
4842}
4843
4844MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
4845 StringRef Suffix) const {
4846 return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, TM);
4847}
4848
4849/// Return the MCSymbol for the specified ExternalSymbol.
4850MCSymbol *AsmPrinter::GetExternalSymbolSymbol(const Twine &Sym) const {
4851 SmallString<60> NameStr;
4852 Mangler::getNameWithPrefix(OutName&: NameStr, GVName: Sym, DL: getDataLayout());
4853 return OutContext.getOrCreateSymbol(Name: NameStr);
4854}
4855
4856/// PrintParentLoopComment - Print comments about parent loops of this one.
4857static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
4858 unsigned FunctionNumber) {
4859 if (!Loop) return;
4860 PrintParentLoopComment(OS, Loop: Loop->getParentLoop(), FunctionNumber);
4861 OS.indent(NumSpaces: Loop->getLoopDepth()*2)
4862 << "Parent Loop BB" << FunctionNumber << "_"
4863 << Loop->getHeader()->getNumber()
4864 << " Depth=" << Loop->getLoopDepth() << '\n';
4865}
4866
4867/// PrintChildLoopComment - Print comments about child loops within
4868/// the loop for this basic block, with nesting.
4869static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
4870 unsigned FunctionNumber) {
4871 // Add child loop information
4872 for (const MachineLoop *CL : *Loop) {
4873 OS.indent(NumSpaces: CL->getLoopDepth()*2)
4874 << "Child Loop BB" << FunctionNumber << "_"
4875 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
4876 << '\n';
4877 PrintChildLoopComment(OS, Loop: CL, FunctionNumber);
4878 }
4879}
4880
4881/// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
4882static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
4883 const MachineLoopInfo *LI,
4884 const AsmPrinter &AP) {
4885 // Add loop depth information
4886 const MachineLoop *Loop = LI->getLoopFor(BB: &MBB);
4887 if (!Loop) return;
4888
4889 MachineBasicBlock *Header = Loop->getHeader();
4890 assert(Header && "No header for loop");
4891
4892 // If this block is not a loop header, just print out what is the loop header
4893 // and return.
4894 if (Header != &MBB) {
4895 AP.OutStreamer->AddComment(T: " in Loop: Header=BB" +
4896 Twine(AP.getFunctionNumber())+"_" +
4897 Twine(Loop->getHeader()->getNumber())+
4898 " Depth="+Twine(Loop->getLoopDepth()));
4899 return;
4900 }
4901
4902 // Otherwise, it is a loop header. Print out information about child and
4903 // parent loops.
4904 raw_ostream &OS = AP.OutStreamer->getCommentOS();
4905
4906 PrintParentLoopComment(OS, Loop: Loop->getParentLoop(), FunctionNumber: AP.getFunctionNumber());
4907
4908 OS << "=>";
4909 OS.indent(NumSpaces: Loop->getLoopDepth()*2-2);
4910
4911 OS << "This ";
4912 if (Loop->isInnermost())
4913 OS << "Inner ";
4914 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
4915
4916 PrintChildLoopComment(OS, Loop, FunctionNumber: AP.getFunctionNumber());
4917}
4918
4919/// emitBasicBlockStart - This method prints the label for the specified
4920/// MachineBasicBlock, an alignment (if present) and a comment describing
4921/// it if appropriate.
4922void AsmPrinter::emitBasicBlockStart(const MachineBasicBlock &MBB) {
4923 // End the previous funclet and start a new one.
4924 if (MBB.isEHFuncletEntry()) {
4925 for (auto &Handler : Handlers) {
4926 Handler->endFunclet();
4927 Handler->beginFunclet(MBB);
4928 }
4929 for (auto &Handler : EHHandlers) {
4930 Handler->endFunclet();
4931 Handler->beginFunclet(MBB);
4932 }
4933 }
4934
4935 // Switch to a new section if this basic block must begin a section. The
4936 // entry block is always placed in the function section and is handled
4937 // separately.
4938 if (MBB.isBeginSection() && !MBB.isEntryBlock()) {
4939 OutStreamer->switchSection(
4940 Section: getObjFileLowering().getSectionForMachineBasicBlock(F: MF->getFunction(),
4941 MBB, TM));
4942 CurrentSectionBeginSym = MBB.getSymbol();
4943 }
4944
4945 for (auto &Handler : Handlers)
4946 Handler->beginCodeAlignment(MBB);
4947
4948 // Emit an alignment directive for this block, if needed.
4949 const Align Alignment = MBB.getAlignment();
4950 if (Alignment != Align(1))
4951 emitAlignment(Alignment, GV: nullptr, MaxBytesToEmit: MBB.getMaxBytesForAlignment());
4952
4953 // If the block has its address taken, emit any labels that were used to
4954 // reference the block. It is possible that there is more than one label
4955 // here, because multiple LLVM BB's may have been RAUW'd to this block after
4956 // the references were generated.
4957 if (MBB.isIRBlockAddressTaken()) {
4958 if (isVerbose())
4959 OutStreamer->AddComment(T: "Block address taken");
4960
4961 BasicBlock *BB = MBB.getAddressTakenIRBlock();
4962 assert(BB && BB->hasAddressTaken() && "Missing BB");
4963 for (MCSymbol *Sym : getAddrLabelSymbolToEmit(BB))
4964 OutStreamer->emitLabel(Symbol: Sym);
4965 } else if (isVerbose() && MBB.isMachineBlockAddressTaken()) {
4966 OutStreamer->AddComment(T: "Block address taken");
4967 } else if (isVerbose() && MBB.isInlineAsmBrIndirectTarget()) {
4968 OutStreamer->AddComment(T: "Inline asm indirect target");
4969 }
4970
4971 // Print some verbose block comments.
4972 if (isVerbose()) {
4973 if (const BasicBlock *BB = MBB.getBasicBlock()) {
4974 if (BB->hasName()) {
4975 BB->printAsOperand(O&: OutStreamer->getCommentOS(),
4976 /*PrintType=*/false, M: BB->getModule());
4977 OutStreamer->getCommentOS() << '\n';
4978 }
4979 }
4980
4981 assert(MLI != nullptr && "MachineLoopInfo should has been computed");
4982 emitBasicBlockLoopComments(MBB, LI: MLI, AP: *this);
4983 }
4984
4985 // Print the main label for the block.
4986 if (shouldEmitLabelForBasicBlock(MBB)) {
4987 if (isVerbose() && MBB.hasLabelMustBeEmitted())
4988 OutStreamer->AddComment(T: "Label of block must be emitted");
4989 OutStreamer->emitLabel(Symbol: MBB.getSymbol());
4990 } else {
4991 if (isVerbose()) {
4992 // NOTE: Want this comment at start of line, don't emit with AddComment.
4993 OutStreamer->emitRawComment(T: " %bb." + Twine(MBB.getNumber()) + ":",
4994 TabPrefix: false);
4995 }
4996 }
4997
4998 if (MBB.isEHContTarget() &&
4999 ModuleExceptionModel == ExceptionHandling::WinEH) {
5000 OutStreamer->emitLabel(Symbol: MBB.getEHContSymbol());
5001 }
5002
5003 // With BB sections, each basic block must handle CFI information on its own
5004 // if it begins a section (Entry block call is handled separately, next to
5005 // beginFunction).
5006 if (MBB.isBeginSection() && !MBB.isEntryBlock()) {
5007 for (auto &Handler : Handlers)
5008 Handler->beginBasicBlockSection(MBB);
5009 for (auto &Handler : EHHandlers)
5010 Handler->beginBasicBlockSection(MBB);
5011 }
5012}
5013
5014void AsmPrinter::emitBasicBlockEnd(const MachineBasicBlock &MBB) {
5015 // Check if CFI information needs to be updated for this MBB with basic block
5016 // sections.
5017 if (MBB.isEndSection()) {
5018 for (auto &Handler : Handlers)
5019 Handler->endBasicBlockSection(MBB);
5020 for (auto &Handler : EHHandlers)
5021 Handler->endBasicBlockSection(MBB);
5022 }
5023}
5024
5025void AsmPrinter::emitVisibility(MCSymbol *Sym, unsigned Visibility,
5026 bool IsDefinition) const {
5027 MCSymbolAttr Attr = MCSA_Invalid;
5028
5029 switch (Visibility) {
5030 default: break;
5031 case GlobalValue::HiddenVisibility:
5032 if (IsDefinition)
5033 Attr = MAI.getHiddenVisibilityAttr();
5034 else
5035 Attr = MAI.getHiddenDeclarationVisibilityAttr();
5036 break;
5037 case GlobalValue::ProtectedVisibility:
5038 Attr = MAI.getProtectedVisibilityAttr();
5039 break;
5040 }
5041
5042 if (Attr != MCSA_Invalid)
5043 OutStreamer->emitSymbolAttribute(Symbol: Sym, Attribute: Attr);
5044}
5045
5046bool AsmPrinter::shouldEmitLabelForBasicBlock(
5047 const MachineBasicBlock &MBB) const {
5048 // With `-fbasic-block-sections=`, a label is needed for every non-entry block
5049 // in the labels mode (option `=labels`) and every section beginning in the
5050 // sections mode (`=all` and `=list=`).
5051 if ((MF->getTarget().Options.BBAddrMap || MBB.isBeginSection()) &&
5052 !MBB.isEntryBlock())
5053 return true;
5054 // A label is needed for any block with at least one predecessor (when that
5055 // predecessor is not the fallthrough predecessor, or if it is an EH funclet
5056 // entry, or if a label is forced).
5057 return !MBB.pred_empty() &&
5058 (!isBlockOnlyReachableByFallthrough(MBB: &MBB) || MBB.isEHFuncletEntry() ||
5059 MBB.hasLabelMustBeEmitted());
5060}
5061
5062/// isBlockOnlyReachableByFallthough - Return true if the basic block has
5063/// exactly one predecessor and the control transfer mechanism between
5064/// the predecessor and this block is a fall-through.
5065bool AsmPrinter::
5066isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
5067 // If this is a landing pad, it isn't a fall through. If it has no preds,
5068 // then nothing falls through to it.
5069 if (MBB->isEHPad() || MBB->pred_empty())
5070 return false;
5071
5072 // If there isn't exactly one predecessor, it can't be a fall through.
5073 if (MBB->pred_size() > 1)
5074 return false;
5075
5076 // The predecessor has to be immediately before this block.
5077 MachineBasicBlock *Pred = *MBB->pred_begin();
5078 if (!Pred->isLayoutSuccessor(MBB))
5079 return false;
5080
5081 // If the block is completely empty, then it definitely does fall through.
5082 if (Pred->empty())
5083 return true;
5084
5085 // Check the terminators in the previous blocks
5086 for (const auto &MI : Pred->terminators()) {
5087 // If it is not a simple branch, we are in a table somewhere.
5088 if (!MI.isBranch() || MI.isIndirectBranch())
5089 return false;
5090
5091 // If we are the operands of one of the branches, this is not a fall
5092 // through. Note that targets with delay slots will usually bundle
5093 // terminators with the delay slot instruction.
5094 for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) {
5095 if (OP->isJTI())
5096 return false;
5097 if (OP->isMBB() && OP->getMBB() == MBB)
5098 return false;
5099 }
5100 }
5101
5102 return true;
5103}
5104
5105GCMetadataPrinter *AsmPrinter::getOrCreateGCPrinter(GCStrategy &S) {
5106 if (!S.usesMetadata())
5107 return nullptr;
5108
5109 auto [GCPI, Inserted] = GCMetadataPrinters.try_emplace(Key: &S);
5110 if (!Inserted)
5111 return GCPI->second.get();
5112
5113 auto Name = S.getName();
5114
5115 for (const GCMetadataPrinterRegistry::entry &GCMetaPrinter :
5116 GCMetadataPrinterRegistry::entries())
5117 if (Name == GCMetaPrinter.getName()) {
5118 std::unique_ptr<GCMetadataPrinter> GMP = GCMetaPrinter.instantiate();
5119 GMP->S = &S;
5120 GCPI->second = std::move(GMP);
5121 return GCPI->second.get();
5122 }
5123
5124 report_fatal_error(reason: "no GCMetadataPrinter registered for GC: " + Twine(Name));
5125}
5126
5127void AsmPrinter::addAsmPrinterHandler(
5128 std::unique_ptr<AsmPrinterHandler> Handler) {
5129 Handlers.insert(I: Handlers.begin(), Elt: std::move(Handler));
5130 NumUserHandlers++;
5131}
5132
5133/// Pin vtables to this file.
5134AsmPrinterHandler::~AsmPrinterHandler() = default;
5135
5136void AsmPrinterHandler::markFunctionEnd() {}
5137
5138// In the binary's "xray_instr_map" section, an array of these function entries
5139// describes each instrumentation point. When XRay patches your code, the index
5140// into this table will be given to your handler as a patch point identifier.
5141void AsmPrinter::XRayFunctionEntry::emit(int Bytes, MCStreamer *Out) const {
5142 auto Kind8 = static_cast<uint8_t>(Kind);
5143 Out->emitBinaryData(Data: StringRef(reinterpret_cast<const char *>(&Kind8), 1));
5144 Out->emitBinaryData(
5145 Data: StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1));
5146 Out->emitBinaryData(Data: StringRef(reinterpret_cast<const char *>(&Version), 1));
5147 auto Padding = (4 * Bytes) - ((2 * Bytes) + 3);
5148 assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size");
5149 Out->emitZeros(NumBytes: Padding);
5150}
5151
5152void AsmPrinter::emitXRayTable() {
5153 if (Sleds.empty())
5154 return;
5155
5156 auto PrevSection = OutStreamer->getCurrentSectionOnly();
5157 const Function &F = MF->getFunction();
5158 MCSection *InstMap = nullptr;
5159 MCSection *FnSledIndex = nullptr;
5160 const Triple &TT = TM.getTargetTriple();
5161 // Use PC-relative addresses on all targets.
5162 if (TT.isOSBinFormatELF()) {
5163 auto LinkedToSym = static_cast<const MCSymbolELF *>(CurrentFnSym);
5164 auto Flags = ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER;
5165 StringRef GroupName;
5166 if (F.hasComdat()) {
5167 Flags |= ELF::SHF_GROUP;
5168 GroupName = F.getComdat()->getName();
5169 }
5170 InstMap = OutContext.getELFSection(Section: "xray_instr_map", Type: ELF::SHT_PROGBITS,
5171 Flags, EntrySize: 0, Group: GroupName, IsComdat: F.hasComdat(),
5172 UniqueID: MCSection::NonUniqueID, LinkedToSym);
5173
5174 if (TM.Options.XRayFunctionIndex)
5175 FnSledIndex = OutContext.getELFSection(
5176 Section: "xray_fn_idx", Type: ELF::SHT_PROGBITS, Flags, EntrySize: 0, Group: GroupName, IsComdat: F.hasComdat(),
5177 UniqueID: MCSection::NonUniqueID, LinkedToSym);
5178 } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) {
5179 InstMap = OutContext.getMachOSection(Segment: "__DATA", Section: "xray_instr_map",
5180 TypeAndAttributes: MachO::S_ATTR_LIVE_SUPPORT,
5181 K: SectionKind::getReadOnlyWithRel());
5182 if (TM.Options.XRayFunctionIndex)
5183 FnSledIndex = OutContext.getMachOSection(Segment: "__DATA", Section: "xray_fn_idx",
5184 TypeAndAttributes: MachO::S_ATTR_LIVE_SUPPORT,
5185 K: SectionKind::getReadOnly());
5186 } else {
5187 llvm_unreachable("Unsupported target");
5188 }
5189
5190 auto WordSizeBytes = MAI.getCodePointerSize();
5191
5192 // Now we switch to the instrumentation map section. Because this is done
5193 // per-function, we are able to create an index entry that will represent the
5194 // range of sleds associated with a function.
5195 auto &Ctx = OutContext;
5196 MCSymbol *SledsStart =
5197 OutContext.createLinkerPrivateSymbol(Name: "xray_sleds_start");
5198 OutStreamer->switchSection(Section: InstMap);
5199 OutStreamer->emitLabel(Symbol: SledsStart);
5200 for (const auto &Sled : Sleds) {
5201 MCSymbol *Dot = Ctx.createTempSymbol();
5202 OutStreamer->emitLabel(Symbol: Dot);
5203 OutStreamer->emitValueImpl(
5204 Value: MCBinaryExpr::createSub(LHS: MCSymbolRefExpr::create(Symbol: Sled.Sled, Ctx),
5205 RHS: MCSymbolRefExpr::create(Symbol: Dot, Ctx), Ctx),
5206 Size: WordSizeBytes);
5207 OutStreamer->emitValueImpl(
5208 Value: MCBinaryExpr::createSub(
5209 LHS: MCSymbolRefExpr::create(Symbol: CurrentFnBegin, Ctx),
5210 RHS: MCBinaryExpr::createAdd(LHS: MCSymbolRefExpr::create(Symbol: Dot, Ctx),
5211 RHS: MCConstantExpr::create(Value: WordSizeBytes, Ctx),
5212 Ctx),
5213 Ctx),
5214 Size: WordSizeBytes);
5215 Sled.emit(Bytes: WordSizeBytes, Out: OutStreamer.get());
5216 }
5217 MCSymbol *SledsEnd = OutContext.createTempSymbol(Name: "xray_sleds_end", AlwaysAddSuffix: true);
5218 OutStreamer->emitLabel(Symbol: SledsEnd);
5219
5220 // We then emit a single entry in the index per function. We use the symbols
5221 // that bound the instrumentation map as the range for a specific function.
5222 // Each entry contains 2 words and needs to be word-aligned.
5223 if (FnSledIndex) {
5224 OutStreamer->switchSection(Section: FnSledIndex);
5225 OutStreamer->emitValueToAlignment(Alignment: Align(WordSizeBytes));
5226 // For Mach-O, use an "l" symbol as the atom of this subsection. The label
5227 // difference uses a SUBTRACTOR external relocation which references the
5228 // symbol.
5229 MCSymbol *Dot = Ctx.createLinkerPrivateSymbol(Name: "xray_fn_idx");
5230 OutStreamer->emitLabel(Symbol: Dot);
5231 OutStreamer->emitValueImpl(
5232 Value: MCBinaryExpr::createSub(LHS: MCSymbolRefExpr::create(Symbol: SledsStart, Ctx),
5233 RHS: MCSymbolRefExpr::create(Symbol: Dot, Ctx), Ctx),
5234 Size: WordSizeBytes);
5235 OutStreamer->emitValueImpl(Value: MCConstantExpr::create(Value: Sleds.size(), Ctx),
5236 Size: WordSizeBytes);
5237 OutStreamer->switchSection(Section: PrevSection);
5238 }
5239 Sleds.clear();
5240}
5241
5242void AsmPrinter::recordSled(MCSymbol *Sled, const MachineInstr &MI,
5243 SledKind Kind, uint8_t Version) {
5244 const Function &F = MI.getMF()->getFunction();
5245 auto Attr = F.getFnAttribute(Kind: "function-instrument");
5246 bool LogArgs = F.hasFnAttribute(Kind: "xray-log-args");
5247 bool AlwaysInstrument =
5248 Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always";
5249 if (Kind == SledKind::FUNCTION_ENTER && LogArgs)
5250 Kind = SledKind::LOG_ARGS_ENTER;
5251 Sleds.emplace_back(Args: XRayFunctionEntry{.Sled: Sled, .Function: CurrentFnSym, .Kind: Kind,
5252 .AlwaysInstrument: AlwaysInstrument, .Fn: &F, .Version: Version});
5253}
5254
5255void AsmPrinter::emitPatchableFunctionEntries() {
5256 const Function &F = MF->getFunction();
5257 unsigned PatchableFunctionPrefix =
5258 F.getFnAttributeAsParsedInteger(Kind: "patchable-function-prefix");
5259 unsigned PatchableFunctionEntry =
5260 F.getFnAttributeAsParsedInteger(Kind: "patchable-function-entry");
5261 if (!PatchableFunctionPrefix && !PatchableFunctionEntry)
5262 return;
5263 const unsigned PointerSize = getPointerSize();
5264 if (TM.getTargetTriple().isOSBinFormatELF()) {
5265 auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC;
5266 const MCSymbolELF *LinkedToSym = nullptr;
5267 StringRef GroupName, SectionName;
5268
5269 if (F.hasFnAttribute(Kind: "patchable-function-entry-section"))
5270 SectionName = F.getFnAttribute(Kind: "patchable-function-entry-section")
5271 .getValueAsString();
5272 if (SectionName.empty())
5273 SectionName = "__patchable_function_entries";
5274
5275 // GNU as < 2.35 did not support section flag 'o'. GNU ld < 2.36 did not
5276 // support mixed SHF_LINK_ORDER and non-SHF_LINK_ORDER sections.
5277 if (MAI.useIntegratedAssembler() || MAI.binutilsIsAtLeast(Major: 2, Minor: 36)) {
5278 Flags |= ELF::SHF_LINK_ORDER;
5279 if (F.hasComdat()) {
5280 Flags |= ELF::SHF_GROUP;
5281 GroupName = F.getComdat()->getName();
5282 }
5283 LinkedToSym = static_cast<const MCSymbolELF *>(CurrentFnSym);
5284 }
5285 OutStreamer->switchSection(Section: OutContext.getELFSection(
5286 Section: SectionName, Type: ELF::SHT_PROGBITS, Flags, EntrySize: 0, Group: GroupName, IsComdat: F.hasComdat(),
5287 UniqueID: MCSection::NonUniqueID, LinkedToSym));
5288 emitAlignment(Alignment: Align(PointerSize));
5289 OutStreamer->emitSymbolValue(Sym: CurrentPatchableFunctionEntrySym, Size: PointerSize);
5290 }
5291}
5292
5293uint16_t AsmPrinter::getDwarfVersion() const {
5294 return OutStreamer->getContext().getDwarfVersion();
5295}
5296
5297void AsmPrinter::setDwarfVersion(uint16_t Version) {
5298 OutStreamer->getContext().setDwarfVersion(Version);
5299}
5300
5301bool AsmPrinter::isDwarf64() const {
5302 return OutStreamer->getContext().getDwarfFormat() == dwarf::DWARF64;
5303}
5304
5305unsigned int AsmPrinter::getDwarfOffsetByteSize() const {
5306 return dwarf::getDwarfOffsetByteSize(
5307 Format: OutStreamer->getContext().getDwarfFormat());
5308}
5309
5310dwarf::FormParams AsmPrinter::getDwarfFormParams() const {
5311 return {.Version: getDwarfVersion(), .AddrSize: uint8_t(MAI.getCodePointerSize()),
5312 .Format: OutStreamer->getContext().getDwarfFormat(),
5313 .DwarfUsesRelocationsAcrossSections: doesDwarfUseRelocationsAcrossSections()};
5314}
5315
5316unsigned int AsmPrinter::getUnitLengthFieldByteSize() const {
5317 return dwarf::getUnitLengthFieldByteSize(
5318 Format: OutStreamer->getContext().getDwarfFormat());
5319}
5320
5321std::tuple<const MCSymbol *, uint64_t, const MCSymbol *,
5322 codeview::JumpTableEntrySize>
5323AsmPrinter::getCodeViewJumpTableInfo(int JTI, const MachineInstr *BranchInstr,
5324 const MCSymbol *BranchLabel) const {
5325 const auto TLI = MF->getSubtarget().getTargetLowering();
5326 const auto BaseExpr =
5327 TLI->getPICJumpTableRelocBaseExpr(MF, JTI, Ctx&: MMI->getContext());
5328 const auto Base = &cast<MCSymbolRefExpr>(Val: BaseExpr)->getSymbol();
5329
5330 // By default, for the architectures that support CodeView,
5331 // EK_LabelDifference32 is implemented as an Int32 from the base address.
5332 return std::make_tuple(args: Base, args: 0, args&: BranchLabel,
5333 args: codeview::JumpTableEntrySize::Int32);
5334}
5335
5336void AsmPrinter::emitCOFFReplaceableFunctionData(Module &M) {
5337 const Triple &TT = M.getTargetTriple();
5338 assert(TT.isOSBinFormatCOFF());
5339
5340 bool IsTargetArm64EC = TT.isWindowsArm64EC();
5341 SmallVector<char> Buf;
5342 SmallVector<MCSymbol *> FuncOverrideDefaultSymbols;
5343 bool SwitchedToDirectiveSection = false;
5344 for (const Function &F : M.functions()) {
5345 if (F.hasFnAttribute(Kind: "loader-replaceable")) {
5346 if (!SwitchedToDirectiveSection) {
5347 OutStreamer->switchSection(
5348 Section: OutContext.getObjectFileInfo()->getDrectveSection());
5349 SwitchedToDirectiveSection = true;
5350 }
5351
5352 StringRef Name = F.getName();
5353
5354 // For hybrid-patchable targets, strip the prefix so that we can mark
5355 // the real function as replaceable.
5356 if (IsTargetArm64EC && Name.ends_with(Suffix: HybridPatchableTargetSuffix)) {
5357 Name = Name.drop_back(N: HybridPatchableTargetSuffix.size());
5358 }
5359
5360 MCSymbol *FuncOverrideSymbol =
5361 MMI->getContext().getOrCreateSymbol(Name: Name + "_$fo$");
5362 OutStreamer->beginCOFFSymbolDef(Symbol: FuncOverrideSymbol);
5363 OutStreamer->emitCOFFSymbolStorageClass(StorageClass: COFF::IMAGE_SYM_CLASS_EXTERNAL);
5364 OutStreamer->emitCOFFSymbolType(Type: COFF::IMAGE_SYM_DTYPE_NULL);
5365 OutStreamer->endCOFFSymbolDef();
5366
5367 MCSymbol *FuncOverrideDefaultSymbol =
5368 MMI->getContext().getOrCreateSymbol(Name: Name + "_$fo_default$");
5369 OutStreamer->beginCOFFSymbolDef(Symbol: FuncOverrideDefaultSymbol);
5370 OutStreamer->emitCOFFSymbolStorageClass(StorageClass: COFF::IMAGE_SYM_CLASS_EXTERNAL);
5371 OutStreamer->emitCOFFSymbolType(Type: COFF::IMAGE_SYM_DTYPE_NULL);
5372 OutStreamer->endCOFFSymbolDef();
5373 FuncOverrideDefaultSymbols.push_back(Elt: FuncOverrideDefaultSymbol);
5374
5375 OutStreamer->emitBytes(Data: (Twine(" /ALTERNATENAME:") +
5376 FuncOverrideSymbol->getName() + "=" +
5377 FuncOverrideDefaultSymbol->getName())
5378 .toStringRef(Out&: Buf));
5379 Buf.clear();
5380 }
5381 }
5382
5383 if (SwitchedToDirectiveSection)
5384 OutStreamer->popSection();
5385
5386 if (FuncOverrideDefaultSymbols.empty())
5387 return;
5388
5389 // MSVC emits the symbols for the default variables pointing at the start of
5390 // the .data section, but doesn't actually allocate any space for them. LLVM
5391 // can't do this, so have all of the variables pointing at a single byte
5392 // instead.
5393 OutStreamer->switchSection(Section: OutContext.getObjectFileInfo()->getDataSection());
5394 for (MCSymbol *Symbol : FuncOverrideDefaultSymbols) {
5395 OutStreamer->emitLabel(Symbol);
5396 }
5397 OutStreamer->emitZeros(NumBytes: 1);
5398 OutStreamer->popSection();
5399}
5400
5401void AsmPrinter::emitCOFFFeatureSymbol(Module &M) {
5402 const Triple &TT = M.getTargetTriple();
5403 assert(TT.isOSBinFormatCOFF());
5404
5405 // Emit an absolute @feat.00 symbol.
5406 MCSymbol *S = MMI->getContext().getOrCreateSymbol(Name: StringRef("@feat.00"));
5407 OutStreamer->beginCOFFSymbolDef(Symbol: S);
5408 OutStreamer->emitCOFFSymbolStorageClass(StorageClass: COFF::IMAGE_SYM_CLASS_STATIC);
5409 OutStreamer->emitCOFFSymbolType(Type: COFF::IMAGE_SYM_DTYPE_NULL);
5410 OutStreamer->endCOFFSymbolDef();
5411 int64_t Feat00Value = 0;
5412
5413 if (TT.getArch() == Triple::x86) {
5414 // According to the PE-COFF spec, the LSB of this value marks the object
5415 // for "registered SEH". This means that all SEH handler entry points
5416 // must be registered in .sxdata. Use of any unregistered handlers will
5417 // cause the process to terminate immediately. LLVM does not know how to
5418 // register any SEH handlers, so its object files should be safe.
5419 Feat00Value |= COFF::Feat00Flags::SafeSEH;
5420 }
5421
5422 if (M.getControlFlowGuardMode() == ControlFlowGuardMode::Enabled) {
5423 // Object is CFG-aware. Only set if we actually inserted the checks.
5424 Feat00Value |= COFF::Feat00Flags::GuardCF;
5425 }
5426
5427 if (M.getModuleFlag(Key: "ehcontguard")) {
5428 // Object also has EHCont.
5429 Feat00Value |= COFF::Feat00Flags::GuardEHCont;
5430 }
5431
5432 if (M.getModuleFlag(Key: "ms-kernel")) {
5433 // Object is compiled with /kernel.
5434 Feat00Value |= COFF::Feat00Flags::Kernel;
5435 }
5436
5437 OutStreamer->emitSymbolAttribute(Symbol: S, Attribute: MCSA_Global);
5438 OutStreamer->emitAssignment(
5439 Symbol: S, Value: MCConstantExpr::create(Value: Feat00Value, Ctx&: MMI->getContext()));
5440}
5441
5442namespace llvm {
5443namespace {
5444FunctionAnalysisManager &getFAM(Module &M, ModuleAnalysisManager &MAM) {
5445 return MAM.getResult<FunctionAnalysisManagerModuleProxy>(IR&: M).getManager();
5446}
5447
5448FunctionAnalysisManager &getFAM(MachineFunctionAnalysisManager &MFAM,
5449 MachineFunction &MF) {
5450 return MFAM.getResult<FunctionAnalysisManagerMachineFunctionProxy>(IR&: MF)
5451 .getManager();
5452}
5453
5454MachineFunctionAnalysisManager &getMFAM(Module &M, ModuleAnalysisManager &MAM,
5455 MachineFunction &MF) {
5456 MachineFunctionAnalysisManager &MFAM =
5457 getFAM(M, MAM)
5458 .getResult<MachineFunctionAnalysisManagerFunctionProxy>(
5459 IR&: MF.getFunction())
5460 .getManager();
5461 return MFAM;
5462}
5463} // anonymous namespace
5464
5465void setupModuleAsmPrinter(Module &M, ModuleAnalysisManager &MAM,
5466 AsmPrinter &AsmPrinter) {
5467 MachineModuleInfo &MMI = MAM.getResult<MachineModuleAnalysis>(IR&: M).getMMI();
5468 AsmPrinter.GetMMI = [&MMI]() { return &MMI; };
5469 AsmPrinter.MMI = &MMI;
5470 AsmPrinter.GetORE = [&MAM, &M](MachineFunction &MF) {
5471 return &getMFAM(M, MAM, MF)
5472 .getResult<MachineOptimizationRemarkEmitterAnalysis>(IR&: MF);
5473 };
5474 AsmPrinter.GetMDT = [&MAM, &M](MachineFunction &MF) {
5475 return &getMFAM(M, MAM, MF).getResult<MachineDominatorTreeAnalysis>(IR&: MF);
5476 };
5477 AsmPrinter.GetMLI = [&MAM, &M](MachineFunction &MF) {
5478 return &getMFAM(M, MAM, MF).getResult<MachineLoopAnalysis>(IR&: MF);
5479 };
5480 AsmPrinter.GetMBPI = [&MAM, &M](MachineFunction &MF) {
5481 return &getMFAM(M, MAM, MF).getResult<MachineBranchProbabilityAnalysis>(IR&: MF);
5482 };
5483 AsmPrinter.GetMBFI = [&MAM, &M](MachineFunction &MF) {
5484 return &getMFAM(M, MAM, MF).getResult<MachineBlockFrequencyAnalysis>(IR&: MF);
5485 };
5486 AsmPrinter.GetMBHI = [&MAM, &M](MachineFunction &MF) {
5487 return &getMFAM(M, MAM, MF).getResult<MachineBlockHashInfoAnalysis>(IR&: MF);
5488 };
5489 AsmPrinter.GetBBSPR = [&MAM, &M](MachineFunction &MF) {
5490 return getFAM(M, MAM)
5491 .getCachedResult<BasicBlockSectionsProfileReaderAnalysis>(
5492 IR&: MF.getFunction());
5493 };
5494 // TODO(boomanaiden154): Get GC working with the new pass manager.
5495 AsmPrinter.BeginGCAssembly = [](Module &M) {};
5496 AsmPrinter.FinishGCAssembly = [](Module &M) {};
5497 AsmPrinter.EmitStackMaps = [](Module &M) {};
5498 AsmPrinter.AssertDebugEHFinalized = []() {};
5499}
5500
5501void setupMachineFunctionAsmPrinter(MachineFunctionAnalysisManager &MFAM,
5502 MachineFunction &MF,
5503 AsmPrinter &AsmPrinter) {
5504 const ModuleAnalysisManagerMachineFunctionProxy::Result &MAMProxy =
5505 MFAM.getResult<ModuleAnalysisManagerMachineFunctionProxy>(IR&: MF);
5506 MachineModuleInfo &MMI =
5507 MAMProxy
5508 .getCachedResult<MachineModuleAnalysis>(IR&: *MF.getFunction().getParent())
5509 ->getMMI();
5510 AsmPrinter.GetMMI = [&MMI]() { return &MMI; };
5511 AsmPrinter.MMI = &MMI;
5512 AsmPrinter.GetORE = [&MFAM](MachineFunction &MF) {
5513 return &MFAM.getResult<MachineOptimizationRemarkEmitterAnalysis>(IR&: MF);
5514 };
5515 AsmPrinter.GetMDT = [&MFAM](MachineFunction &MF) {
5516 return &MFAM.getResult<MachineDominatorTreeAnalysis>(IR&: MF);
5517 };
5518 AsmPrinter.GetMLI = [&MFAM](MachineFunction &MF) {
5519 return &MFAM.getResult<MachineLoopAnalysis>(IR&: MF);
5520 };
5521 AsmPrinter.GetMBPI = [&MFAM](MachineFunction &MF) {
5522 return &MFAM.getResult<MachineBranchProbabilityAnalysis>(IR&: MF);
5523 };
5524 AsmPrinter.GetMBFI = [&MFAM](MachineFunction &MF) {
5525 return &MFAM.getResult<MachineBlockFrequencyAnalysis>(IR&: MF);
5526 };
5527 AsmPrinter.GetMBHI = [&MFAM](MachineFunction &MF) {
5528 return &MFAM.getResult<MachineBlockHashInfoAnalysis>(IR&: MF);
5529 };
5530 AsmPrinter.GetBBSPR = [&MFAM](MachineFunction &MF) {
5531 return getFAM(MFAM, MF)
5532 .getCachedResult<BasicBlockSectionsProfileReaderAnalysis>(
5533 IR&: MF.getFunction());
5534 };
5535 // TODO(boomanaiden154): Get GC working with the new pass manager.
5536 AsmPrinter.BeginGCAssembly = [](Module &M) {};
5537 AsmPrinter.FinishGCAssembly = [](Module &M) {};
5538 AsmPrinter.EmitStackMaps = [](Module &M) {};
5539 AsmPrinter.AssertDebugEHFinalized = []() {};
5540}
5541
5542AnalysisKey AsmPrinterAnalysis::Key;
5543
5544} // namespace llvm
5545