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