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