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 && GV.isDSOLocal())
487       return getSymbolWithGlobalValueBase(&GV, "$local");
488   }
489   return TM.getSymbol(&GV);
490 }
491 
492 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
493 void AsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
494   bool IsEmuTLSVar = TM.useEmulatedTLS() && GV->isThreadLocal();
495   assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) &&
496          "No emulated TLS variables in the common section");
497 
498   // Never emit TLS variable xyz in emulated TLS model.
499   // The initialization value is in __emutls_t.xyz instead of xyz.
500   if (IsEmuTLSVar)
501     return;
502 
503   if (GV->hasInitializer()) {
504     // Check to see if this is a special global used by LLVM, if so, emit it.
505     if (emitSpecialLLVMGlobal(GV))
506       return;
507 
508     // Skip the emission of global equivalents. The symbol can be emitted later
509     // on by emitGlobalGOTEquivs in case it turns out to be needed.
510     if (GlobalGOTEquivs.count(getSymbol(GV)))
511       return;
512 
513     if (isVerbose()) {
514       // When printing the control variable __emutls_v.*,
515       // we don't need to print the original TLS variable name.
516       GV->printAsOperand(OutStreamer->GetCommentOS(),
517                      /*PrintType=*/false, GV->getParent());
518       OutStreamer->GetCommentOS() << '\n';
519     }
520   }
521 
522   MCSymbol *GVSym = getSymbol(GV);
523   MCSymbol *EmittedSym = GVSym;
524 
525   // getOrCreateEmuTLSControlSym only creates the symbol with name and default
526   // attributes.
527   // GV's or GVSym's attributes will be used for the EmittedSym.
528   emitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration());
529 
530   if (!GV->hasInitializer())   // External globals require no extra code.
531     return;
532 
533   GVSym->redefineIfPossible();
534   if (GVSym->isDefined() || GVSym->isVariable())
535     OutContext.reportError(SMLoc(), "symbol '" + Twine(GVSym->getName()) +
536                                         "' is already defined");
537 
538   if (MAI->hasDotTypeDotSizeDirective())
539     OutStreamer->emitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject);
540 
541   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
542 
543   const DataLayout &DL = GV->getParent()->getDataLayout();
544   uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
545 
546   // If the alignment is specified, we *must* obey it.  Overaligning a global
547   // with a specified alignment is a prompt way to break globals emitted to
548   // sections and expected to be contiguous (e.g. ObjC metadata).
549   const Align Alignment = getGVAlignment(GV, DL);
550 
551   for (const HandlerInfo &HI : Handlers) {
552     NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
553                        HI.TimerGroupName, HI.TimerGroupDescription,
554                        TimePassesIsEnabled);
555     HI.Handler->setSymbolSize(GVSym, Size);
556   }
557 
558   // Handle common symbols
559   if (GVKind.isCommon()) {
560     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
561     // .comm _foo, 42, 4
562     const bool SupportsAlignment =
563         getObjFileLowering().getCommDirectiveSupportsAlignment();
564     OutStreamer->emitCommonSymbol(GVSym, Size,
565                                   SupportsAlignment ? Alignment.value() : 0);
566     return;
567   }
568 
569   // Determine to which section this global should be emitted.
570   MCSection *TheSection = getObjFileLowering().SectionForGlobal(GV, GVKind, TM);
571 
572   // If we have a bss global going to a section that supports the
573   // zerofill directive, do so here.
574   if (GVKind.isBSS() && MAI->hasMachoZeroFillDirective() &&
575       TheSection->isVirtualSection()) {
576     if (Size == 0)
577       Size = 1; // zerofill of 0 bytes is undefined.
578     emitLinkage(GV, GVSym);
579     // .zerofill __DATA, __bss, _foo, 400, 5
580     OutStreamer->emitZerofill(TheSection, GVSym, Size, Alignment.value());
581     return;
582   }
583 
584   // If this is a BSS local symbol and we are emitting in the BSS
585   // section use .lcomm/.comm directive.
586   if (GVKind.isBSSLocal() &&
587       getObjFileLowering().getBSSSection() == TheSection) {
588     if (Size == 0)
589       Size = 1; // .comm Foo, 0 is undefined, avoid it.
590 
591     // Use .lcomm only if it supports user-specified alignment.
592     // Otherwise, while it would still be correct to use .lcomm in some
593     // cases (e.g. when Align == 1), the external assembler might enfore
594     // some -unknown- default alignment behavior, which could cause
595     // spurious differences between external and integrated assembler.
596     // Prefer to simply fall back to .local / .comm in this case.
597     if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
598       // .lcomm _foo, 42
599       OutStreamer->emitLocalCommonSymbol(GVSym, Size, Alignment.value());
600       return;
601     }
602 
603     // .local _foo
604     OutStreamer->emitSymbolAttribute(GVSym, MCSA_Local);
605     // .comm _foo, 42, 4
606     const bool SupportsAlignment =
607         getObjFileLowering().getCommDirectiveSupportsAlignment();
608     OutStreamer->emitCommonSymbol(GVSym, Size,
609                                   SupportsAlignment ? Alignment.value() : 0);
610     return;
611   }
612 
613   // Handle thread local data for mach-o which requires us to output an
614   // additional structure of data and mangle the original symbol so that we
615   // can reference it later.
616   //
617   // TODO: This should become an "emit thread local global" method on TLOF.
618   // All of this macho specific stuff should be sunk down into TLOFMachO and
619   // stuff like "TLSExtraDataSection" should no longer be part of the parent
620   // TLOF class.  This will also make it more obvious that stuff like
621   // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
622   // specific code.
623   if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
624     // Emit the .tbss symbol
625     MCSymbol *MangSym =
626         OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
627 
628     if (GVKind.isThreadBSS()) {
629       TheSection = getObjFileLowering().getTLSBSSSection();
630       OutStreamer->emitTBSSSymbol(TheSection, MangSym, Size, Alignment.value());
631     } else if (GVKind.isThreadData()) {
632       OutStreamer->SwitchSection(TheSection);
633 
634       emitAlignment(Alignment, GV);
635       OutStreamer->emitLabel(MangSym);
636 
637       emitGlobalConstant(GV->getParent()->getDataLayout(),
638                          GV->getInitializer());
639     }
640 
641     OutStreamer->AddBlankLine();
642 
643     // Emit the variable struct for the runtime.
644     MCSection *TLVSect = getObjFileLowering().getTLSExtraDataSection();
645 
646     OutStreamer->SwitchSection(TLVSect);
647     // Emit the linkage here.
648     emitLinkage(GV, GVSym);
649     OutStreamer->emitLabel(GVSym);
650 
651     // Three pointers in size:
652     //   - __tlv_bootstrap - used to make sure support exists
653     //   - spare pointer, used when mapped by the runtime
654     //   - pointer to mangled symbol above with initializer
655     unsigned PtrSize = DL.getPointerTypeSize(GV->getType());
656     OutStreamer->emitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
657                                 PtrSize);
658     OutStreamer->emitIntValue(0, PtrSize);
659     OutStreamer->emitSymbolValue(MangSym, PtrSize);
660 
661     OutStreamer->AddBlankLine();
662     return;
663   }
664 
665   MCSymbol *EmittedInitSym = GVSym;
666 
667   OutStreamer->SwitchSection(TheSection);
668 
669   emitLinkage(GV, EmittedInitSym);
670   emitAlignment(Alignment, GV);
671 
672   OutStreamer->emitLabel(EmittedInitSym);
673   MCSymbol *LocalAlias = getSymbolPreferLocal(*GV);
674   if (LocalAlias != EmittedInitSym)
675     OutStreamer->emitLabel(LocalAlias);
676 
677   emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer());
678 
679   if (MAI->hasDotTypeDotSizeDirective())
680     // .size foo, 42
681     OutStreamer->emitELFSize(EmittedInitSym,
682                              MCConstantExpr::create(Size, OutContext));
683 
684   OutStreamer->AddBlankLine();
685 }
686 
687 /// Emit the directive and value for debug thread local expression
688 ///
689 /// \p Value - The value to emit.
690 /// \p Size - The size of the integer (in bytes) to emit.
691 void AsmPrinter::emitDebugValue(const MCExpr *Value, unsigned Size) const {
692   OutStreamer->emitValue(Value, Size);
693 }
694 
695 void AsmPrinter::emitFunctionHeaderComment() {}
696 
697 /// EmitFunctionHeader - This method emits the header for the current
698 /// function.
699 void AsmPrinter::emitFunctionHeader() {
700   const Function &F = MF->getFunction();
701 
702   if (isVerbose())
703     OutStreamer->GetCommentOS()
704         << "-- Begin function "
705         << GlobalValue::dropLLVMManglingEscape(F.getName()) << '\n';
706 
707   // Print out constants referenced by the function
708   emitConstantPool();
709 
710   // Print the 'header' of function.
711   MF->setSection(getObjFileLowering().SectionForGlobal(&F, TM));
712   OutStreamer->SwitchSection(MF->getSection());
713 
714   if (!MAI->hasVisibilityOnlyWithLinkage())
715     emitVisibility(CurrentFnSym, F.getVisibility());
716 
717   if (MAI->needsFunctionDescriptors())
718     emitLinkage(&F, CurrentFnDescSym);
719 
720   emitLinkage(&F, CurrentFnSym);
721   if (MAI->hasFunctionAlignment())
722     emitAlignment(MF->getAlignment(), &F);
723 
724   if (MAI->hasDotTypeDotSizeDirective())
725     OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
726 
727   if (F.hasFnAttribute(Attribute::Cold))
728     OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_Cold);
729 
730   if (isVerbose()) {
731     F.printAsOperand(OutStreamer->GetCommentOS(),
732                    /*PrintType=*/false, F.getParent());
733     emitFunctionHeaderComment();
734     OutStreamer->GetCommentOS() << '\n';
735   }
736 
737   // Emit the prefix data.
738   if (F.hasPrefixData()) {
739     if (MAI->hasSubsectionsViaSymbols()) {
740       // Preserving prefix data on platforms which use subsections-via-symbols
741       // is a bit tricky. Here we introduce a symbol for the prefix data
742       // and use the .alt_entry attribute to mark the function's real entry point
743       // as an alternative entry point to the prefix-data symbol.
744       MCSymbol *PrefixSym = OutContext.createLinkerPrivateTempSymbol();
745       OutStreamer->emitLabel(PrefixSym);
746 
747       emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData());
748 
749       // Emit an .alt_entry directive for the actual function symbol.
750       OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_AltEntry);
751     } else {
752       emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData());
753     }
754   }
755 
756   // Emit M NOPs for -fpatchable-function-entry=N,M where M>0. We arbitrarily
757   // place prefix data before NOPs.
758   unsigned PatchableFunctionPrefix = 0;
759   unsigned PatchableFunctionEntry = 0;
760   (void)F.getFnAttribute("patchable-function-prefix")
761       .getValueAsString()
762       .getAsInteger(10, PatchableFunctionPrefix);
763   (void)F.getFnAttribute("patchable-function-entry")
764       .getValueAsString()
765       .getAsInteger(10, PatchableFunctionEntry);
766   if (PatchableFunctionPrefix) {
767     CurrentPatchableFunctionEntrySym =
768         OutContext.createLinkerPrivateTempSymbol();
769     OutStreamer->emitLabel(CurrentPatchableFunctionEntrySym);
770     emitNops(PatchableFunctionPrefix);
771   } else if (PatchableFunctionEntry) {
772     // May be reassigned when emitting the body, to reference the label after
773     // the initial BTI (AArch64) or endbr32/endbr64 (x86).
774     CurrentPatchableFunctionEntrySym = CurrentFnBegin;
775   }
776 
777   // Emit the function descriptor. This is a virtual function to allow targets
778   // to emit their specific function descriptor. Right now it is only used by
779   // the AIX target. The PowerPC 64-bit V1 ELF target also uses function
780   // descriptors and should be converted to use this hook as well.
781   if (MAI->needsFunctionDescriptors())
782     emitFunctionDescriptor();
783 
784   // Emit the CurrentFnSym. This is a virtual function to allow targets to do
785   // their wild and crazy things as required.
786   emitFunctionEntryLabel();
787 
788   if (CurrentFnBegin) {
789     if (MAI->useAssignmentForEHBegin()) {
790       MCSymbol *CurPos = OutContext.createTempSymbol();
791       OutStreamer->emitLabel(CurPos);
792       OutStreamer->emitAssignment(CurrentFnBegin,
793                                  MCSymbolRefExpr::create(CurPos, OutContext));
794     } else {
795       OutStreamer->emitLabel(CurrentFnBegin);
796     }
797   }
798 
799   // Emit pre-function debug and/or EH information.
800   for (const HandlerInfo &HI : Handlers) {
801     NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
802                        HI.TimerGroupDescription, TimePassesIsEnabled);
803     HI.Handler->beginFunction(MF);
804   }
805 
806   // Emit the prologue data.
807   if (F.hasPrologueData())
808     emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrologueData());
809 }
810 
811 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
812 /// function.  This can be overridden by targets as required to do custom stuff.
813 void AsmPrinter::emitFunctionEntryLabel() {
814   CurrentFnSym->redefineIfPossible();
815 
816   // The function label could have already been emitted if two symbols end up
817   // conflicting due to asm renaming.  Detect this and emit an error.
818   if (CurrentFnSym->isVariable())
819     report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
820                        "' is a protected alias");
821   if (CurrentFnSym->isDefined())
822     report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
823                        "' label emitted multiple times to assembly file");
824 
825   OutStreamer->emitLabel(CurrentFnSym);
826 
827   if (TM.getTargetTriple().isOSBinFormatELF()) {
828     MCSymbol *Sym = getSymbolPreferLocal(MF->getFunction());
829     if (Sym != CurrentFnSym)
830       OutStreamer->emitLabel(Sym);
831   }
832 }
833 
834 /// emitComments - Pretty-print comments for instructions.
835 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
836   const MachineFunction *MF = MI.getMF();
837   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
838 
839   // Check for spills and reloads
840 
841   // We assume a single instruction only has a spill or reload, not
842   // both.
843   Optional<unsigned> Size;
844   if ((Size = MI.getRestoreSize(TII))) {
845     CommentOS << *Size << "-byte Reload\n";
846   } else if ((Size = MI.getFoldedRestoreSize(TII))) {
847     if (*Size)
848       CommentOS << *Size << "-byte Folded Reload\n";
849   } else if ((Size = MI.getSpillSize(TII))) {
850     CommentOS << *Size << "-byte Spill\n";
851   } else if ((Size = MI.getFoldedSpillSize(TII))) {
852     if (*Size)
853       CommentOS << *Size << "-byte Folded Spill\n";
854   }
855 
856   // Check for spill-induced copies
857   if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
858     CommentOS << " Reload Reuse\n";
859 }
860 
861 /// emitImplicitDef - This method emits the specified machine instruction
862 /// that is an implicit def.
863 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
864   Register RegNo = MI->getOperand(0).getReg();
865 
866   SmallString<128> Str;
867   raw_svector_ostream OS(Str);
868   OS << "implicit-def: "
869      << printReg(RegNo, MF->getSubtarget().getRegisterInfo());
870 
871   OutStreamer->AddComment(OS.str());
872   OutStreamer->AddBlankLine();
873 }
874 
875 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
876   std::string Str;
877   raw_string_ostream OS(Str);
878   OS << "kill:";
879   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
880     const MachineOperand &Op = MI->getOperand(i);
881     assert(Op.isReg() && "KILL instruction must have only register operands");
882     OS << ' ' << (Op.isDef() ? "def " : "killed ")
883        << printReg(Op.getReg(), AP.MF->getSubtarget().getRegisterInfo());
884   }
885   AP.OutStreamer->AddComment(OS.str());
886   AP.OutStreamer->AddBlankLine();
887 }
888 
889 /// emitDebugValueComment - This method handles the target-independent form
890 /// of DBG_VALUE, returning true if it was able to do so.  A false return
891 /// means the target will need to handle MI in EmitInstruction.
892 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
893   // This code handles only the 4-operand target-independent form.
894   if (MI->getNumOperands() != 4)
895     return false;
896 
897   SmallString<128> Str;
898   raw_svector_ostream OS(Str);
899   OS << "DEBUG_VALUE: ";
900 
901   const DILocalVariable *V = MI->getDebugVariable();
902   if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
903     StringRef Name = SP->getName();
904     if (!Name.empty())
905       OS << Name << ":";
906   }
907   OS << V->getName();
908   OS << " <- ";
909 
910   // The second operand is only an offset if it's an immediate.
911   bool MemLoc = MI->isIndirectDebugValue();
912   auto Offset = StackOffset::getFixed(MemLoc ? MI->getOperand(1).getImm() : 0);
913   const DIExpression *Expr = MI->getDebugExpression();
914   if (Expr->getNumElements()) {
915     OS << '[';
916     bool NeedSep = false;
917     for (auto Op : Expr->expr_ops()) {
918       if (NeedSep)
919         OS << ", ";
920       else
921         NeedSep = true;
922       OS << dwarf::OperationEncodingString(Op.getOp());
923       for (unsigned I = 0; I < Op.getNumArgs(); ++I)
924         OS << ' ' << Op.getArg(I);
925     }
926     OS << "] ";
927   }
928 
929   // Register or immediate value. Register 0 means undef.
930   if (MI->getDebugOperand(0).isFPImm()) {
931     APFloat APF = APFloat(MI->getDebugOperand(0).getFPImm()->getValueAPF());
932     if (MI->getDebugOperand(0).getFPImm()->getType()->isFloatTy()) {
933       OS << (double)APF.convertToFloat();
934     } else if (MI->getDebugOperand(0).getFPImm()->getType()->isDoubleTy()) {
935       OS << APF.convertToDouble();
936     } else {
937       // There is no good way to print long double.  Convert a copy to
938       // double.  Ah well, it's only a comment.
939       bool ignored;
940       APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
941                   &ignored);
942       OS << "(long double) " << APF.convertToDouble();
943     }
944   } else if (MI->getDebugOperand(0).isImm()) {
945     OS << MI->getDebugOperand(0).getImm();
946   } else if (MI->getDebugOperand(0).isCImm()) {
947     MI->getDebugOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
948   } else if (MI->getDebugOperand(0).isTargetIndex()) {
949     auto Op = MI->getDebugOperand(0);
950     OS << "!target-index(" << Op.getIndex() << "," << Op.getOffset() << ")";
951     // NOTE: Want this comment at start of line, don't emit with AddComment.
952     AP.OutStreamer->emitRawComment(OS.str());
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       Offset = NewOffset + CPE.getSizeInBytes(getDataLayout());
1976 
1977       OutStreamer->emitLabel(Sym);
1978       if (CPE.isMachineConstantPoolEntry())
1979         emitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1980       else
1981         emitGlobalConstant(getDataLayout(), CPE.Val.ConstVal);
1982     }
1983   }
1984 }
1985 
1986 // Print assembly representations of the jump tables used by the current
1987 // function.
1988 void AsmPrinter::emitJumpTableInfo() {
1989   const DataLayout &DL = MF->getDataLayout();
1990   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1991   if (!MJTI) return;
1992   if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1993   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1994   if (JT.empty()) return;
1995 
1996   // Pick the directive to use to print the jump table entries, and switch to
1997   // the appropriate section.
1998   const Function &F = MF->getFunction();
1999   const TargetLoweringObjectFile &TLOF = getObjFileLowering();
2000   bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
2001       MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32,
2002       F);
2003   if (JTInDiffSection) {
2004     // Drop it in the readonly section.
2005     MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(F, TM);
2006     OutStreamer->SwitchSection(ReadOnlySection);
2007   }
2008 
2009   emitAlignment(Align(MJTI->getEntryAlignment(DL)));
2010 
2011   // Jump tables in code sections are marked with a data_region directive
2012   // where that's supported.
2013   if (!JTInDiffSection)
2014     OutStreamer->emitDataRegion(MCDR_DataRegionJT32);
2015 
2016   for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
2017     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2018 
2019     // If this jump table was deleted, ignore it.
2020     if (JTBBs.empty()) continue;
2021 
2022     // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
2023     /// emit a .set directive for each unique entry.
2024     if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
2025         MAI->doesSetDirectiveSuppressReloc()) {
2026       SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
2027       const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
2028       const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
2029       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
2030         const MachineBasicBlock *MBB = JTBBs[ii];
2031         if (!EmittedSets.insert(MBB).second)
2032           continue;
2033 
2034         // .set LJTSet, LBB32-base
2035         const MCExpr *LHS =
2036           MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
2037         OutStreamer->emitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
2038                                     MCBinaryExpr::createSub(LHS, Base,
2039                                                             OutContext));
2040       }
2041     }
2042 
2043     // On some targets (e.g. Darwin) we want to emit two consecutive labels
2044     // before each jump table.  The first label is never referenced, but tells
2045     // the assembler and linker the extents of the jump table object.  The
2046     // second label is actually referenced by the code.
2047     if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
2048       // FIXME: This doesn't have to have any specific name, just any randomly
2049       // named and numbered local label started with 'l' would work.  Simplify
2050       // GetJTISymbol.
2051       OutStreamer->emitLabel(GetJTISymbol(JTI, true));
2052 
2053     MCSymbol* JTISymbol = GetJTISymbol(JTI);
2054     OutStreamer->emitLabel(JTISymbol);
2055 
2056     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
2057       emitJumpTableEntry(MJTI, JTBBs[ii], JTI);
2058   }
2059   if (!JTInDiffSection)
2060     OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
2061 }
2062 
2063 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
2064 /// current stream.
2065 void AsmPrinter::emitJumpTableEntry(const MachineJumpTableInfo *MJTI,
2066                                     const MachineBasicBlock *MBB,
2067                                     unsigned UID) const {
2068   assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
2069   const MCExpr *Value = nullptr;
2070   switch (MJTI->getEntryKind()) {
2071   case MachineJumpTableInfo::EK_Inline:
2072     llvm_unreachable("Cannot emit EK_Inline jump table entry");
2073   case MachineJumpTableInfo::EK_Custom32:
2074     Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
2075         MJTI, MBB, UID, OutContext);
2076     break;
2077   case MachineJumpTableInfo::EK_BlockAddress:
2078     // EK_BlockAddress - Each entry is a plain address of block, e.g.:
2079     //     .word LBB123
2080     Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
2081     break;
2082   case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
2083     // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
2084     // with a relocation as gp-relative, e.g.:
2085     //     .gprel32 LBB123
2086     MCSymbol *MBBSym = MBB->getSymbol();
2087     OutStreamer->emitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext));
2088     return;
2089   }
2090 
2091   case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
2092     // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
2093     // with a relocation as gp-relative, e.g.:
2094     //     .gpdword LBB123
2095     MCSymbol *MBBSym = MBB->getSymbol();
2096     OutStreamer->emitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext));
2097     return;
2098   }
2099 
2100   case MachineJumpTableInfo::EK_LabelDifference32: {
2101     // Each entry is the address of the block minus the address of the jump
2102     // table. This is used for PIC jump tables where gprel32 is not supported.
2103     // e.g.:
2104     //      .word LBB123 - LJTI1_2
2105     // If the .set directive avoids relocations, this is emitted as:
2106     //      .set L4_5_set_123, LBB123 - LJTI1_2
2107     //      .word L4_5_set_123
2108     if (MAI->doesSetDirectiveSuppressReloc()) {
2109       Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()),
2110                                       OutContext);
2111       break;
2112     }
2113     Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
2114     const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
2115     const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
2116     Value = MCBinaryExpr::createSub(Value, Base, OutContext);
2117     break;
2118   }
2119   }
2120 
2121   assert(Value && "Unknown entry kind!");
2122 
2123   unsigned EntrySize = MJTI->getEntrySize(getDataLayout());
2124   OutStreamer->emitValue(Value, EntrySize);
2125 }
2126 
2127 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
2128 /// special global used by LLVM.  If so, emit it and return true, otherwise
2129 /// do nothing and return false.
2130 bool AsmPrinter::emitSpecialLLVMGlobal(const GlobalVariable *GV) {
2131   if (GV->getName() == "llvm.used") {
2132     if (MAI->hasNoDeadStrip())    // No need to emit this at all.
2133       emitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
2134     return true;
2135   }
2136 
2137   // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
2138   if (GV->getSection() == "llvm.metadata" ||
2139       GV->hasAvailableExternallyLinkage())
2140     return true;
2141 
2142   if (!GV->hasAppendingLinkage()) return false;
2143 
2144   assert(GV->hasInitializer() && "Not a special LLVM global!");
2145 
2146   if (GV->getName() == "llvm.global_ctors") {
2147     emitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
2148                        /* isCtor */ true);
2149 
2150     return true;
2151   }
2152 
2153   if (GV->getName() == "llvm.global_dtors") {
2154     emitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
2155                        /* isCtor */ false);
2156 
2157     return true;
2158   }
2159 
2160   report_fatal_error("unknown special variable");
2161 }
2162 
2163 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
2164 /// global in the specified llvm.used list.
2165 void AsmPrinter::emitLLVMUsedList(const ConstantArray *InitList) {
2166   // Should be an array of 'i8*'.
2167   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
2168     const GlobalValue *GV =
2169       dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
2170     if (GV)
2171       OutStreamer->emitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
2172   }
2173 }
2174 
2175 void AsmPrinter::preprocessXXStructorList(const DataLayout &DL,
2176                                           const Constant *List,
2177                                           SmallVector<Structor, 8> &Structors) {
2178   // Should be an array of '{ i32, void ()*, i8* }' structs.  The first value is
2179   // the init priority.
2180   if (!isa<ConstantArray>(List))
2181     return;
2182 
2183   // Gather the structors in a form that's convenient for sorting by priority.
2184   for (Value *O : cast<ConstantArray>(List)->operands()) {
2185     auto *CS = cast<ConstantStruct>(O);
2186     if (CS->getOperand(1)->isNullValue())
2187       break; // Found a null terminator, skip the rest.
2188     ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
2189     if (!Priority)
2190       continue; // Malformed.
2191     Structors.push_back(Structor());
2192     Structor &S = Structors.back();
2193     S.Priority = Priority->getLimitedValue(65535);
2194     S.Func = CS->getOperand(1);
2195     if (!CS->getOperand(2)->isNullValue()) {
2196       if (TM.getTargetTriple().isOSAIX())
2197         llvm::report_fatal_error(
2198             "associated data of XXStructor list is not yet supported on AIX");
2199       S.ComdatKey =
2200           dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
2201     }
2202   }
2203 
2204   // Emit the function pointers in the target-specific order
2205   llvm::stable_sort(Structors, [](const Structor &L, const Structor &R) {
2206     return L.Priority < R.Priority;
2207   });
2208 }
2209 
2210 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
2211 /// priority.
2212 void AsmPrinter::emitXXStructorList(const DataLayout &DL, const Constant *List,
2213                                     bool IsCtor) {
2214   SmallVector<Structor, 8> Structors;
2215   preprocessXXStructorList(DL, List, Structors);
2216   if (Structors.empty())
2217     return;
2218 
2219   const Align Align = DL.getPointerPrefAlignment();
2220   for (Structor &S : Structors) {
2221     const TargetLoweringObjectFile &Obj = getObjFileLowering();
2222     const MCSymbol *KeySym = nullptr;
2223     if (GlobalValue *GV = S.ComdatKey) {
2224       if (GV->isDeclarationForLinker())
2225         // If the associated variable is not defined in this module
2226         // (it might be available_externally, or have been an
2227         // available_externally definition that was dropped by the
2228         // EliminateAvailableExternally pass), some other TU
2229         // will provide its dynamic initializer.
2230         continue;
2231 
2232       KeySym = getSymbol(GV);
2233     }
2234 
2235     MCSection *OutputSection =
2236         (IsCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
2237                 : Obj.getStaticDtorSection(S.Priority, KeySym));
2238     OutStreamer->SwitchSection(OutputSection);
2239     if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
2240       emitAlignment(Align);
2241     emitXXStructor(DL, S.Func);
2242   }
2243 }
2244 
2245 void AsmPrinter::emitModuleIdents(Module &M) {
2246   if (!MAI->hasIdentDirective())
2247     return;
2248 
2249   if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
2250     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2251       const MDNode *N = NMD->getOperand(i);
2252       assert(N->getNumOperands() == 1 &&
2253              "llvm.ident metadata entry can have only one operand");
2254       const MDString *S = cast<MDString>(N->getOperand(0));
2255       OutStreamer->emitIdent(S->getString());
2256     }
2257   }
2258 }
2259 
2260 void AsmPrinter::emitModuleCommandLines(Module &M) {
2261   MCSection *CommandLine = getObjFileLowering().getSectionForCommandLines();
2262   if (!CommandLine)
2263     return;
2264 
2265   const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
2266   if (!NMD || !NMD->getNumOperands())
2267     return;
2268 
2269   OutStreamer->PushSection();
2270   OutStreamer->SwitchSection(CommandLine);
2271   OutStreamer->emitZeros(1);
2272   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2273     const MDNode *N = NMD->getOperand(i);
2274     assert(N->getNumOperands() == 1 &&
2275            "llvm.commandline metadata entry can have only one operand");
2276     const MDString *S = cast<MDString>(N->getOperand(0));
2277     OutStreamer->emitBytes(S->getString());
2278     OutStreamer->emitZeros(1);
2279   }
2280   OutStreamer->PopSection();
2281 }
2282 
2283 //===--------------------------------------------------------------------===//
2284 // Emission and print routines
2285 //
2286 
2287 /// Emit a byte directive and value.
2288 ///
2289 void AsmPrinter::emitInt8(int Value) const { OutStreamer->emitInt8(Value); }
2290 
2291 /// Emit a short directive and value.
2292 void AsmPrinter::emitInt16(int Value) const { OutStreamer->emitInt16(Value); }
2293 
2294 /// Emit a long directive and value.
2295 void AsmPrinter::emitInt32(int Value) const { OutStreamer->emitInt32(Value); }
2296 
2297 /// Emit a long long directive and value.
2298 void AsmPrinter::emitInt64(uint64_t Value) const {
2299   OutStreamer->emitInt64(Value);
2300 }
2301 
2302 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
2303 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
2304 /// .set if it avoids relocations.
2305 void AsmPrinter::emitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
2306                                      unsigned Size) const {
2307   OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
2308 }
2309 
2310 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
2311 /// where the size in bytes of the directive is specified by Size and Label
2312 /// specifies the label.  This implicitly uses .set if it is available.
2313 void AsmPrinter::emitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
2314                                      unsigned Size,
2315                                      bool IsSectionRelative) const {
2316   if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
2317     OutStreamer->EmitCOFFSecRel32(Label, Offset);
2318     if (Size > 4)
2319       OutStreamer->emitZeros(Size - 4);
2320     return;
2321   }
2322 
2323   // Emit Label+Offset (or just Label if Offset is zero)
2324   const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
2325   if (Offset)
2326     Expr = MCBinaryExpr::createAdd(
2327         Expr, MCConstantExpr::create(Offset, OutContext), OutContext);
2328 
2329   OutStreamer->emitValue(Expr, Size);
2330 }
2331 
2332 //===----------------------------------------------------------------------===//
2333 
2334 // EmitAlignment - Emit an alignment directive to the specified power of
2335 // two boundary.  If a global value is specified, and if that global has
2336 // an explicit alignment requested, it will override the alignment request
2337 // if required for correctness.
2338 void AsmPrinter::emitAlignment(Align Alignment, const GlobalObject *GV) const {
2339   if (GV)
2340     Alignment = getGVAlignment(GV, GV->getParent()->getDataLayout(), Alignment);
2341 
2342   if (Alignment == Align(1))
2343     return; // 1-byte aligned: no need to emit alignment.
2344 
2345   if (getCurrentSection()->getKind().isText())
2346     OutStreamer->emitCodeAlignment(Alignment.value());
2347   else
2348     OutStreamer->emitValueToAlignment(Alignment.value());
2349 }
2350 
2351 //===----------------------------------------------------------------------===//
2352 // Constant emission.
2353 //===----------------------------------------------------------------------===//
2354 
2355 const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) {
2356   MCContext &Ctx = OutContext;
2357 
2358   if (CV->isNullValue() || isa<UndefValue>(CV))
2359     return MCConstantExpr::create(0, Ctx);
2360 
2361   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
2362     return MCConstantExpr::create(CI->getZExtValue(), Ctx);
2363 
2364   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
2365     return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
2366 
2367   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
2368     return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx);
2369 
2370   if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV))
2371     return getObjFileLowering().lowerDSOLocalEquivalent(Equiv, TM);
2372 
2373   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
2374   if (!CE) {
2375     llvm_unreachable("Unknown constant value to lower!");
2376   }
2377 
2378   switch (CE->getOpcode()) {
2379   case Instruction::AddrSpaceCast: {
2380     const Constant *Op = CE->getOperand(0);
2381     unsigned DstAS = CE->getType()->getPointerAddressSpace();
2382     unsigned SrcAS = Op->getType()->getPointerAddressSpace();
2383     if (TM.isNoopAddrSpaceCast(SrcAS, DstAS))
2384       return lowerConstant(Op);
2385 
2386     // Fallthrough to error.
2387     LLVM_FALLTHROUGH;
2388   }
2389   default: {
2390     // If the code isn't optimized, there may be outstanding folding
2391     // opportunities. Attempt to fold the expression using DataLayout as a
2392     // last resort before giving up.
2393     Constant *C = ConstantFoldConstant(CE, getDataLayout());
2394     if (C != CE)
2395       return lowerConstant(C);
2396 
2397     // Otherwise report the problem to the user.
2398     std::string S;
2399     raw_string_ostream OS(S);
2400     OS << "Unsupported expression in static initializer: ";
2401     CE->printAsOperand(OS, /*PrintType=*/false,
2402                    !MF ? nullptr : MF->getFunction().getParent());
2403     report_fatal_error(OS.str());
2404   }
2405   case Instruction::GetElementPtr: {
2406     // Generate a symbolic expression for the byte address
2407     APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
2408     cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
2409 
2410     const MCExpr *Base = lowerConstant(CE->getOperand(0));
2411     if (!OffsetAI)
2412       return Base;
2413 
2414     int64_t Offset = OffsetAI.getSExtValue();
2415     return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
2416                                    Ctx);
2417   }
2418 
2419   case Instruction::Trunc:
2420     // We emit the value and depend on the assembler to truncate the generated
2421     // expression properly.  This is important for differences between
2422     // blockaddress labels.  Since the two labels are in the same function, it
2423     // is reasonable to treat their delta as a 32-bit value.
2424     LLVM_FALLTHROUGH;
2425   case Instruction::BitCast:
2426     return lowerConstant(CE->getOperand(0));
2427 
2428   case Instruction::IntToPtr: {
2429     const DataLayout &DL = getDataLayout();
2430 
2431     // Handle casts to pointers by changing them into casts to the appropriate
2432     // integer type.  This promotes constant folding and simplifies this code.
2433     Constant *Op = CE->getOperand(0);
2434     Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
2435                                       false/*ZExt*/);
2436     return lowerConstant(Op);
2437   }
2438 
2439   case Instruction::PtrToInt: {
2440     const DataLayout &DL = getDataLayout();
2441 
2442     // Support only foldable casts to/from pointers that can be eliminated by
2443     // changing the pointer to the appropriately sized integer type.
2444     Constant *Op = CE->getOperand(0);
2445     Type *Ty = CE->getType();
2446 
2447     const MCExpr *OpExpr = lowerConstant(Op);
2448 
2449     // We can emit the pointer value into this slot if the slot is an
2450     // integer slot equal to the size of the pointer.
2451     //
2452     // If the pointer is larger than the resultant integer, then
2453     // as with Trunc just depend on the assembler to truncate it.
2454     if (DL.getTypeAllocSize(Ty).getFixedSize() <=
2455         DL.getTypeAllocSize(Op->getType()).getFixedSize())
2456       return OpExpr;
2457 
2458     // Otherwise the pointer is smaller than the resultant integer, mask off
2459     // the high bits so we are sure to get a proper truncation if the input is
2460     // a constant expr.
2461     unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
2462     const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
2463     return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
2464   }
2465 
2466   case Instruction::Sub: {
2467     GlobalValue *LHSGV;
2468     APInt LHSOffset;
2469     DSOLocalEquivalent *DSOEquiv;
2470     if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset,
2471                                    getDataLayout(), &DSOEquiv)) {
2472       GlobalValue *RHSGV;
2473       APInt RHSOffset;
2474       if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset,
2475                                      getDataLayout())) {
2476         const MCExpr *RelocExpr =
2477             getObjFileLowering().lowerRelativeReference(LHSGV, RHSGV, TM);
2478         if (!RelocExpr) {
2479           const MCExpr *LHSExpr =
2480               MCSymbolRefExpr::create(getSymbol(LHSGV), Ctx);
2481           if (DSOEquiv &&
2482               getObjFileLowering().supportDSOLocalEquivalentLowering())
2483             LHSExpr =
2484                 getObjFileLowering().lowerDSOLocalEquivalent(DSOEquiv, TM);
2485           RelocExpr = MCBinaryExpr::createSub(
2486               LHSExpr, MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx);
2487         }
2488         int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
2489         if (Addend != 0)
2490           RelocExpr = MCBinaryExpr::createAdd(
2491               RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx);
2492         return RelocExpr;
2493       }
2494     }
2495   }
2496   // else fallthrough
2497   LLVM_FALLTHROUGH;
2498 
2499   // The MC library also has a right-shift operator, but it isn't consistently
2500   // signed or unsigned between different targets.
2501   case Instruction::Add:
2502   case Instruction::Mul:
2503   case Instruction::SDiv:
2504   case Instruction::SRem:
2505   case Instruction::Shl:
2506   case Instruction::And:
2507   case Instruction::Or:
2508   case Instruction::Xor: {
2509     const MCExpr *LHS = lowerConstant(CE->getOperand(0));
2510     const MCExpr *RHS = lowerConstant(CE->getOperand(1));
2511     switch (CE->getOpcode()) {
2512     default: llvm_unreachable("Unknown binary operator constant cast expr");
2513     case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
2514     case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx);
2515     case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx);
2516     case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx);
2517     case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx);
2518     case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx);
2519     case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx);
2520     case Instruction::Or:  return MCBinaryExpr::createOr (LHS, RHS, Ctx);
2521     case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx);
2522     }
2523   }
2524   }
2525 }
2526 
2527 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
2528                                    AsmPrinter &AP,
2529                                    const Constant *BaseCV = nullptr,
2530                                    uint64_t Offset = 0);
2531 
2532 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
2533 static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP);
2534 
2535 /// isRepeatedByteSequence - Determine whether the given value is
2536 /// composed of a repeated sequence of identical bytes and return the
2537 /// byte value.  If it is not a repeated sequence, return -1.
2538 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
2539   StringRef Data = V->getRawDataValues();
2540   assert(!Data.empty() && "Empty aggregates should be CAZ node");
2541   char C = Data[0];
2542   for (unsigned i = 1, e = Data.size(); i != e; ++i)
2543     if (Data[i] != C) return -1;
2544   return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
2545 }
2546 
2547 /// isRepeatedByteSequence - Determine whether the given value is
2548 /// composed of a repeated sequence of identical bytes and return the
2549 /// byte value.  If it is not a repeated sequence, return -1.
2550 static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
2551   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2552     uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
2553     assert(Size % 8 == 0);
2554 
2555     // Extend the element to take zero padding into account.
2556     APInt Value = CI->getValue().zextOrSelf(Size);
2557     if (!Value.isSplat(8))
2558       return -1;
2559 
2560     return Value.zextOrTrunc(8).getZExtValue();
2561   }
2562   if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
2563     // Make sure all array elements are sequences of the same repeated
2564     // byte.
2565     assert(CA->getNumOperands() != 0 && "Should be a CAZ");
2566     Constant *Op0 = CA->getOperand(0);
2567     int Byte = isRepeatedByteSequence(Op0, DL);
2568     if (Byte == -1)
2569       return -1;
2570 
2571     // All array elements must be equal.
2572     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
2573       if (CA->getOperand(i) != Op0)
2574         return -1;
2575     return Byte;
2576   }
2577 
2578   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
2579     return isRepeatedByteSequence(CDS);
2580 
2581   return -1;
2582 }
2583 
2584 static void emitGlobalConstantDataSequential(const DataLayout &DL,
2585                                              const ConstantDataSequential *CDS,
2586                                              AsmPrinter &AP) {
2587   // See if we can aggregate this into a .fill, if so, emit it as such.
2588   int Value = isRepeatedByteSequence(CDS, DL);
2589   if (Value != -1) {
2590     uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
2591     // Don't emit a 1-byte object as a .fill.
2592     if (Bytes > 1)
2593       return AP.OutStreamer->emitFill(Bytes, Value);
2594   }
2595 
2596   // If this can be emitted with .ascii/.asciz, emit it as such.
2597   if (CDS->isString())
2598     return AP.OutStreamer->emitBytes(CDS->getAsString());
2599 
2600   // Otherwise, emit the values in successive locations.
2601   unsigned ElementByteSize = CDS->getElementByteSize();
2602   if (isa<IntegerType>(CDS->getElementType())) {
2603     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
2604       if (AP.isVerbose())
2605         AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
2606                                                  CDS->getElementAsInteger(i));
2607       AP.OutStreamer->emitIntValue(CDS->getElementAsInteger(i),
2608                                    ElementByteSize);
2609     }
2610   } else {
2611     Type *ET = CDS->getElementType();
2612     for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I)
2613       emitGlobalConstantFP(CDS->getElementAsAPFloat(I), ET, AP);
2614   }
2615 
2616   unsigned Size = DL.getTypeAllocSize(CDS->getType());
2617   unsigned EmittedSize =
2618       DL.getTypeAllocSize(CDS->getElementType()) * CDS->getNumElements();
2619   assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!");
2620   if (unsigned Padding = Size - EmittedSize)
2621     AP.OutStreamer->emitZeros(Padding);
2622 }
2623 
2624 static void emitGlobalConstantArray(const DataLayout &DL,
2625                                     const ConstantArray *CA, AsmPrinter &AP,
2626                                     const Constant *BaseCV, uint64_t Offset) {
2627   // See if we can aggregate some values.  Make sure it can be
2628   // represented as a series of bytes of the constant value.
2629   int Value = isRepeatedByteSequence(CA, DL);
2630 
2631   if (Value != -1) {
2632     uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
2633     AP.OutStreamer->emitFill(Bytes, Value);
2634   }
2635   else {
2636     for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
2637       emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset);
2638       Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
2639     }
2640   }
2641 }
2642 
2643 static void emitGlobalConstantVector(const DataLayout &DL,
2644                                      const ConstantVector *CV, AsmPrinter &AP) {
2645   for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
2646     emitGlobalConstantImpl(DL, CV->getOperand(i), AP);
2647 
2648   unsigned Size = DL.getTypeAllocSize(CV->getType());
2649   unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
2650                          CV->getType()->getNumElements();
2651   if (unsigned Padding = Size - EmittedSize)
2652     AP.OutStreamer->emitZeros(Padding);
2653 }
2654 
2655 static void emitGlobalConstantStruct(const DataLayout &DL,
2656                                      const ConstantStruct *CS, AsmPrinter &AP,
2657                                      const Constant *BaseCV, uint64_t Offset) {
2658   // Print the fields in successive locations. Pad to align if needed!
2659   unsigned Size = DL.getTypeAllocSize(CS->getType());
2660   const StructLayout *Layout = DL.getStructLayout(CS->getType());
2661   uint64_t SizeSoFar = 0;
2662   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
2663     const Constant *Field = CS->getOperand(i);
2664 
2665     // Print the actual field value.
2666     emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar);
2667 
2668     // Check if padding is needed and insert one or more 0s.
2669     uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
2670     uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
2671                         - Layout->getElementOffset(i)) - FieldSize;
2672     SizeSoFar += FieldSize + PadSize;
2673 
2674     // Insert padding - this may include padding to increase the size of the
2675     // current field up to the ABI size (if the struct is not packed) as well
2676     // as padding to ensure that the next field starts at the right offset.
2677     AP.OutStreamer->emitZeros(PadSize);
2678   }
2679   assert(SizeSoFar == Layout->getSizeInBytes() &&
2680          "Layout of constant struct may be incorrect!");
2681 }
2682 
2683 static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) {
2684   assert(ET && "Unknown float type");
2685   APInt API = APF.bitcastToAPInt();
2686 
2687   // First print a comment with what we think the original floating-point value
2688   // should have been.
2689   if (AP.isVerbose()) {
2690     SmallString<8> StrVal;
2691     APF.toString(StrVal);
2692     ET->print(AP.OutStreamer->GetCommentOS());
2693     AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n';
2694   }
2695 
2696   // Now iterate through the APInt chunks, emitting them in endian-correct
2697   // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
2698   // floats).
2699   unsigned NumBytes = API.getBitWidth() / 8;
2700   unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
2701   const uint64_t *p = API.getRawData();
2702 
2703   // PPC's long double has odd notions of endianness compared to how LLVM
2704   // handles it: p[0] goes first for *big* endian on PPC.
2705   if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) {
2706     int Chunk = API.getNumWords() - 1;
2707 
2708     if (TrailingBytes)
2709       AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk--], TrailingBytes);
2710 
2711     for (; Chunk >= 0; --Chunk)
2712       AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
2713   } else {
2714     unsigned Chunk;
2715     for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
2716       AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
2717 
2718     if (TrailingBytes)
2719       AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], TrailingBytes);
2720   }
2721 
2722   // Emit the tail padding for the long double.
2723   const DataLayout &DL = AP.getDataLayout();
2724   AP.OutStreamer->emitZeros(DL.getTypeAllocSize(ET) - DL.getTypeStoreSize(ET));
2725 }
2726 
2727 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
2728   emitGlobalConstantFP(CFP->getValueAPF(), CFP->getType(), AP);
2729 }
2730 
2731 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
2732   const DataLayout &DL = AP.getDataLayout();
2733   unsigned BitWidth = CI->getBitWidth();
2734 
2735   // Copy the value as we may massage the layout for constants whose bit width
2736   // is not a multiple of 64-bits.
2737   APInt Realigned(CI->getValue());
2738   uint64_t ExtraBits = 0;
2739   unsigned ExtraBitsSize = BitWidth & 63;
2740 
2741   if (ExtraBitsSize) {
2742     // The bit width of the data is not a multiple of 64-bits.
2743     // The extra bits are expected to be at the end of the chunk of the memory.
2744     // Little endian:
2745     // * Nothing to be done, just record the extra bits to emit.
2746     // Big endian:
2747     // * Record the extra bits to emit.
2748     // * Realign the raw data to emit the chunks of 64-bits.
2749     if (DL.isBigEndian()) {
2750       // Basically the structure of the raw data is a chunk of 64-bits cells:
2751       //    0        1         BitWidth / 64
2752       // [chunk1][chunk2] ... [chunkN].
2753       // The most significant chunk is chunkN and it should be emitted first.
2754       // However, due to the alignment issue chunkN contains useless bits.
2755       // Realign the chunks so that they contain only useful information:
2756       // ExtraBits     0       1       (BitWidth / 64) - 1
2757       //       chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
2758       ExtraBitsSize = alignTo(ExtraBitsSize, 8);
2759       ExtraBits = Realigned.getRawData()[0] &
2760         (((uint64_t)-1) >> (64 - ExtraBitsSize));
2761       Realigned.lshrInPlace(ExtraBitsSize);
2762     } else
2763       ExtraBits = Realigned.getRawData()[BitWidth / 64];
2764   }
2765 
2766   // We don't expect assemblers to support integer data directives
2767   // for more than 64 bits, so we emit the data in at most 64-bit
2768   // quantities at a time.
2769   const uint64_t *RawData = Realigned.getRawData();
2770   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
2771     uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
2772     AP.OutStreamer->emitIntValue(Val, 8);
2773   }
2774 
2775   if (ExtraBitsSize) {
2776     // Emit the extra bits after the 64-bits chunks.
2777 
2778     // Emit a directive that fills the expected size.
2779     uint64_t Size = AP.getDataLayout().getTypeStoreSize(CI->getType());
2780     Size -= (BitWidth / 64) * 8;
2781     assert(Size && Size * 8 >= ExtraBitsSize &&
2782            (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
2783            == ExtraBits && "Directive too small for extra bits.");
2784     AP.OutStreamer->emitIntValue(ExtraBits, Size);
2785   }
2786 }
2787 
2788 /// Transform a not absolute MCExpr containing a reference to a GOT
2789 /// equivalent global, by a target specific GOT pc relative access to the
2790 /// final symbol.
2791 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
2792                                          const Constant *BaseCst,
2793                                          uint64_t Offset) {
2794   // The global @foo below illustrates a global that uses a got equivalent.
2795   //
2796   //  @bar = global i32 42
2797   //  @gotequiv = private unnamed_addr constant i32* @bar
2798   //  @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
2799   //                             i64 ptrtoint (i32* @foo to i64))
2800   //                        to i32)
2801   //
2802   // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
2803   // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
2804   // form:
2805   //
2806   //  foo = cstexpr, where
2807   //    cstexpr := <gotequiv> - "." + <cst>
2808   //    cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
2809   //
2810   // After canonicalization by evaluateAsRelocatable `ME` turns into:
2811   //
2812   //  cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
2813   //    gotpcrelcst := <offset from @foo base> + <cst>
2814   MCValue MV;
2815   if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
2816     return;
2817   const MCSymbolRefExpr *SymA = MV.getSymA();
2818   if (!SymA)
2819     return;
2820 
2821   // Check that GOT equivalent symbol is cached.
2822   const MCSymbol *GOTEquivSym = &SymA->getSymbol();
2823   if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
2824     return;
2825 
2826   const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
2827   if (!BaseGV)
2828     return;
2829 
2830   // Check for a valid base symbol
2831   const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
2832   const MCSymbolRefExpr *SymB = MV.getSymB();
2833 
2834   if (!SymB || BaseSym != &SymB->getSymbol())
2835     return;
2836 
2837   // Make sure to match:
2838   //
2839   //    gotpcrelcst := <offset from @foo base> + <cst>
2840   //
2841   // If gotpcrelcst is positive it means that we can safely fold the pc rel
2842   // displacement into the GOTPCREL. We can also can have an extra offset <cst>
2843   // if the target knows how to encode it.
2844   int64_t GOTPCRelCst = Offset + MV.getConstant();
2845   if (GOTPCRelCst < 0)
2846     return;
2847   if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
2848     return;
2849 
2850   // Emit the GOT PC relative to replace the got equivalent global, i.e.:
2851   //
2852   //  bar:
2853   //    .long 42
2854   //  gotequiv:
2855   //    .quad bar
2856   //  foo:
2857   //    .long gotequiv - "." + <cst>
2858   //
2859   // is replaced by the target specific equivalent to:
2860   //
2861   //  bar:
2862   //    .long 42
2863   //  foo:
2864   //    .long bar@GOTPCREL+<gotpcrelcst>
2865   AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
2866   const GlobalVariable *GV = Result.first;
2867   int NumUses = (int)Result.second;
2868   const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
2869   const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
2870   *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel(
2871       FinalGV, FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
2872 
2873   // Update GOT equivalent usage information
2874   --NumUses;
2875   if (NumUses >= 0)
2876     AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
2877 }
2878 
2879 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
2880                                    AsmPrinter &AP, const Constant *BaseCV,
2881                                    uint64_t Offset) {
2882   uint64_t Size = DL.getTypeAllocSize(CV->getType());
2883 
2884   // Globals with sub-elements such as combinations of arrays and structs
2885   // are handled recursively by emitGlobalConstantImpl. Keep track of the
2886   // constant symbol base and the current position with BaseCV and Offset.
2887   if (!BaseCV && CV->hasOneUse())
2888     BaseCV = dyn_cast<Constant>(CV->user_back());
2889 
2890   if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
2891     return AP.OutStreamer->emitZeros(Size);
2892 
2893   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
2894     const uint64_t StoreSize = DL.getTypeStoreSize(CV->getType());
2895 
2896     if (StoreSize <= 8) {
2897       if (AP.isVerbose())
2898         AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
2899                                                  CI->getZExtValue());
2900       AP.OutStreamer->emitIntValue(CI->getZExtValue(), StoreSize);
2901     } else {
2902       emitGlobalConstantLargeInt(CI, AP);
2903     }
2904 
2905     // Emit tail padding if needed
2906     if (Size != StoreSize)
2907       AP.OutStreamer->emitZeros(Size - StoreSize);
2908 
2909     return;
2910   }
2911 
2912   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
2913     return emitGlobalConstantFP(CFP, AP);
2914 
2915   if (isa<ConstantPointerNull>(CV)) {
2916     AP.OutStreamer->emitIntValue(0, Size);
2917     return;
2918   }
2919 
2920   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
2921     return emitGlobalConstantDataSequential(DL, CDS, AP);
2922 
2923   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
2924     return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset);
2925 
2926   if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
2927     return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset);
2928 
2929   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
2930     // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
2931     // vectors).
2932     if (CE->getOpcode() == Instruction::BitCast)
2933       return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
2934 
2935     if (Size > 8) {
2936       // If the constant expression's size is greater than 64-bits, then we have
2937       // to emit the value in chunks. Try to constant fold the value and emit it
2938       // that way.
2939       Constant *New = ConstantFoldConstant(CE, DL);
2940       if (New != CE)
2941         return emitGlobalConstantImpl(DL, New, AP);
2942     }
2943   }
2944 
2945   if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
2946     return emitGlobalConstantVector(DL, V, AP);
2947 
2948   // Otherwise, it must be a ConstantExpr.  Lower it to an MCExpr, then emit it
2949   // thread the streamer with EmitValue.
2950   const MCExpr *ME = AP.lowerConstant(CV);
2951 
2952   // Since lowerConstant already folded and got rid of all IR pointer and
2953   // integer casts, detect GOT equivalent accesses by looking into the MCExpr
2954   // directly.
2955   if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel())
2956     handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
2957 
2958   AP.OutStreamer->emitValue(ME, Size);
2959 }
2960 
2961 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
2962 void AsmPrinter::emitGlobalConstant(const DataLayout &DL, const Constant *CV) {
2963   uint64_t Size = DL.getTypeAllocSize(CV->getType());
2964   if (Size)
2965     emitGlobalConstantImpl(DL, CV, *this);
2966   else if (MAI->hasSubsectionsViaSymbols()) {
2967     // If the global has zero size, emit a single byte so that two labels don't
2968     // look like they are at the same location.
2969     OutStreamer->emitIntValue(0, 1);
2970   }
2971 }
2972 
2973 void AsmPrinter::emitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
2974   // Target doesn't support this yet!
2975   llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
2976 }
2977 
2978 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
2979   if (Offset > 0)
2980     OS << '+' << Offset;
2981   else if (Offset < 0)
2982     OS << Offset;
2983 }
2984 
2985 void AsmPrinter::emitNops(unsigned N) {
2986   MCInst Nop;
2987   MF->getSubtarget().getInstrInfo()->getNoop(Nop);
2988   for (; N; --N)
2989     EmitToStreamer(*OutStreamer, Nop);
2990 }
2991 
2992 //===----------------------------------------------------------------------===//
2993 // Symbol Lowering Routines.
2994 //===----------------------------------------------------------------------===//
2995 
2996 MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const {
2997   return OutContext.createTempSymbol(Name, true);
2998 }
2999 
3000 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
3001   return MMI->getAddrLabelSymbol(BA->getBasicBlock());
3002 }
3003 
3004 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
3005   return MMI->getAddrLabelSymbol(BB);
3006 }
3007 
3008 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
3009 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
3010   if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment()) {
3011     const MachineConstantPoolEntry &CPE =
3012         MF->getConstantPool()->getConstants()[CPID];
3013     if (!CPE.isMachineConstantPoolEntry()) {
3014       const DataLayout &DL = MF->getDataLayout();
3015       SectionKind Kind = CPE.getSectionKind(&DL);
3016       const Constant *C = CPE.Val.ConstVal;
3017       Align Alignment = CPE.Alignment;
3018       if (const MCSectionCOFF *S = dyn_cast<MCSectionCOFF>(
3019               getObjFileLowering().getSectionForConstant(DL, Kind, C,
3020                                                          Alignment))) {
3021         if (MCSymbol *Sym = S->getCOMDATSymbol()) {
3022           if (Sym->isUndefined())
3023             OutStreamer->emitSymbolAttribute(Sym, MCSA_Global);
3024           return Sym;
3025         }
3026       }
3027     }
3028   }
3029 
3030   const DataLayout &DL = getDataLayout();
3031   return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
3032                                       "CPI" + Twine(getFunctionNumber()) + "_" +
3033                                       Twine(CPID));
3034 }
3035 
3036 /// GetJTISymbol - Return the symbol for the specified jump table entry.
3037 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
3038   return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
3039 }
3040 
3041 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
3042 /// FIXME: privatize to AsmPrinter.
3043 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
3044   const DataLayout &DL = getDataLayout();
3045   return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
3046                                       Twine(getFunctionNumber()) + "_" +
3047                                       Twine(UID) + "_set_" + Twine(MBBID));
3048 }
3049 
3050 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
3051                                                    StringRef Suffix) const {
3052   return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, TM);
3053 }
3054 
3055 /// Return the MCSymbol for the specified ExternalSymbol.
3056 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
3057   SmallString<60> NameStr;
3058   Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout());
3059   return OutContext.getOrCreateSymbol(NameStr);
3060 }
3061 
3062 /// PrintParentLoopComment - Print comments about parent loops of this one.
3063 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
3064                                    unsigned FunctionNumber) {
3065   if (!Loop) return;
3066   PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
3067   OS.indent(Loop->getLoopDepth()*2)
3068     << "Parent Loop BB" << FunctionNumber << "_"
3069     << Loop->getHeader()->getNumber()
3070     << " Depth=" << Loop->getLoopDepth() << '\n';
3071 }
3072 
3073 /// PrintChildLoopComment - Print comments about child loops within
3074 /// the loop for this basic block, with nesting.
3075 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
3076                                   unsigned FunctionNumber) {
3077   // Add child loop information
3078   for (const MachineLoop *CL : *Loop) {
3079     OS.indent(CL->getLoopDepth()*2)
3080       << "Child Loop BB" << FunctionNumber << "_"
3081       << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
3082       << '\n';
3083     PrintChildLoopComment(OS, CL, FunctionNumber);
3084   }
3085 }
3086 
3087 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
3088 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
3089                                        const MachineLoopInfo *LI,
3090                                        const AsmPrinter &AP) {
3091   // Add loop depth information
3092   const MachineLoop *Loop = LI->getLoopFor(&MBB);
3093   if (!Loop) return;
3094 
3095   MachineBasicBlock *Header = Loop->getHeader();
3096   assert(Header && "No header for loop");
3097 
3098   // If this block is not a loop header, just print out what is the loop header
3099   // and return.
3100   if (Header != &MBB) {
3101     AP.OutStreamer->AddComment("  in Loop: Header=BB" +
3102                                Twine(AP.getFunctionNumber())+"_" +
3103                                Twine(Loop->getHeader()->getNumber())+
3104                                " Depth="+Twine(Loop->getLoopDepth()));
3105     return;
3106   }
3107 
3108   // Otherwise, it is a loop header.  Print out information about child and
3109   // parent loops.
3110   raw_ostream &OS = AP.OutStreamer->GetCommentOS();
3111 
3112   PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
3113 
3114   OS << "=>";
3115   OS.indent(Loop->getLoopDepth()*2-2);
3116 
3117   OS << "This ";
3118   if (Loop->isInnermost())
3119     OS << "Inner ";
3120   OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
3121 
3122   PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
3123 }
3124 
3125 /// emitBasicBlockStart - This method prints the label for the specified
3126 /// MachineBasicBlock, an alignment (if present) and a comment describing
3127 /// it if appropriate.
3128 void AsmPrinter::emitBasicBlockStart(const MachineBasicBlock &MBB) {
3129   // End the previous funclet and start a new one.
3130   if (MBB.isEHFuncletEntry()) {
3131     for (const HandlerInfo &HI : Handlers) {
3132       HI.Handler->endFunclet();
3133       HI.Handler->beginFunclet(MBB);
3134     }
3135   }
3136 
3137   // Emit an alignment directive for this block, if needed.
3138   const Align Alignment = MBB.getAlignment();
3139   if (Alignment != Align(1))
3140     emitAlignment(Alignment);
3141 
3142   // Switch to a new section if this basic block must begin a section. The
3143   // entry block is always placed in the function section and is handled
3144   // separately.
3145   if (MBB.isBeginSection() && !MBB.isEntryBlock()) {
3146     OutStreamer->SwitchSection(
3147         getObjFileLowering().getSectionForMachineBasicBlock(MF->getFunction(),
3148                                                             MBB, TM));
3149     CurrentSectionBeginSym = MBB.getSymbol();
3150   }
3151 
3152   // If the block has its address taken, emit any labels that were used to
3153   // reference the block.  It is possible that there is more than one label
3154   // here, because multiple LLVM BB's may have been RAUW'd to this block after
3155   // the references were generated.
3156   if (MBB.hasAddressTaken()) {
3157     const BasicBlock *BB = MBB.getBasicBlock();
3158     if (isVerbose())
3159       OutStreamer->AddComment("Block address taken");
3160 
3161     // MBBs can have their address taken as part of CodeGen without having
3162     // their corresponding BB's address taken in IR
3163     if (BB->hasAddressTaken())
3164       for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB))
3165         OutStreamer->emitLabel(Sym);
3166   }
3167 
3168   // Print some verbose block comments.
3169   if (isVerbose()) {
3170     if (const BasicBlock *BB = MBB.getBasicBlock()) {
3171       if (BB->hasName()) {
3172         BB->printAsOperand(OutStreamer->GetCommentOS(),
3173                            /*PrintType=*/false, BB->getModule());
3174         OutStreamer->GetCommentOS() << '\n';
3175       }
3176     }
3177 
3178     assert(MLI != nullptr && "MachineLoopInfo should has been computed");
3179     emitBasicBlockLoopComments(MBB, MLI, *this);
3180   }
3181 
3182   // Print the main label for the block.
3183   if (shouldEmitLabelForBasicBlock(MBB)) {
3184     if (isVerbose() && MBB.hasLabelMustBeEmitted())
3185       OutStreamer->AddComment("Label of block must be emitted");
3186     OutStreamer->emitLabel(MBB.getSymbol());
3187   } else {
3188     if (isVerbose()) {
3189       // NOTE: Want this comment at start of line, don't emit with AddComment.
3190       OutStreamer->emitRawComment(" %bb." + Twine(MBB.getNumber()) + ":",
3191                                   false);
3192     }
3193   }
3194 
3195   // With BB sections, each basic block must handle CFI information on its own
3196   // if it begins a section (Entry block is handled separately by
3197   // AsmPrinterHandler::beginFunction).
3198   if (MBB.isBeginSection() && !MBB.isEntryBlock())
3199     for (const HandlerInfo &HI : Handlers)
3200       HI.Handler->beginBasicBlock(MBB);
3201 }
3202 
3203 void AsmPrinter::emitBasicBlockEnd(const MachineBasicBlock &MBB) {
3204   // Check if CFI information needs to be updated for this MBB with basic block
3205   // sections.
3206   if (MBB.isEndSection())
3207     for (const HandlerInfo &HI : Handlers)
3208       HI.Handler->endBasicBlock(MBB);
3209 }
3210 
3211 void AsmPrinter::emitVisibility(MCSymbol *Sym, unsigned Visibility,
3212                                 bool IsDefinition) const {
3213   MCSymbolAttr Attr = MCSA_Invalid;
3214 
3215   switch (Visibility) {
3216   default: break;
3217   case GlobalValue::HiddenVisibility:
3218     if (IsDefinition)
3219       Attr = MAI->getHiddenVisibilityAttr();
3220     else
3221       Attr = MAI->getHiddenDeclarationVisibilityAttr();
3222     break;
3223   case GlobalValue::ProtectedVisibility:
3224     Attr = MAI->getProtectedVisibilityAttr();
3225     break;
3226   }
3227 
3228   if (Attr != MCSA_Invalid)
3229     OutStreamer->emitSymbolAttribute(Sym, Attr);
3230 }
3231 
3232 bool AsmPrinter::shouldEmitLabelForBasicBlock(
3233     const MachineBasicBlock &MBB) const {
3234   // With `-fbasic-block-sections=`, a label is needed for every non-entry block
3235   // in the labels mode (option `=labels`) and every section beginning in the
3236   // sections mode (`=all` and `=list=`).
3237   if ((MF->hasBBLabels() || MBB.isBeginSection()) && !MBB.isEntryBlock())
3238     return true;
3239   // A label is needed for any block with at least one predecessor (when that
3240   // predecessor is not the fallthrough predecessor, or if it is an EH funclet
3241   // entry, or if a label is forced).
3242   return !MBB.pred_empty() &&
3243          (!isBlockOnlyReachableByFallthrough(&MBB) || MBB.isEHFuncletEntry() ||
3244           MBB.hasLabelMustBeEmitted());
3245 }
3246 
3247 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
3248 /// exactly one predecessor and the control transfer mechanism between
3249 /// the predecessor and this block is a fall-through.
3250 bool AsmPrinter::
3251 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
3252   // If this is a landing pad, it isn't a fall through.  If it has no preds,
3253   // then nothing falls through to it.
3254   if (MBB->isEHPad() || MBB->pred_empty())
3255     return false;
3256 
3257   // If there isn't exactly one predecessor, it can't be a fall through.
3258   if (MBB->pred_size() > 1)
3259     return false;
3260 
3261   // The predecessor has to be immediately before this block.
3262   MachineBasicBlock *Pred = *MBB->pred_begin();
3263   if (!Pred->isLayoutSuccessor(MBB))
3264     return false;
3265 
3266   // If the block is completely empty, then it definitely does fall through.
3267   if (Pred->empty())
3268     return true;
3269 
3270   // Check the terminators in the previous blocks
3271   for (const auto &MI : Pred->terminators()) {
3272     // If it is not a simple branch, we are in a table somewhere.
3273     if (!MI.isBranch() || MI.isIndirectBranch())
3274       return false;
3275 
3276     // If we are the operands of one of the branches, this is not a fall
3277     // through. Note that targets with delay slots will usually bundle
3278     // terminators with the delay slot instruction.
3279     for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) {
3280       if (OP->isJTI())
3281         return false;
3282       if (OP->isMBB() && OP->getMBB() == MBB)
3283         return false;
3284     }
3285   }
3286 
3287   return true;
3288 }
3289 
3290 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
3291   if (!S.usesMetadata())
3292     return nullptr;
3293 
3294   gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
3295   gcp_map_type::iterator GCPI = GCMap.find(&S);
3296   if (GCPI != GCMap.end())
3297     return GCPI->second.get();
3298 
3299   auto Name = S.getName();
3300 
3301   for (const GCMetadataPrinterRegistry::entry &GCMetaPrinter :
3302        GCMetadataPrinterRegistry::entries())
3303     if (Name == GCMetaPrinter.getName()) {
3304       std::unique_ptr<GCMetadataPrinter> GMP = GCMetaPrinter.instantiate();
3305       GMP->S = &S;
3306       auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
3307       return IterBool.first->second.get();
3308     }
3309 
3310   report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
3311 }
3312 
3313 void AsmPrinter::emitStackMaps(StackMaps &SM) {
3314   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
3315   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
3316   bool NeedsDefault = false;
3317   if (MI->begin() == MI->end())
3318     // No GC strategy, use the default format.
3319     NeedsDefault = true;
3320   else
3321     for (auto &I : *MI) {
3322       if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
3323         if (MP->emitStackMaps(SM, *this))
3324           continue;
3325       // The strategy doesn't have printer or doesn't emit custom stack maps.
3326       // Use the default format.
3327       NeedsDefault = true;
3328     }
3329 
3330   if (NeedsDefault)
3331     SM.serializeToStackMapSection();
3332 }
3333 
3334 /// Pin vtable to this file.
3335 AsmPrinterHandler::~AsmPrinterHandler() = default;
3336 
3337 void AsmPrinterHandler::markFunctionEnd() {}
3338 
3339 // In the binary's "xray_instr_map" section, an array of these function entries
3340 // describes each instrumentation point.  When XRay patches your code, the index
3341 // into this table will be given to your handler as a patch point identifier.
3342 void AsmPrinter::XRayFunctionEntry::emit(int Bytes, MCStreamer *Out) const {
3343   auto Kind8 = static_cast<uint8_t>(Kind);
3344   Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8), 1));
3345   Out->emitBinaryData(
3346       StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1));
3347   Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Version), 1));
3348   auto Padding = (4 * Bytes) - ((2 * Bytes) + 3);
3349   assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size");
3350   Out->emitZeros(Padding);
3351 }
3352 
3353 void AsmPrinter::emitXRayTable() {
3354   if (Sleds.empty())
3355     return;
3356 
3357   auto PrevSection = OutStreamer->getCurrentSectionOnly();
3358   const Function &F = MF->getFunction();
3359   MCSection *InstMap = nullptr;
3360   MCSection *FnSledIndex = nullptr;
3361   const Triple &TT = TM.getTargetTriple();
3362   // Use PC-relative addresses on all targets.
3363   if (TT.isOSBinFormatELF()) {
3364     auto LinkedToSym = cast<MCSymbolELF>(CurrentFnSym);
3365     auto Flags = ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER;
3366     StringRef GroupName;
3367     if (F.hasComdat()) {
3368       Flags |= ELF::SHF_GROUP;
3369       GroupName = F.getComdat()->getName();
3370     }
3371     InstMap = OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS,
3372                                        Flags, 0, GroupName,
3373                                        MCSection::NonUniqueID, LinkedToSym);
3374 
3375     if (!TM.Options.XRayOmitFunctionIndex)
3376       FnSledIndex = OutContext.getELFSection(
3377           "xray_fn_idx", ELF::SHT_PROGBITS, Flags | ELF::SHF_WRITE, 0,
3378           GroupName, MCSection::NonUniqueID, LinkedToSym);
3379   } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) {
3380     InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map", 0,
3381                                          SectionKind::getReadOnlyWithRel());
3382     if (!TM.Options.XRayOmitFunctionIndex)
3383       FnSledIndex = OutContext.getMachOSection(
3384           "__DATA", "xray_fn_idx", 0, SectionKind::getReadOnlyWithRel());
3385   } else {
3386     llvm_unreachable("Unsupported target");
3387   }
3388 
3389   auto WordSizeBytes = MAI->getCodePointerSize();
3390 
3391   // Now we switch to the instrumentation map section. Because this is done
3392   // per-function, we are able to create an index entry that will represent the
3393   // range of sleds associated with a function.
3394   auto &Ctx = OutContext;
3395   MCSymbol *SledsStart = OutContext.createTempSymbol("xray_sleds_start", true);
3396   OutStreamer->SwitchSection(InstMap);
3397   OutStreamer->emitLabel(SledsStart);
3398   for (const auto &Sled : Sleds) {
3399     MCSymbol *Dot = Ctx.createTempSymbol();
3400     OutStreamer->emitLabel(Dot);
3401     OutStreamer->emitValueImpl(
3402         MCBinaryExpr::createSub(MCSymbolRefExpr::create(Sled.Sled, Ctx),
3403                                 MCSymbolRefExpr::create(Dot, Ctx), Ctx),
3404         WordSizeBytes);
3405     OutStreamer->emitValueImpl(
3406         MCBinaryExpr::createSub(
3407             MCSymbolRefExpr::create(CurrentFnBegin, Ctx),
3408             MCBinaryExpr::createAdd(MCSymbolRefExpr::create(Dot, Ctx),
3409                                     MCConstantExpr::create(WordSizeBytes, Ctx),
3410                                     Ctx),
3411             Ctx),
3412         WordSizeBytes);
3413     Sled.emit(WordSizeBytes, OutStreamer.get());
3414   }
3415   MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_sleds_end", true);
3416   OutStreamer->emitLabel(SledsEnd);
3417 
3418   // We then emit a single entry in the index per function. We use the symbols
3419   // that bound the instrumentation map as the range for a specific function.
3420   // Each entry here will be 2 * word size aligned, as we're writing down two
3421   // pointers. This should work for both 32-bit and 64-bit platforms.
3422   if (FnSledIndex) {
3423     OutStreamer->SwitchSection(FnSledIndex);
3424     OutStreamer->emitCodeAlignment(2 * WordSizeBytes);
3425     OutStreamer->emitSymbolValue(SledsStart, WordSizeBytes, false);
3426     OutStreamer->emitSymbolValue(SledsEnd, WordSizeBytes, false);
3427     OutStreamer->SwitchSection(PrevSection);
3428   }
3429   Sleds.clear();
3430 }
3431 
3432 void AsmPrinter::recordSled(MCSymbol *Sled, const MachineInstr &MI,
3433                             SledKind Kind, uint8_t Version) {
3434   const Function &F = MI.getMF()->getFunction();
3435   auto Attr = F.getFnAttribute("function-instrument");
3436   bool LogArgs = F.hasFnAttribute("xray-log-args");
3437   bool AlwaysInstrument =
3438     Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always";
3439   if (Kind == SledKind::FUNCTION_ENTER && LogArgs)
3440     Kind = SledKind::LOG_ARGS_ENTER;
3441   Sleds.emplace_back(XRayFunctionEntry{Sled, CurrentFnSym, Kind,
3442                                        AlwaysInstrument, &F, Version});
3443 }
3444 
3445 void AsmPrinter::emitPatchableFunctionEntries() {
3446   const Function &F = MF->getFunction();
3447   unsigned PatchableFunctionPrefix = 0, PatchableFunctionEntry = 0;
3448   (void)F.getFnAttribute("patchable-function-prefix")
3449       .getValueAsString()
3450       .getAsInteger(10, PatchableFunctionPrefix);
3451   (void)F.getFnAttribute("patchable-function-entry")
3452       .getValueAsString()
3453       .getAsInteger(10, PatchableFunctionEntry);
3454   if (!PatchableFunctionPrefix && !PatchableFunctionEntry)
3455     return;
3456   const unsigned PointerSize = getPointerSize();
3457   if (TM.getTargetTriple().isOSBinFormatELF()) {
3458     auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC;
3459     const MCSymbolELF *LinkedToSym = nullptr;
3460     StringRef GroupName;
3461 
3462     // GNU as < 2.35 did not support section flag 'o'. Use SHF_LINK_ORDER only
3463     // if we are using the integrated assembler.
3464     if (MAI->useIntegratedAssembler()) {
3465       Flags |= ELF::SHF_LINK_ORDER;
3466       if (F.hasComdat()) {
3467         Flags |= ELF::SHF_GROUP;
3468         GroupName = F.getComdat()->getName();
3469       }
3470       LinkedToSym = cast<MCSymbolELF>(CurrentFnSym);
3471     }
3472     OutStreamer->SwitchSection(OutContext.getELFSection(
3473         "__patchable_function_entries", ELF::SHT_PROGBITS, Flags, 0, GroupName,
3474         MCSection::NonUniqueID, LinkedToSym));
3475     emitAlignment(Align(PointerSize));
3476     OutStreamer->emitSymbolValue(CurrentPatchableFunctionEntrySym, PointerSize);
3477   }
3478 }
3479 
3480 uint16_t AsmPrinter::getDwarfVersion() const {
3481   return OutStreamer->getContext().getDwarfVersion();
3482 }
3483 
3484 void AsmPrinter::setDwarfVersion(uint16_t Version) {
3485   OutStreamer->getContext().setDwarfVersion(Version);
3486 }
3487 
3488 bool AsmPrinter::isDwarf64() const {
3489   return OutStreamer->getContext().getDwarfFormat() == dwarf::DWARF64;
3490 }
3491 
3492 unsigned int AsmPrinter::getDwarfOffsetByteSize() const {
3493   return dwarf::getDwarfOffsetByteSize(
3494       OutStreamer->getContext().getDwarfFormat());
3495 }
3496 
3497 unsigned int AsmPrinter::getUnitLengthFieldByteSize() const {
3498   return dwarf::getUnitLengthFieldByteSize(
3499       OutStreamer->getContext().getDwarfFormat());
3500 }
3501