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