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