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   // Emit .note.GNU-split-stack and .note.GNU-no-split-stack sections if
1386   // split-stack is used.
1387   if (TM.getTargetTriple().isOSBinFormatELF() && MMI->hasSplitStack()) {
1388     OutStreamer->SwitchSection(
1389         OutContext.getELFSection(".note.GNU-split-stack", ELF::SHT_PROGBITS, 0));
1390     if (MMI->hasNosplitStack())
1391       OutStreamer->SwitchSection(
1392           OutContext.getELFSection(".note.GNU-no-split-stack", ELF::SHT_PROGBITS, 0));
1393   }
1394 
1395   // If we don't have any trampolines, then we don't require stack memory
1396   // to be executable. Some targets have a directive to declare this.
1397   Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1398   if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1399     if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
1400       OutStreamer->SwitchSection(S);
1401 
1402   // Allow the target to emit any magic that it wants at the end of the file,
1403   // after everything else has gone out.
1404   EmitEndOfAsmFile(M);
1405 
1406   MMI = nullptr;
1407 
1408   OutStreamer->Finish();
1409   OutStreamer->reset();
1410 
1411   return false;
1412 }
1413 
1414 MCSymbol *AsmPrinter::getCurExceptionSym() {
1415   if (!CurExceptionSym)
1416     CurExceptionSym = createTempSymbol("exception");
1417   return CurExceptionSym;
1418 }
1419 
1420 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1421   this->MF = &MF;
1422   // Get the function symbol.
1423   CurrentFnSym = getSymbol(MF.getFunction());
1424   CurrentFnSymForSize = CurrentFnSym;
1425   CurrentFnBegin = nullptr;
1426   CurExceptionSym = nullptr;
1427   bool NeedsLocalForSize = MAI->needsLocalForSize();
1428   if (needFuncLabelsForEHOrDebugInfo(MF, MMI) || NeedsLocalForSize) {
1429     CurrentFnBegin = createTempSymbol("func_begin");
1430     if (NeedsLocalForSize)
1431       CurrentFnSymForSize = CurrentFnBegin;
1432   }
1433 
1434   ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
1435   if (isVerbose())
1436     LI = &getAnalysis<MachineLoopInfo>();
1437 
1438   const TargetSubtargetInfo &STI = MF.getSubtarget();
1439   EnablePrintSchedInfo = PrintSchedule.getNumOccurrences()
1440                              ? PrintSchedule
1441                              : STI.supportPrintSchedInfo();
1442 }
1443 
1444 namespace {
1445 
1446 // Keep track the alignment, constpool entries per Section.
1447   struct SectionCPs {
1448     MCSection *S;
1449     unsigned Alignment;
1450     SmallVector<unsigned, 4> CPEs;
1451 
1452     SectionCPs(MCSection *s, unsigned a) : S(s), Alignment(a) {}
1453   };
1454 
1455 } // end anonymous namespace
1456 
1457 /// EmitConstantPool - Print to the current output stream assembly
1458 /// representations of the constants in the constant pool MCP. This is
1459 /// used to print out constants which have been "spilled to memory" by
1460 /// the code generator.
1461 ///
1462 void AsmPrinter::EmitConstantPool() {
1463   const MachineConstantPool *MCP = MF->getConstantPool();
1464   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1465   if (CP.empty()) return;
1466 
1467   // Calculate sections for constant pool entries. We collect entries to go into
1468   // the same section together to reduce amount of section switch statements.
1469   SmallVector<SectionCPs, 4> CPSections;
1470   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1471     const MachineConstantPoolEntry &CPE = CP[i];
1472     unsigned Align = CPE.getAlignment();
1473 
1474     SectionKind Kind = CPE.getSectionKind(&getDataLayout());
1475 
1476     const Constant *C = nullptr;
1477     if (!CPE.isMachineConstantPoolEntry())
1478       C = CPE.Val.ConstVal;
1479 
1480     MCSection *S = getObjFileLowering().getSectionForConstant(getDataLayout(),
1481                                                               Kind, C, Align);
1482 
1483     // The number of sections are small, just do a linear search from the
1484     // last section to the first.
1485     bool Found = false;
1486     unsigned SecIdx = CPSections.size();
1487     while (SecIdx != 0) {
1488       if (CPSections[--SecIdx].S == S) {
1489         Found = true;
1490         break;
1491       }
1492     }
1493     if (!Found) {
1494       SecIdx = CPSections.size();
1495       CPSections.push_back(SectionCPs(S, Align));
1496     }
1497 
1498     if (Align > CPSections[SecIdx].Alignment)
1499       CPSections[SecIdx].Alignment = Align;
1500     CPSections[SecIdx].CPEs.push_back(i);
1501   }
1502 
1503   // Now print stuff into the calculated sections.
1504   const MCSection *CurSection = nullptr;
1505   unsigned Offset = 0;
1506   for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1507     for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1508       unsigned CPI = CPSections[i].CPEs[j];
1509       MCSymbol *Sym = GetCPISymbol(CPI);
1510       if (!Sym->isUndefined())
1511         continue;
1512 
1513       if (CurSection != CPSections[i].S) {
1514         OutStreamer->SwitchSection(CPSections[i].S);
1515         EmitAlignment(Log2_32(CPSections[i].Alignment));
1516         CurSection = CPSections[i].S;
1517         Offset = 0;
1518       }
1519 
1520       MachineConstantPoolEntry CPE = CP[CPI];
1521 
1522       // Emit inter-object padding for alignment.
1523       unsigned AlignMask = CPE.getAlignment() - 1;
1524       unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1525       OutStreamer->EmitZeros(NewOffset - Offset);
1526 
1527       Type *Ty = CPE.getType();
1528       Offset = NewOffset + getDataLayout().getTypeAllocSize(Ty);
1529 
1530       OutStreamer->EmitLabel(Sym);
1531       if (CPE.isMachineConstantPoolEntry())
1532         EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1533       else
1534         EmitGlobalConstant(getDataLayout(), CPE.Val.ConstVal);
1535     }
1536   }
1537 }
1538 
1539 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1540 /// by the current function to the current output stream.
1541 ///
1542 void AsmPrinter::EmitJumpTableInfo() {
1543   const DataLayout &DL = MF->getDataLayout();
1544   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1545   if (!MJTI) return;
1546   if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1547   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1548   if (JT.empty()) return;
1549 
1550   // Pick the directive to use to print the jump table entries, and switch to
1551   // the appropriate section.
1552   const Function *F = MF->getFunction();
1553   const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1554   bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
1555       MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32,
1556       *F);
1557   if (JTInDiffSection) {
1558     // Drop it in the readonly section.
1559     MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(*F, TM);
1560     OutStreamer->SwitchSection(ReadOnlySection);
1561   }
1562 
1563   EmitAlignment(Log2_32(MJTI->getEntryAlignment(DL)));
1564 
1565   // Jump tables in code sections are marked with a data_region directive
1566   // where that's supported.
1567   if (!JTInDiffSection)
1568     OutStreamer->EmitDataRegion(MCDR_DataRegionJT32);
1569 
1570   for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1571     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1572 
1573     // If this jump table was deleted, ignore it.
1574     if (JTBBs.empty()) continue;
1575 
1576     // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
1577     /// emit a .set directive for each unique entry.
1578     if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1579         MAI->doesSetDirectiveSuppressReloc()) {
1580       SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1581       const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1582       const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1583       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1584         const MachineBasicBlock *MBB = JTBBs[ii];
1585         if (!EmittedSets.insert(MBB).second)
1586           continue;
1587 
1588         // .set LJTSet, LBB32-base
1589         const MCExpr *LHS =
1590           MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1591         OutStreamer->EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1592                                     MCBinaryExpr::createSub(LHS, Base,
1593                                                             OutContext));
1594       }
1595     }
1596 
1597     // On some targets (e.g. Darwin) we want to emit two consecutive labels
1598     // before each jump table.  The first label is never referenced, but tells
1599     // the assembler and linker the extents of the jump table object.  The
1600     // second label is actually referenced by the code.
1601     if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
1602       // FIXME: This doesn't have to have any specific name, just any randomly
1603       // named and numbered 'l' label would work.  Simplify GetJTISymbol.
1604       OutStreamer->EmitLabel(GetJTISymbol(JTI, true));
1605 
1606     OutStreamer->EmitLabel(GetJTISymbol(JTI));
1607 
1608     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1609       EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1610   }
1611   if (!JTInDiffSection)
1612     OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1613 }
1614 
1615 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1616 /// current stream.
1617 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1618                                     const MachineBasicBlock *MBB,
1619                                     unsigned UID) const {
1620   assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1621   const MCExpr *Value = nullptr;
1622   switch (MJTI->getEntryKind()) {
1623   case MachineJumpTableInfo::EK_Inline:
1624     llvm_unreachable("Cannot emit EK_Inline jump table entry");
1625   case MachineJumpTableInfo::EK_Custom32:
1626     Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
1627         MJTI, MBB, UID, OutContext);
1628     break;
1629   case MachineJumpTableInfo::EK_BlockAddress:
1630     // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1631     //     .word LBB123
1632     Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1633     break;
1634   case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1635     // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1636     // with a relocation as gp-relative, e.g.:
1637     //     .gprel32 LBB123
1638     MCSymbol *MBBSym = MBB->getSymbol();
1639     OutStreamer->EmitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext));
1640     return;
1641   }
1642 
1643   case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1644     // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1645     // with a relocation as gp-relative, e.g.:
1646     //     .gpdword LBB123
1647     MCSymbol *MBBSym = MBB->getSymbol();
1648     OutStreamer->EmitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext));
1649     return;
1650   }
1651 
1652   case MachineJumpTableInfo::EK_LabelDifference32: {
1653     // Each entry is the address of the block minus the address of the jump
1654     // table. This is used for PIC jump tables where gprel32 is not supported.
1655     // e.g.:
1656     //      .word LBB123 - LJTI1_2
1657     // If the .set directive avoids relocations, this is emitted as:
1658     //      .set L4_5_set_123, LBB123 - LJTI1_2
1659     //      .word L4_5_set_123
1660     if (MAI->doesSetDirectiveSuppressReloc()) {
1661       Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()),
1662                                       OutContext);
1663       break;
1664     }
1665     Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1666     const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1667     const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
1668     Value = MCBinaryExpr::createSub(Value, Base, OutContext);
1669     break;
1670   }
1671   }
1672 
1673   assert(Value && "Unknown entry kind!");
1674 
1675   unsigned EntrySize = MJTI->getEntrySize(getDataLayout());
1676   OutStreamer->EmitValue(Value, EntrySize);
1677 }
1678 
1679 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1680 /// special global used by LLVM.  If so, emit it and return true, otherwise
1681 /// do nothing and return false.
1682 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1683   if (GV->getName() == "llvm.used") {
1684     if (MAI->hasNoDeadStrip())    // No need to emit this at all.
1685       EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1686     return true;
1687   }
1688 
1689   // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
1690   if (GV->getSection() == "llvm.metadata" ||
1691       GV->hasAvailableExternallyLinkage())
1692     return true;
1693 
1694   if (!GV->hasAppendingLinkage()) return false;
1695 
1696   assert(GV->hasInitializer() && "Not a special LLVM global!");
1697 
1698   if (GV->getName() == "llvm.global_ctors") {
1699     EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
1700                        /* isCtor */ true);
1701 
1702     return true;
1703   }
1704 
1705   if (GV->getName() == "llvm.global_dtors") {
1706     EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
1707                        /* isCtor */ false);
1708 
1709     return true;
1710   }
1711 
1712   report_fatal_error("unknown special variable");
1713 }
1714 
1715 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1716 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1717 /// is true, as being used with this directive.
1718 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1719   // Should be an array of 'i8*'.
1720   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1721     const GlobalValue *GV =
1722       dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1723     if (GV)
1724       OutStreamer->EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1725   }
1726 }
1727 
1728 namespace {
1729 
1730 struct Structor {
1731   int Priority = 0;
1732   Constant *Func = nullptr;
1733   GlobalValue *ComdatKey = nullptr;
1734 
1735   Structor() = default;
1736 };
1737 
1738 }  // end anonymous namespace
1739 
1740 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1741 /// priority.
1742 void AsmPrinter::EmitXXStructorList(const DataLayout &DL, const Constant *List,
1743                                     bool isCtor) {
1744   // Should be an array of '{ int, void ()* }' structs.  The first value is the
1745   // init priority.
1746   if (!isa<ConstantArray>(List)) return;
1747 
1748   // Sanity check the structors list.
1749   const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1750   if (!InitList) return; // Not an array!
1751   StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1752   // FIXME: Only allow the 3-field form in LLVM 4.0.
1753   if (!ETy || ETy->getNumElements() < 2 || ETy->getNumElements() > 3)
1754     return; // Not an array of two or three elements!
1755   if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1756       !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1757   if (ETy->getNumElements() == 3 && !isa<PointerType>(ETy->getTypeAtIndex(2U)))
1758     return; // Not (int, ptr, ptr).
1759 
1760   // Gather the structors in a form that's convenient for sorting by priority.
1761   SmallVector<Structor, 8> Structors;
1762   for (Value *O : InitList->operands()) {
1763     ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
1764     if (!CS) continue; // Malformed.
1765     if (CS->getOperand(1)->isNullValue())
1766       break;  // Found a null terminator, skip the rest.
1767     ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1768     if (!Priority) continue; // Malformed.
1769     Structors.push_back(Structor());
1770     Structor &S = Structors.back();
1771     S.Priority = Priority->getLimitedValue(65535);
1772     S.Func = CS->getOperand(1);
1773     if (ETy->getNumElements() == 3 && !CS->getOperand(2)->isNullValue())
1774       S.ComdatKey =
1775           dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
1776   }
1777 
1778   // Emit the function pointers in the target-specific order
1779   unsigned Align = Log2_32(DL.getPointerPrefAlignment());
1780   std::stable_sort(Structors.begin(), Structors.end(),
1781                    [](const Structor &L,
1782                       const Structor &R) { return L.Priority < R.Priority; });
1783   for (Structor &S : Structors) {
1784     const TargetLoweringObjectFile &Obj = getObjFileLowering();
1785     const MCSymbol *KeySym = nullptr;
1786     if (GlobalValue *GV = S.ComdatKey) {
1787       if (GV->isDeclarationForLinker())
1788         // If the associated variable is not defined in this module
1789         // (it might be available_externally, or have been an
1790         // available_externally definition that was dropped by the
1791         // EliminateAvailableExternally pass), some other TU
1792         // will provide its dynamic initializer.
1793         continue;
1794 
1795       KeySym = getSymbol(GV);
1796     }
1797     MCSection *OutputSection =
1798         (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
1799                 : Obj.getStaticDtorSection(S.Priority, KeySym));
1800     OutStreamer->SwitchSection(OutputSection);
1801     if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
1802       EmitAlignment(Align);
1803     EmitXXStructor(DL, S.Func);
1804   }
1805 }
1806 
1807 void AsmPrinter::EmitModuleIdents(Module &M) {
1808   if (!MAI->hasIdentDirective())
1809     return;
1810 
1811   if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1812     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1813       const MDNode *N = NMD->getOperand(i);
1814       assert(N->getNumOperands() == 1 &&
1815              "llvm.ident metadata entry can have only one operand");
1816       const MDString *S = cast<MDString>(N->getOperand(0));
1817       OutStreamer->EmitIdent(S->getString());
1818     }
1819   }
1820 }
1821 
1822 //===--------------------------------------------------------------------===//
1823 // Emission and print routines
1824 //
1825 
1826 /// EmitInt8 - Emit a byte directive and value.
1827 ///
1828 void AsmPrinter::EmitInt8(int Value) const {
1829   OutStreamer->EmitIntValue(Value, 1);
1830 }
1831 
1832 /// EmitInt16 - Emit a short directive and value.
1833 ///
1834 void AsmPrinter::EmitInt16(int Value) const {
1835   OutStreamer->EmitIntValue(Value, 2);
1836 }
1837 
1838 /// EmitInt32 - Emit a long directive and value.
1839 ///
1840 void AsmPrinter::EmitInt32(int Value) const {
1841   OutStreamer->EmitIntValue(Value, 4);
1842 }
1843 
1844 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
1845 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
1846 /// .set if it avoids relocations.
1847 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1848                                      unsigned Size) const {
1849   OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
1850 }
1851 
1852 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1853 /// where the size in bytes of the directive is specified by Size and Label
1854 /// specifies the label.  This implicitly uses .set if it is available.
1855 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1856                                      unsigned Size,
1857                                      bool IsSectionRelative) const {
1858   if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
1859     OutStreamer->EmitCOFFSecRel32(Label, Offset);
1860     if (Size > 4)
1861       OutStreamer->EmitZeros(Size - 4);
1862     return;
1863   }
1864 
1865   // Emit Label+Offset (or just Label if Offset is zero)
1866   const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
1867   if (Offset)
1868     Expr = MCBinaryExpr::createAdd(
1869         Expr, MCConstantExpr::create(Offset, OutContext), OutContext);
1870 
1871   OutStreamer->EmitValue(Expr, Size);
1872 }
1873 
1874 //===----------------------------------------------------------------------===//
1875 
1876 // EmitAlignment - Emit an alignment directive to the specified power of
1877 // two boundary.  For example, if you pass in 3 here, you will get an 8
1878 // byte alignment.  If a global value is specified, and if that global has
1879 // an explicit alignment requested, it will override the alignment request
1880 // if required for correctness.
1881 //
1882 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalObject *GV) const {
1883   if (GV)
1884     NumBits = getGVAlignmentLog2(GV, GV->getParent()->getDataLayout(), NumBits);
1885 
1886   if (NumBits == 0) return;   // 1-byte aligned: no need to emit alignment.
1887 
1888   assert(NumBits <
1889              static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
1890          "undefined behavior");
1891   if (getCurrentSection()->getKind().isText())
1892     OutStreamer->EmitCodeAlignment(1u << NumBits);
1893   else
1894     OutStreamer->EmitValueToAlignment(1u << NumBits);
1895 }
1896 
1897 //===----------------------------------------------------------------------===//
1898 // Constant emission.
1899 //===----------------------------------------------------------------------===//
1900 
1901 const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) {
1902   MCContext &Ctx = OutContext;
1903 
1904   if (CV->isNullValue() || isa<UndefValue>(CV))
1905     return MCConstantExpr::create(0, Ctx);
1906 
1907   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1908     return MCConstantExpr::create(CI->getZExtValue(), Ctx);
1909 
1910   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1911     return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
1912 
1913   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1914     return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx);
1915 
1916   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1917   if (!CE) {
1918     llvm_unreachable("Unknown constant value to lower!");
1919   }
1920 
1921   switch (CE->getOpcode()) {
1922   default:
1923     // If the code isn't optimized, there may be outstanding folding
1924     // opportunities. Attempt to fold the expression using DataLayout as a
1925     // last resort before giving up.
1926     if (Constant *C = ConstantFoldConstant(CE, getDataLayout()))
1927       if (C != CE)
1928         return lowerConstant(C);
1929 
1930     // Otherwise report the problem to the user.
1931     {
1932       std::string S;
1933       raw_string_ostream OS(S);
1934       OS << "Unsupported expression in static initializer: ";
1935       CE->printAsOperand(OS, /*PrintType=*/false,
1936                      !MF ? nullptr : MF->getFunction()->getParent());
1937       report_fatal_error(OS.str());
1938     }
1939   case Instruction::GetElementPtr: {
1940     // Generate a symbolic expression for the byte address
1941     APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
1942     cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
1943 
1944     const MCExpr *Base = lowerConstant(CE->getOperand(0));
1945     if (!OffsetAI)
1946       return Base;
1947 
1948     int64_t Offset = OffsetAI.getSExtValue();
1949     return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
1950                                    Ctx);
1951   }
1952 
1953   case Instruction::Trunc:
1954     // We emit the value and depend on the assembler to truncate the generated
1955     // expression properly.  This is important for differences between
1956     // blockaddress labels.  Since the two labels are in the same function, it
1957     // is reasonable to treat their delta as a 32-bit value.
1958     LLVM_FALLTHROUGH;
1959   case Instruction::BitCast:
1960     return lowerConstant(CE->getOperand(0));
1961 
1962   case Instruction::IntToPtr: {
1963     const DataLayout &DL = getDataLayout();
1964 
1965     // Handle casts to pointers by changing them into casts to the appropriate
1966     // integer type.  This promotes constant folding and simplifies this code.
1967     Constant *Op = CE->getOperand(0);
1968     Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
1969                                       false/*ZExt*/);
1970     return lowerConstant(Op);
1971   }
1972 
1973   case Instruction::PtrToInt: {
1974     const DataLayout &DL = getDataLayout();
1975 
1976     // Support only foldable casts to/from pointers that can be eliminated by
1977     // changing the pointer to the appropriately sized integer type.
1978     Constant *Op = CE->getOperand(0);
1979     Type *Ty = CE->getType();
1980 
1981     const MCExpr *OpExpr = lowerConstant(Op);
1982 
1983     // We can emit the pointer value into this slot if the slot is an
1984     // integer slot equal to the size of the pointer.
1985     if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
1986       return OpExpr;
1987 
1988     // Otherwise the pointer is smaller than the resultant integer, mask off
1989     // the high bits so we are sure to get a proper truncation if the input is
1990     // a constant expr.
1991     unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1992     const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
1993     return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
1994   }
1995 
1996   case Instruction::Sub: {
1997     GlobalValue *LHSGV;
1998     APInt LHSOffset;
1999     if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset,
2000                                    getDataLayout())) {
2001       GlobalValue *RHSGV;
2002       APInt RHSOffset;
2003       if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset,
2004                                      getDataLayout())) {
2005         const MCExpr *RelocExpr =
2006             getObjFileLowering().lowerRelativeReference(LHSGV, RHSGV, TM);
2007         if (!RelocExpr)
2008           RelocExpr = MCBinaryExpr::createSub(
2009               MCSymbolRefExpr::create(getSymbol(LHSGV), Ctx),
2010               MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx);
2011         int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
2012         if (Addend != 0)
2013           RelocExpr = MCBinaryExpr::createAdd(
2014               RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx);
2015         return RelocExpr;
2016       }
2017     }
2018   }
2019   // else fallthrough
2020 
2021   // The MC library also has a right-shift operator, but it isn't consistently
2022   // signed or unsigned between different targets.
2023   case Instruction::Add:
2024   case Instruction::Mul:
2025   case Instruction::SDiv:
2026   case Instruction::SRem:
2027   case Instruction::Shl:
2028   case Instruction::And:
2029   case Instruction::Or:
2030   case Instruction::Xor: {
2031     const MCExpr *LHS = lowerConstant(CE->getOperand(0));
2032     const MCExpr *RHS = lowerConstant(CE->getOperand(1));
2033     switch (CE->getOpcode()) {
2034     default: llvm_unreachable("Unknown binary operator constant cast expr");
2035     case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
2036     case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx);
2037     case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx);
2038     case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx);
2039     case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx);
2040     case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx);
2041     case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx);
2042     case Instruction::Or:  return MCBinaryExpr::createOr (LHS, RHS, Ctx);
2043     case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx);
2044     }
2045   }
2046   }
2047 }
2048 
2049 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
2050                                    AsmPrinter &AP,
2051                                    const Constant *BaseCV = nullptr,
2052                                    uint64_t Offset = 0);
2053 
2054 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
2055 
2056 /// isRepeatedByteSequence - Determine whether the given value is
2057 /// composed of a repeated sequence of identical bytes and return the
2058 /// byte value.  If it is not a repeated sequence, return -1.
2059 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
2060   StringRef Data = V->getRawDataValues();
2061   assert(!Data.empty() && "Empty aggregates should be CAZ node");
2062   char C = Data[0];
2063   for (unsigned i = 1, e = Data.size(); i != e; ++i)
2064     if (Data[i] != C) return -1;
2065   return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
2066 }
2067 
2068 /// isRepeatedByteSequence - Determine whether the given value is
2069 /// composed of a repeated sequence of identical bytes and return the
2070 /// byte value.  If it is not a repeated sequence, return -1.
2071 static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
2072   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2073     uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
2074     assert(Size % 8 == 0);
2075 
2076     // Extend the element to take zero padding into account.
2077     APInt Value = CI->getValue().zextOrSelf(Size);
2078     if (!Value.isSplat(8))
2079       return -1;
2080 
2081     return Value.zextOrTrunc(8).getZExtValue();
2082   }
2083   if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
2084     // Make sure all array elements are sequences of the same repeated
2085     // byte.
2086     assert(CA->getNumOperands() != 0 && "Should be a CAZ");
2087     Constant *Op0 = CA->getOperand(0);
2088     int Byte = isRepeatedByteSequence(Op0, DL);
2089     if (Byte == -1)
2090       return -1;
2091 
2092     // All array elements must be equal.
2093     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
2094       if (CA->getOperand(i) != Op0)
2095         return -1;
2096     return Byte;
2097   }
2098 
2099   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
2100     return isRepeatedByteSequence(CDS);
2101 
2102   return -1;
2103 }
2104 
2105 static void emitGlobalConstantDataSequential(const DataLayout &DL,
2106                                              const ConstantDataSequential *CDS,
2107                                              AsmPrinter &AP) {
2108   // See if we can aggregate this into a .fill, if so, emit it as such.
2109   int Value = isRepeatedByteSequence(CDS, DL);
2110   if (Value != -1) {
2111     uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
2112     // Don't emit a 1-byte object as a .fill.
2113     if (Bytes > 1)
2114       return AP.OutStreamer->emitFill(Bytes, Value);
2115   }
2116 
2117   // If this can be emitted with .ascii/.asciz, emit it as such.
2118   if (CDS->isString())
2119     return AP.OutStreamer->EmitBytes(CDS->getAsString());
2120 
2121   // Otherwise, emit the values in successive locations.
2122   unsigned ElementByteSize = CDS->getElementByteSize();
2123   if (isa<IntegerType>(CDS->getElementType())) {
2124     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
2125       if (AP.isVerbose())
2126         AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
2127                                                  CDS->getElementAsInteger(i));
2128       AP.OutStreamer->EmitIntValue(CDS->getElementAsInteger(i),
2129                                    ElementByteSize);
2130     }
2131   } else {
2132     for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I)
2133       emitGlobalConstantFP(cast<ConstantFP>(CDS->getElementAsConstant(I)), AP);
2134   }
2135 
2136   unsigned Size = DL.getTypeAllocSize(CDS->getType());
2137   unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
2138                         CDS->getNumElements();
2139   if (unsigned Padding = Size - EmittedSize)
2140     AP.OutStreamer->EmitZeros(Padding);
2141 }
2142 
2143 static void emitGlobalConstantArray(const DataLayout &DL,
2144                                     const ConstantArray *CA, AsmPrinter &AP,
2145                                     const Constant *BaseCV, uint64_t Offset) {
2146   // See if we can aggregate some values.  Make sure it can be
2147   // represented as a series of bytes of the constant value.
2148   int Value = isRepeatedByteSequence(CA, DL);
2149 
2150   if (Value != -1) {
2151     uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
2152     AP.OutStreamer->emitFill(Bytes, Value);
2153   }
2154   else {
2155     for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
2156       emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset);
2157       Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
2158     }
2159   }
2160 }
2161 
2162 static void emitGlobalConstantVector(const DataLayout &DL,
2163                                      const ConstantVector *CV, AsmPrinter &AP) {
2164   for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
2165     emitGlobalConstantImpl(DL, CV->getOperand(i), AP);
2166 
2167   unsigned Size = DL.getTypeAllocSize(CV->getType());
2168   unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
2169                          CV->getType()->getNumElements();
2170   if (unsigned Padding = Size - EmittedSize)
2171     AP.OutStreamer->EmitZeros(Padding);
2172 }
2173 
2174 static void emitGlobalConstantStruct(const DataLayout &DL,
2175                                      const ConstantStruct *CS, AsmPrinter &AP,
2176                                      const Constant *BaseCV, uint64_t Offset) {
2177   // Print the fields in successive locations. Pad to align if needed!
2178   unsigned Size = DL.getTypeAllocSize(CS->getType());
2179   const StructLayout *Layout = DL.getStructLayout(CS->getType());
2180   uint64_t SizeSoFar = 0;
2181   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
2182     const Constant *Field = CS->getOperand(i);
2183 
2184     // Print the actual field value.
2185     emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar);
2186 
2187     // Check if padding is needed and insert one or more 0s.
2188     uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
2189     uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
2190                         - Layout->getElementOffset(i)) - FieldSize;
2191     SizeSoFar += FieldSize + PadSize;
2192 
2193     // Insert padding - this may include padding to increase the size of the
2194     // current field up to the ABI size (if the struct is not packed) as well
2195     // as padding to ensure that the next field starts at the right offset.
2196     AP.OutStreamer->EmitZeros(PadSize);
2197   }
2198   assert(SizeSoFar == Layout->getSizeInBytes() &&
2199          "Layout of constant struct may be incorrect!");
2200 }
2201 
2202 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
2203   APInt API = CFP->getValueAPF().bitcastToAPInt();
2204 
2205   // First print a comment with what we think the original floating-point value
2206   // should have been.
2207   if (AP.isVerbose()) {
2208     SmallString<8> StrVal;
2209     CFP->getValueAPF().toString(StrVal);
2210 
2211     if (CFP->getType())
2212       CFP->getType()->print(AP.OutStreamer->GetCommentOS());
2213     else
2214       AP.OutStreamer->GetCommentOS() << "Printing <null> Type";
2215     AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n';
2216   }
2217 
2218   // Now iterate through the APInt chunks, emitting them in endian-correct
2219   // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
2220   // floats).
2221   unsigned NumBytes = API.getBitWidth() / 8;
2222   unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
2223   const uint64_t *p = API.getRawData();
2224 
2225   // PPC's long double has odd notions of endianness compared to how LLVM
2226   // handles it: p[0] goes first for *big* endian on PPC.
2227   if (AP.getDataLayout().isBigEndian() && !CFP->getType()->isPPC_FP128Ty()) {
2228     int Chunk = API.getNumWords() - 1;
2229 
2230     if (TrailingBytes)
2231       AP.OutStreamer->EmitIntValue(p[Chunk--], TrailingBytes);
2232 
2233     for (; Chunk >= 0; --Chunk)
2234       AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
2235   } else {
2236     unsigned Chunk;
2237     for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
2238       AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
2239 
2240     if (TrailingBytes)
2241       AP.OutStreamer->EmitIntValue(p[Chunk], TrailingBytes);
2242   }
2243 
2244   // Emit the tail padding for the long double.
2245   const DataLayout &DL = AP.getDataLayout();
2246   AP.OutStreamer->EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
2247                             DL.getTypeStoreSize(CFP->getType()));
2248 }
2249 
2250 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
2251   const DataLayout &DL = AP.getDataLayout();
2252   unsigned BitWidth = CI->getBitWidth();
2253 
2254   // Copy the value as we may massage the layout for constants whose bit width
2255   // is not a multiple of 64-bits.
2256   APInt Realigned(CI->getValue());
2257   uint64_t ExtraBits = 0;
2258   unsigned ExtraBitsSize = BitWidth & 63;
2259 
2260   if (ExtraBitsSize) {
2261     // The bit width of the data is not a multiple of 64-bits.
2262     // The extra bits are expected to be at the end of the chunk of the memory.
2263     // Little endian:
2264     // * Nothing to be done, just record the extra bits to emit.
2265     // Big endian:
2266     // * Record the extra bits to emit.
2267     // * Realign the raw data to emit the chunks of 64-bits.
2268     if (DL.isBigEndian()) {
2269       // Basically the structure of the raw data is a chunk of 64-bits cells:
2270       //    0        1         BitWidth / 64
2271       // [chunk1][chunk2] ... [chunkN].
2272       // The most significant chunk is chunkN and it should be emitted first.
2273       // However, due to the alignment issue chunkN contains useless bits.
2274       // Realign the chunks so that they contain only useless information:
2275       // ExtraBits     0       1       (BitWidth / 64) - 1
2276       //       chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
2277       ExtraBits = Realigned.getRawData()[0] &
2278         (((uint64_t)-1) >> (64 - ExtraBitsSize));
2279       Realigned.lshrInPlace(ExtraBitsSize);
2280     } else
2281       ExtraBits = Realigned.getRawData()[BitWidth / 64];
2282   }
2283 
2284   // We don't expect assemblers to support integer data directives
2285   // for more than 64 bits, so we emit the data in at most 64-bit
2286   // quantities at a time.
2287   const uint64_t *RawData = Realigned.getRawData();
2288   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
2289     uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
2290     AP.OutStreamer->EmitIntValue(Val, 8);
2291   }
2292 
2293   if (ExtraBitsSize) {
2294     // Emit the extra bits after the 64-bits chunks.
2295 
2296     // Emit a directive that fills the expected size.
2297     uint64_t Size = AP.getDataLayout().getTypeAllocSize(CI->getType());
2298     Size -= (BitWidth / 64) * 8;
2299     assert(Size && Size * 8 >= ExtraBitsSize &&
2300            (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
2301            == ExtraBits && "Directive too small for extra bits.");
2302     AP.OutStreamer->EmitIntValue(ExtraBits, Size);
2303   }
2304 }
2305 
2306 /// \brief Transform a not absolute MCExpr containing a reference to a GOT
2307 /// equivalent global, by a target specific GOT pc relative access to the
2308 /// final symbol.
2309 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
2310                                          const Constant *BaseCst,
2311                                          uint64_t Offset) {
2312   // The global @foo below illustrates a global that uses a got equivalent.
2313   //
2314   //  @bar = global i32 42
2315   //  @gotequiv = private unnamed_addr constant i32* @bar
2316   //  @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
2317   //                             i64 ptrtoint (i32* @foo to i64))
2318   //                        to i32)
2319   //
2320   // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
2321   // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
2322   // form:
2323   //
2324   //  foo = cstexpr, where
2325   //    cstexpr := <gotequiv> - "." + <cst>
2326   //    cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
2327   //
2328   // After canonicalization by evaluateAsRelocatable `ME` turns into:
2329   //
2330   //  cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
2331   //    gotpcrelcst := <offset from @foo base> + <cst>
2332   //
2333   MCValue MV;
2334   if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
2335     return;
2336   const MCSymbolRefExpr *SymA = MV.getSymA();
2337   if (!SymA)
2338     return;
2339 
2340   // Check that GOT equivalent symbol is cached.
2341   const MCSymbol *GOTEquivSym = &SymA->getSymbol();
2342   if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
2343     return;
2344 
2345   const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
2346   if (!BaseGV)
2347     return;
2348 
2349   // Check for a valid base symbol
2350   const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
2351   const MCSymbolRefExpr *SymB = MV.getSymB();
2352 
2353   if (!SymB || BaseSym != &SymB->getSymbol())
2354     return;
2355 
2356   // Make sure to match:
2357   //
2358   //    gotpcrelcst := <offset from @foo base> + <cst>
2359   //
2360   // If gotpcrelcst is positive it means that we can safely fold the pc rel
2361   // displacement into the GOTPCREL. We can also can have an extra offset <cst>
2362   // if the target knows how to encode it.
2363   //
2364   int64_t GOTPCRelCst = Offset + MV.getConstant();
2365   if (GOTPCRelCst < 0)
2366     return;
2367   if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
2368     return;
2369 
2370   // Emit the GOT PC relative to replace the got equivalent global, i.e.:
2371   //
2372   //  bar:
2373   //    .long 42
2374   //  gotequiv:
2375   //    .quad bar
2376   //  foo:
2377   //    .long gotequiv - "." + <cst>
2378   //
2379   // is replaced by the target specific equivalent to:
2380   //
2381   //  bar:
2382   //    .long 42
2383   //  foo:
2384   //    .long bar@GOTPCREL+<gotpcrelcst>
2385   //
2386   AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
2387   const GlobalVariable *GV = Result.first;
2388   int NumUses = (int)Result.second;
2389   const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
2390   const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
2391   *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel(
2392       FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
2393 
2394   // Update GOT equivalent usage information
2395   --NumUses;
2396   if (NumUses >= 0)
2397     AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
2398 }
2399 
2400 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
2401                                    AsmPrinter &AP, const Constant *BaseCV,
2402                                    uint64_t Offset) {
2403   uint64_t Size = DL.getTypeAllocSize(CV->getType());
2404 
2405   // Globals with sub-elements such as combinations of arrays and structs
2406   // are handled recursively by emitGlobalConstantImpl. Keep track of the
2407   // constant symbol base and the current position with BaseCV and Offset.
2408   if (!BaseCV && CV->hasOneUse())
2409     BaseCV = dyn_cast<Constant>(CV->user_back());
2410 
2411   if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
2412     return AP.OutStreamer->EmitZeros(Size);
2413 
2414   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
2415     switch (Size) {
2416     case 1:
2417     case 2:
2418     case 4:
2419     case 8:
2420       if (AP.isVerbose())
2421         AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
2422                                                  CI->getZExtValue());
2423       AP.OutStreamer->EmitIntValue(CI->getZExtValue(), Size);
2424       return;
2425     default:
2426       emitGlobalConstantLargeInt(CI, AP);
2427       return;
2428     }
2429   }
2430 
2431   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
2432     return emitGlobalConstantFP(CFP, AP);
2433 
2434   if (isa<ConstantPointerNull>(CV)) {
2435     AP.OutStreamer->EmitIntValue(0, Size);
2436     return;
2437   }
2438 
2439   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
2440     return emitGlobalConstantDataSequential(DL, CDS, AP);
2441 
2442   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
2443     return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset);
2444 
2445   if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
2446     return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset);
2447 
2448   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
2449     // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
2450     // vectors).
2451     if (CE->getOpcode() == Instruction::BitCast)
2452       return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
2453 
2454     if (Size > 8) {
2455       // If the constant expression's size is greater than 64-bits, then we have
2456       // to emit the value in chunks. Try to constant fold the value and emit it
2457       // that way.
2458       Constant *New = ConstantFoldConstant(CE, DL);
2459       if (New && New != CE)
2460         return emitGlobalConstantImpl(DL, New, AP);
2461     }
2462   }
2463 
2464   if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
2465     return emitGlobalConstantVector(DL, V, AP);
2466 
2467   // Otherwise, it must be a ConstantExpr.  Lower it to an MCExpr, then emit it
2468   // thread the streamer with EmitValue.
2469   const MCExpr *ME = AP.lowerConstant(CV);
2470 
2471   // Since lowerConstant already folded and got rid of all IR pointer and
2472   // integer casts, detect GOT equivalent accesses by looking into the MCExpr
2473   // directly.
2474   if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel())
2475     handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
2476 
2477   AP.OutStreamer->EmitValue(ME, Size);
2478 }
2479 
2480 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
2481 void AsmPrinter::EmitGlobalConstant(const DataLayout &DL, const Constant *CV) {
2482   uint64_t Size = DL.getTypeAllocSize(CV->getType());
2483   if (Size)
2484     emitGlobalConstantImpl(DL, CV, *this);
2485   else if (MAI->hasSubsectionsViaSymbols()) {
2486     // If the global has zero size, emit a single byte so that two labels don't
2487     // look like they are at the same location.
2488     OutStreamer->EmitIntValue(0, 1);
2489   }
2490 }
2491 
2492 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
2493   // Target doesn't support this yet!
2494   llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
2495 }
2496 
2497 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
2498   if (Offset > 0)
2499     OS << '+' << Offset;
2500   else if (Offset < 0)
2501     OS << Offset;
2502 }
2503 
2504 //===----------------------------------------------------------------------===//
2505 // Symbol Lowering Routines.
2506 //===----------------------------------------------------------------------===//
2507 
2508 MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const {
2509   return OutContext.createTempSymbol(Name, true);
2510 }
2511 
2512 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2513   return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2514 }
2515 
2516 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2517   return MMI->getAddrLabelSymbol(BB);
2518 }
2519 
2520 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
2521 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2522   const DataLayout &DL = getDataLayout();
2523   return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
2524                                       "CPI" + Twine(getFunctionNumber()) + "_" +
2525                                       Twine(CPID));
2526 }
2527 
2528 /// GetJTISymbol - Return the symbol for the specified jump table entry.
2529 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2530   return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2531 }
2532 
2533 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2534 /// FIXME: privatize to AsmPrinter.
2535 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2536   const DataLayout &DL = getDataLayout();
2537   return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
2538                                       Twine(getFunctionNumber()) + "_" +
2539                                       Twine(UID) + "_set_" + Twine(MBBID));
2540 }
2541 
2542 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
2543                                                    StringRef Suffix) const {
2544   return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, TM);
2545 }
2546 
2547 /// Return the MCSymbol for the specified ExternalSymbol.
2548 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2549   SmallString<60> NameStr;
2550   Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout());
2551   return OutContext.getOrCreateSymbol(NameStr);
2552 }
2553 
2554 /// PrintParentLoopComment - Print comments about parent loops of this one.
2555 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2556                                    unsigned FunctionNumber) {
2557   if (!Loop) return;
2558   PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2559   OS.indent(Loop->getLoopDepth()*2)
2560     << "Parent Loop BB" << FunctionNumber << "_"
2561     << Loop->getHeader()->getNumber()
2562     << " Depth=" << Loop->getLoopDepth() << '\n';
2563 }
2564 
2565 
2566 /// PrintChildLoopComment - Print comments about child loops within
2567 /// the loop for this basic block, with nesting.
2568 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2569                                   unsigned FunctionNumber) {
2570   // Add child loop information
2571   for (const MachineLoop *CL : *Loop) {
2572     OS.indent(CL->getLoopDepth()*2)
2573       << "Child Loop BB" << FunctionNumber << "_"
2574       << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
2575       << '\n';
2576     PrintChildLoopComment(OS, CL, FunctionNumber);
2577   }
2578 }
2579 
2580 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2581 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2582                                        const MachineLoopInfo *LI,
2583                                        const AsmPrinter &AP) {
2584   // Add loop depth information
2585   const MachineLoop *Loop = LI->getLoopFor(&MBB);
2586   if (!Loop) return;
2587 
2588   MachineBasicBlock *Header = Loop->getHeader();
2589   assert(Header && "No header for loop");
2590 
2591   // If this block is not a loop header, just print out what is the loop header
2592   // and return.
2593   if (Header != &MBB) {
2594     AP.OutStreamer->AddComment("  in Loop: Header=BB" +
2595                                Twine(AP.getFunctionNumber())+"_" +
2596                                Twine(Loop->getHeader()->getNumber())+
2597                                " Depth="+Twine(Loop->getLoopDepth()));
2598     return;
2599   }
2600 
2601   // Otherwise, it is a loop header.  Print out information about child and
2602   // parent loops.
2603   raw_ostream &OS = AP.OutStreamer->GetCommentOS();
2604 
2605   PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2606 
2607   OS << "=>";
2608   OS.indent(Loop->getLoopDepth()*2-2);
2609 
2610   OS << "This ";
2611   if (Loop->empty())
2612     OS << "Inner ";
2613   OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2614 
2615   PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2616 }
2617 
2618 /// EmitBasicBlockStart - This method prints the label for the specified
2619 /// MachineBasicBlock, an alignment (if present) and a comment describing
2620 /// it if appropriate.
2621 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
2622   // End the previous funclet and start a new one.
2623   if (MBB.isEHFuncletEntry()) {
2624     for (const HandlerInfo &HI : Handlers) {
2625       HI.Handler->endFunclet();
2626       HI.Handler->beginFunclet(MBB);
2627     }
2628   }
2629 
2630   // Emit an alignment directive for this block, if needed.
2631   if (unsigned Align = MBB.getAlignment())
2632     EmitAlignment(Align);
2633 
2634   // If the block has its address taken, emit any labels that were used to
2635   // reference the block.  It is possible that there is more than one label
2636   // here, because multiple LLVM BB's may have been RAUW'd to this block after
2637   // the references were generated.
2638   if (MBB.hasAddressTaken()) {
2639     const BasicBlock *BB = MBB.getBasicBlock();
2640     if (isVerbose())
2641       OutStreamer->AddComment("Block address taken");
2642 
2643     // MBBs can have their address taken as part of CodeGen without having
2644     // their corresponding BB's address taken in IR
2645     if (BB->hasAddressTaken())
2646       for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB))
2647         OutStreamer->EmitLabel(Sym);
2648   }
2649 
2650   // Print some verbose block comments.
2651   if (isVerbose()) {
2652     if (const BasicBlock *BB = MBB.getBasicBlock()) {
2653       if (BB->hasName()) {
2654         BB->printAsOperand(OutStreamer->GetCommentOS(),
2655                            /*PrintType=*/false, BB->getModule());
2656         OutStreamer->GetCommentOS() << '\n';
2657       }
2658     }
2659     emitBasicBlockLoopComments(MBB, LI, *this);
2660   }
2661 
2662   // Print the main label for the block.
2663   if (MBB.pred_empty() ||
2664       (isBlockOnlyReachableByFallthrough(&MBB) && !MBB.isEHFuncletEntry())) {
2665     if (isVerbose()) {
2666       // NOTE: Want this comment at start of line, don't emit with AddComment.
2667       OutStreamer->emitRawComment(" BB#" + Twine(MBB.getNumber()) + ":", false);
2668     }
2669   } else {
2670     OutStreamer->EmitLabel(MBB.getSymbol());
2671   }
2672 }
2673 
2674 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2675                                 bool IsDefinition) const {
2676   MCSymbolAttr Attr = MCSA_Invalid;
2677 
2678   switch (Visibility) {
2679   default: break;
2680   case GlobalValue::HiddenVisibility:
2681     if (IsDefinition)
2682       Attr = MAI->getHiddenVisibilityAttr();
2683     else
2684       Attr = MAI->getHiddenDeclarationVisibilityAttr();
2685     break;
2686   case GlobalValue::ProtectedVisibility:
2687     Attr = MAI->getProtectedVisibilityAttr();
2688     break;
2689   }
2690 
2691   if (Attr != MCSA_Invalid)
2692     OutStreamer->EmitSymbolAttribute(Sym, Attr);
2693 }
2694 
2695 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2696 /// exactly one predecessor and the control transfer mechanism between
2697 /// the predecessor and this block is a fall-through.
2698 bool AsmPrinter::
2699 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2700   // If this is a landing pad, it isn't a fall through.  If it has no preds,
2701   // then nothing falls through to it.
2702   if (MBB->isEHPad() || MBB->pred_empty())
2703     return false;
2704 
2705   // If there isn't exactly one predecessor, it can't be a fall through.
2706   if (MBB->pred_size() > 1)
2707     return false;
2708 
2709   // The predecessor has to be immediately before this block.
2710   MachineBasicBlock *Pred = *MBB->pred_begin();
2711   if (!Pred->isLayoutSuccessor(MBB))
2712     return false;
2713 
2714   // If the block is completely empty, then it definitely does fall through.
2715   if (Pred->empty())
2716     return true;
2717 
2718   // Check the terminators in the previous blocks
2719   for (const auto &MI : Pred->terminators()) {
2720     // If it is not a simple branch, we are in a table somewhere.
2721     if (!MI.isBranch() || MI.isIndirectBranch())
2722       return false;
2723 
2724     // If we are the operands of one of the branches, this is not a fall
2725     // through. Note that targets with delay slots will usually bundle
2726     // terminators with the delay slot instruction.
2727     for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) {
2728       if (OP->isJTI())
2729         return false;
2730       if (OP->isMBB() && OP->getMBB() == MBB)
2731         return false;
2732     }
2733   }
2734 
2735   return true;
2736 }
2737 
2738 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
2739   if (!S.usesMetadata())
2740     return nullptr;
2741 
2742   assert(!S.useStatepoints() && "statepoints do not currently support custom"
2743          " stackmap formats, please see the documentation for a description of"
2744          " the default format.  If you really need a custom serialized format,"
2745          " please file a bug");
2746 
2747   gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2748   gcp_map_type::iterator GCPI = GCMap.find(&S);
2749   if (GCPI != GCMap.end())
2750     return GCPI->second.get();
2751 
2752   auto Name = S.getName();
2753 
2754   for (GCMetadataPrinterRegistry::iterator
2755          I = GCMetadataPrinterRegistry::begin(),
2756          E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2757     if (Name == I->getName()) {
2758       std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
2759       GMP->S = &S;
2760       auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
2761       return IterBool.first->second.get();
2762     }
2763 
2764   report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
2765 }
2766 
2767 /// Pin vtable to this file.
2768 AsmPrinterHandler::~AsmPrinterHandler() = default;
2769 
2770 void AsmPrinterHandler::markFunctionEnd() {}
2771 
2772 // In the binary's "xray_instr_map" section, an array of these function entries
2773 // describes each instrumentation point.  When XRay patches your code, the index
2774 // into this table will be given to your handler as a patch point identifier.
2775 void AsmPrinter::XRayFunctionEntry::emit(int Bytes, MCStreamer *Out,
2776                                          const MCSymbol *CurrentFnSym) const {
2777   Out->EmitSymbolValue(Sled, Bytes);
2778   Out->EmitSymbolValue(CurrentFnSym, Bytes);
2779   auto Kind8 = static_cast<uint8_t>(Kind);
2780   Out->EmitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8), 1));
2781   Out->EmitBinaryData(
2782       StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1));
2783   Out->EmitBinaryData(StringRef(reinterpret_cast<const char *>(&Version), 1));
2784   auto Padding = (4 * Bytes) - ((2 * Bytes) + 3);
2785   assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size");
2786   Out->EmitZeros(Padding);
2787 }
2788 
2789 void AsmPrinter::emitXRayTable() {
2790   if (Sleds.empty())
2791     return;
2792 
2793   auto PrevSection = OutStreamer->getCurrentSectionOnly();
2794   auto Fn = MF->getFunction();
2795   MCSection *InstMap = nullptr;
2796   MCSection *FnSledIndex = nullptr;
2797   if (MF->getSubtarget().getTargetTriple().isOSBinFormatELF()) {
2798     auto Associated = dyn_cast<MCSymbolELF>(CurrentFnSym);
2799     assert(Associated != nullptr);
2800     auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER;
2801     std::string GroupName;
2802     if (Fn->hasComdat()) {
2803       Flags |= ELF::SHF_GROUP;
2804       GroupName = Fn->getComdat()->getName();
2805     }
2806 
2807     auto UniqueID = ++XRayFnUniqueID;
2808     InstMap =
2809         OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS, Flags, 0,
2810                                  GroupName, UniqueID, Associated);
2811     FnSledIndex =
2812         OutContext.getELFSection("xray_fn_idx", ELF::SHT_PROGBITS, Flags, 0,
2813                                  GroupName, UniqueID, Associated);
2814   } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) {
2815     InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map", 0,
2816                                          SectionKind::getReadOnlyWithRel());
2817     FnSledIndex = OutContext.getMachOSection("__DATA", "xray_fn_idx", 0,
2818                                              SectionKind::getReadOnlyWithRel());
2819   } else {
2820     llvm_unreachable("Unsupported target");
2821   }
2822 
2823   auto WordSizeBytes = MAI->getCodePointerSize();
2824 
2825   // Now we switch to the instrumentation map section. Because this is done
2826   // per-function, we are able to create an index entry that will represent the
2827   // range of sleds associated with a function.
2828   MCSymbol *SledsStart = OutContext.createTempSymbol("xray_sleds_start", true);
2829   OutStreamer->SwitchSection(InstMap);
2830   OutStreamer->EmitLabel(SledsStart);
2831   for (const auto &Sled : Sleds)
2832     Sled.emit(WordSizeBytes, OutStreamer.get(), CurrentFnSym);
2833   MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_sleds_end", true);
2834   OutStreamer->EmitLabel(SledsEnd);
2835 
2836   // We then emit a single entry in the index per function. We use the symbols
2837   // that bound the instrumentation map as the range for a specific function.
2838   // Each entry here will be 2 * word size aligned, as we're writing down two
2839   // pointers. This should work for both 32-bit and 64-bit platforms.
2840   OutStreamer->SwitchSection(FnSledIndex);
2841   OutStreamer->EmitCodeAlignment(2 * WordSizeBytes);
2842   OutStreamer->EmitSymbolValue(SledsStart, WordSizeBytes, false);
2843   OutStreamer->EmitSymbolValue(SledsEnd, WordSizeBytes, false);
2844   OutStreamer->SwitchSection(PrevSection);
2845   Sleds.clear();
2846 }
2847 
2848 void AsmPrinter::recordSled(MCSymbol *Sled, const MachineInstr &MI,
2849                             SledKind Kind, uint8_t Version) {
2850   auto Fn = MI.getParent()->getParent()->getFunction();
2851   auto Attr = Fn->getFnAttribute("function-instrument");
2852   bool LogArgs = Fn->hasFnAttribute("xray-log-args");
2853   bool AlwaysInstrument =
2854     Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always";
2855   if (Kind == SledKind::FUNCTION_ENTER && LogArgs)
2856     Kind = SledKind::LOG_ARGS_ENTER;
2857   Sleds.emplace_back(XRayFunctionEntry{Sled, CurrentFnSym, Kind,
2858                                        AlwaysInstrument, Fn, Version});
2859 }
2860 
2861 uint16_t AsmPrinter::getDwarfVersion() const {
2862   return OutStreamer->getContext().getDwarfVersion();
2863 }
2864 
2865 void AsmPrinter::setDwarfVersion(uint16_t Version) {
2866   OutStreamer->getContext().setDwarfVersion(Version);
2867 }
2868