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