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