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