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