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