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