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