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