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