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