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