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