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