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