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