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