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