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