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