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