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 bool AsmPrinter::doFinalization(Module &M) {
1064   // Set the MachineFunction to nullptr so that we can catch attempted
1065   // accesses to MF specific features at the module level and so that
1066   // we can conditionalize accesses based on whether or not it is nullptr.
1067   MF = nullptr;
1068 
1069   // Gather all GOT equivalent globals in the module. We really need two
1070   // passes over the globals: one to compute and another to avoid its emission
1071   // in EmitGlobalVariable, otherwise we would not be able to handle cases
1072   // where the got equivalent shows up before its use.
1073   computeGlobalGOTEquivs(M);
1074 
1075   // Emit global variables.
1076   for (const auto &G : M.globals())
1077     EmitGlobalVariable(&G);
1078 
1079   // Emit remaining GOT equivalent globals.
1080   emitGlobalGOTEquivs();
1081 
1082   // Emit visibility info for declarations
1083   for (const Function &F : M) {
1084     if (!F.isDeclarationForLinker())
1085       continue;
1086     GlobalValue::VisibilityTypes V = F.getVisibility();
1087     if (V == GlobalValue::DefaultVisibility)
1088       continue;
1089 
1090     MCSymbol *Name = getSymbol(&F);
1091     EmitVisibility(Name, V, false);
1092   }
1093 
1094   const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1095 
1096   // Emit module flags.
1097   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
1098   M.getModuleFlagsMetadata(ModuleFlags);
1099   if (!ModuleFlags.empty())
1100     TLOF.emitModuleFlags(*OutStreamer, ModuleFlags, *Mang, TM);
1101 
1102   if (TM.getTargetTriple().isOSBinFormatELF()) {
1103     MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
1104 
1105     // Output stubs for external and common global variables.
1106     MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
1107     if (!Stubs.empty()) {
1108       OutStreamer->SwitchSection(TLOF.getDataSection());
1109       const DataLayout &DL = M.getDataLayout();
1110 
1111       for (const auto &Stub : Stubs) {
1112         OutStreamer->EmitLabel(Stub.first);
1113         OutStreamer->EmitSymbolValue(Stub.second.getPointer(),
1114                                      DL.getPointerSize());
1115       }
1116     }
1117   }
1118 
1119   // Finalize debug and EH information.
1120   for (const HandlerInfo &HI : Handlers) {
1121     NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
1122                        TimePassesIsEnabled);
1123     HI.Handler->endModule();
1124     delete HI.Handler;
1125   }
1126   Handlers.clear();
1127   DD = nullptr;
1128 
1129   // If the target wants to know about weak references, print them all.
1130   if (MAI->getWeakRefDirective()) {
1131     // FIXME: This is not lazy, it would be nice to only print weak references
1132     // to stuff that is actually used.  Note that doing so would require targets
1133     // to notice uses in operands (due to constant exprs etc).  This should
1134     // happen with the MC stuff eventually.
1135 
1136     // Print out module-level global variables here.
1137     for (const auto &G : M.globals()) {
1138       if (!G.hasExternalWeakLinkage())
1139         continue;
1140       OutStreamer->EmitSymbolAttribute(getSymbol(&G), MCSA_WeakReference);
1141     }
1142 
1143     for (const auto &F : M) {
1144       if (!F.hasExternalWeakLinkage())
1145         continue;
1146       OutStreamer->EmitSymbolAttribute(getSymbol(&F), MCSA_WeakReference);
1147     }
1148   }
1149 
1150   OutStreamer->AddBlankLine();
1151   for (const auto &Alias : M.aliases()) {
1152     MCSymbol *Name = getSymbol(&Alias);
1153 
1154     if (Alias.hasExternalLinkage() || !MAI->getWeakRefDirective())
1155       OutStreamer->EmitSymbolAttribute(Name, MCSA_Global);
1156     else if (Alias.hasWeakLinkage() || Alias.hasLinkOnceLinkage())
1157       OutStreamer->EmitSymbolAttribute(Name, MCSA_WeakReference);
1158     else
1159       assert(Alias.hasLocalLinkage() && "Invalid alias linkage");
1160 
1161     // Set the symbol type to function if the alias has a function type.
1162     // This affects codegen when the aliasee is not a function.
1163     if (Alias.getType()->getPointerElementType()->isFunctionTy())
1164       OutStreamer->EmitSymbolAttribute(Name, MCSA_ELF_TypeFunction);
1165 
1166     EmitVisibility(Name, Alias.getVisibility());
1167 
1168     // Emit the directives as assignments aka .set:
1169     OutStreamer->EmitAssignment(Name, lowerConstant(Alias.getAliasee()));
1170 
1171     // If the aliasee does not correspond to a symbol in the output, i.e. the
1172     // alias is not of an object or the aliased object is private, then set the
1173     // size of the alias symbol from the type of the alias. We don't do this in
1174     // other situations as the alias and aliasee having differing types but same
1175     // size may be intentional.
1176     const GlobalObject *BaseObject = Alias.getBaseObject();
1177     if (MAI->hasDotTypeDotSizeDirective() && Alias.getValueType()->isSized() &&
1178         (!BaseObject || BaseObject->hasPrivateLinkage())) {
1179       const DataLayout &DL = M.getDataLayout();
1180       uint64_t Size = DL.getTypeAllocSize(Alias.getValueType());
1181       OutStreamer->emitELFSize(cast<MCSymbolELF>(Name),
1182                                MCConstantExpr::create(Size, OutContext));
1183     }
1184   }
1185 
1186   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
1187   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
1188   for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
1189     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
1190       MP->finishAssembly(M, *MI, *this);
1191 
1192   // Emit llvm.ident metadata in an '.ident' directive.
1193   EmitModuleIdents(M);
1194 
1195   // Emit __morestack address if needed for indirect calls.
1196   if (MMI->usesMorestackAddr()) {
1197     MCSection *ReadOnlySection = getObjFileLowering().getSectionForConstant(
1198         getDataLayout(), SectionKind::getReadOnly(),
1199         /*C=*/nullptr);
1200     OutStreamer->SwitchSection(ReadOnlySection);
1201 
1202     MCSymbol *AddrSymbol =
1203         OutContext.getOrCreateSymbol(StringRef("__morestack_addr"));
1204     OutStreamer->EmitLabel(AddrSymbol);
1205 
1206     unsigned PtrSize = M.getDataLayout().getPointerSize(0);
1207     OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("__morestack"),
1208                                  PtrSize);
1209   }
1210 
1211   // If we don't have any trampolines, then we don't require stack memory
1212   // to be executable. Some targets have a directive to declare this.
1213   Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1214   if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1215     if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
1216       OutStreamer->SwitchSection(S);
1217 
1218   // Allow the target to emit any magic that it wants at the end of the file,
1219   // after everything else has gone out.
1220   EmitEndOfAsmFile(M);
1221 
1222   delete Mang; Mang = nullptr;
1223   MMI = nullptr;
1224 
1225   OutStreamer->Finish();
1226   OutStreamer->reset();
1227 
1228   return false;
1229 }
1230 
1231 MCSymbol *AsmPrinter::getCurExceptionSym() {
1232   if (!CurExceptionSym)
1233     CurExceptionSym = createTempSymbol("exception");
1234   return CurExceptionSym;
1235 }
1236 
1237 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1238   this->MF = &MF;
1239   // Get the function symbol.
1240   CurrentFnSym = getSymbol(MF.getFunction());
1241   CurrentFnSymForSize = CurrentFnSym;
1242   CurrentFnBegin = nullptr;
1243   CurExceptionSym = nullptr;
1244   bool NeedsLocalForSize = MAI->needsLocalForSize();
1245   if (!MMI->getLandingPads().empty() || MMI->hasDebugInfo() ||
1246       MMI->hasEHFunclets() || NeedsLocalForSize) {
1247     CurrentFnBegin = createTempSymbol("func_begin");
1248     if (NeedsLocalForSize)
1249       CurrentFnSymForSize = CurrentFnBegin;
1250   }
1251 
1252   if (isVerbose())
1253     LI = &getAnalysis<MachineLoopInfo>();
1254 }
1255 
1256 namespace {
1257 // Keep track the alignment, constpool entries per Section.
1258   struct SectionCPs {
1259     MCSection *S;
1260     unsigned Alignment;
1261     SmallVector<unsigned, 4> CPEs;
1262     SectionCPs(MCSection *s, unsigned a) : S(s), Alignment(a) {}
1263   };
1264 }
1265 
1266 /// EmitConstantPool - Print to the current output stream assembly
1267 /// representations of the constants in the constant pool MCP. This is
1268 /// used to print out constants which have been "spilled to memory" by
1269 /// the code generator.
1270 ///
1271 void AsmPrinter::EmitConstantPool() {
1272   const MachineConstantPool *MCP = MF->getConstantPool();
1273   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1274   if (CP.empty()) return;
1275 
1276   // Calculate sections for constant pool entries. We collect entries to go into
1277   // the same section together to reduce amount of section switch statements.
1278   SmallVector<SectionCPs, 4> CPSections;
1279   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1280     const MachineConstantPoolEntry &CPE = CP[i];
1281     unsigned Align = CPE.getAlignment();
1282 
1283     SectionKind Kind = CPE.getSectionKind(&getDataLayout());
1284 
1285     const Constant *C = nullptr;
1286     if (!CPE.isMachineConstantPoolEntry())
1287       C = CPE.Val.ConstVal;
1288 
1289     MCSection *S =
1290         getObjFileLowering().getSectionForConstant(getDataLayout(), Kind, C);
1291 
1292     // The number of sections are small, just do a linear search from the
1293     // last section to the first.
1294     bool Found = false;
1295     unsigned SecIdx = CPSections.size();
1296     while (SecIdx != 0) {
1297       if (CPSections[--SecIdx].S == S) {
1298         Found = true;
1299         break;
1300       }
1301     }
1302     if (!Found) {
1303       SecIdx = CPSections.size();
1304       CPSections.push_back(SectionCPs(S, Align));
1305     }
1306 
1307     if (Align > CPSections[SecIdx].Alignment)
1308       CPSections[SecIdx].Alignment = Align;
1309     CPSections[SecIdx].CPEs.push_back(i);
1310   }
1311 
1312   // Now print stuff into the calculated sections.
1313   const MCSection *CurSection = nullptr;
1314   unsigned Offset = 0;
1315   for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1316     for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1317       unsigned CPI = CPSections[i].CPEs[j];
1318       MCSymbol *Sym = GetCPISymbol(CPI);
1319       if (!Sym->isUndefined())
1320         continue;
1321 
1322       if (CurSection != CPSections[i].S) {
1323         OutStreamer->SwitchSection(CPSections[i].S);
1324         EmitAlignment(Log2_32(CPSections[i].Alignment));
1325         CurSection = CPSections[i].S;
1326         Offset = 0;
1327       }
1328 
1329       MachineConstantPoolEntry CPE = CP[CPI];
1330 
1331       // Emit inter-object padding for alignment.
1332       unsigned AlignMask = CPE.getAlignment() - 1;
1333       unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1334       OutStreamer->EmitZeros(NewOffset - Offset);
1335 
1336       Type *Ty = CPE.getType();
1337       Offset = NewOffset + getDataLayout().getTypeAllocSize(Ty);
1338 
1339       OutStreamer->EmitLabel(Sym);
1340       if (CPE.isMachineConstantPoolEntry())
1341         EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1342       else
1343         EmitGlobalConstant(getDataLayout(), CPE.Val.ConstVal);
1344     }
1345   }
1346 }
1347 
1348 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1349 /// by the current function to the current output stream.
1350 ///
1351 void AsmPrinter::EmitJumpTableInfo() {
1352   const DataLayout &DL = MF->getDataLayout();
1353   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1354   if (!MJTI) return;
1355   if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1356   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1357   if (JT.empty()) return;
1358 
1359   // Pick the directive to use to print the jump table entries, and switch to
1360   // the appropriate section.
1361   const Function *F = MF->getFunction();
1362   const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1363   bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
1364       MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32,
1365       *F);
1366   if (JTInDiffSection) {
1367     // Drop it in the readonly section.
1368     MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(*F, *Mang, TM);
1369     OutStreamer->SwitchSection(ReadOnlySection);
1370   }
1371 
1372   EmitAlignment(Log2_32(MJTI->getEntryAlignment(DL)));
1373 
1374   // Jump tables in code sections are marked with a data_region directive
1375   // where that's supported.
1376   if (!JTInDiffSection)
1377     OutStreamer->EmitDataRegion(MCDR_DataRegionJT32);
1378 
1379   for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1380     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1381 
1382     // If this jump table was deleted, ignore it.
1383     if (JTBBs.empty()) continue;
1384 
1385     // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
1386     /// emit a .set directive for each unique entry.
1387     if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1388         MAI->doesSetDirectiveSuppressesReloc()) {
1389       SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1390       const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1391       const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1392       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1393         const MachineBasicBlock *MBB = JTBBs[ii];
1394         if (!EmittedSets.insert(MBB).second)
1395           continue;
1396 
1397         // .set LJTSet, LBB32-base
1398         const MCExpr *LHS =
1399           MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1400         OutStreamer->EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1401                                     MCBinaryExpr::createSub(LHS, Base,
1402                                                             OutContext));
1403       }
1404     }
1405 
1406     // On some targets (e.g. Darwin) we want to emit two consecutive labels
1407     // before each jump table.  The first label is never referenced, but tells
1408     // the assembler and linker the extents of the jump table object.  The
1409     // second label is actually referenced by the code.
1410     if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
1411       // FIXME: This doesn't have to have any specific name, just any randomly
1412       // named and numbered 'l' label would work.  Simplify GetJTISymbol.
1413       OutStreamer->EmitLabel(GetJTISymbol(JTI, true));
1414 
1415     OutStreamer->EmitLabel(GetJTISymbol(JTI));
1416 
1417     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1418       EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1419   }
1420   if (!JTInDiffSection)
1421     OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1422 }
1423 
1424 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1425 /// current stream.
1426 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1427                                     const MachineBasicBlock *MBB,
1428                                     unsigned UID) const {
1429   assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1430   const MCExpr *Value = nullptr;
1431   switch (MJTI->getEntryKind()) {
1432   case MachineJumpTableInfo::EK_Inline:
1433     llvm_unreachable("Cannot emit EK_Inline jump table entry");
1434   case MachineJumpTableInfo::EK_Custom32:
1435     Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
1436         MJTI, MBB, UID, OutContext);
1437     break;
1438   case MachineJumpTableInfo::EK_BlockAddress:
1439     // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1440     //     .word LBB123
1441     Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1442     break;
1443   case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1444     // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1445     // with a relocation as gp-relative, e.g.:
1446     //     .gprel32 LBB123
1447     MCSymbol *MBBSym = MBB->getSymbol();
1448     OutStreamer->EmitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext));
1449     return;
1450   }
1451 
1452   case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1453     // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1454     // with a relocation as gp-relative, e.g.:
1455     //     .gpdword LBB123
1456     MCSymbol *MBBSym = MBB->getSymbol();
1457     OutStreamer->EmitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext));
1458     return;
1459   }
1460 
1461   case MachineJumpTableInfo::EK_LabelDifference32: {
1462     // Each entry is the address of the block minus the address of the jump
1463     // table. This is used for PIC jump tables where gprel32 is not supported.
1464     // e.g.:
1465     //      .word LBB123 - LJTI1_2
1466     // If the .set directive avoids relocations, this is emitted as:
1467     //      .set L4_5_set_123, LBB123 - LJTI1_2
1468     //      .word L4_5_set_123
1469     if (MAI->doesSetDirectiveSuppressesReloc()) {
1470       Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()),
1471                                       OutContext);
1472       break;
1473     }
1474     Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1475     const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1476     const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
1477     Value = MCBinaryExpr::createSub(Value, Base, OutContext);
1478     break;
1479   }
1480   }
1481 
1482   assert(Value && "Unknown entry kind!");
1483 
1484   unsigned EntrySize = MJTI->getEntrySize(getDataLayout());
1485   OutStreamer->EmitValue(Value, EntrySize);
1486 }
1487 
1488 
1489 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1490 /// special global used by LLVM.  If so, emit it and return true, otherwise
1491 /// do nothing and return false.
1492 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1493   if (GV->getName() == "llvm.used") {
1494     if (MAI->hasNoDeadStrip())    // No need to emit this at all.
1495       EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1496     return true;
1497   }
1498 
1499   // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
1500   if (StringRef(GV->getSection()) == "llvm.metadata" ||
1501       GV->hasAvailableExternallyLinkage())
1502     return true;
1503 
1504   if (!GV->hasAppendingLinkage()) return false;
1505 
1506   assert(GV->hasInitializer() && "Not a special LLVM global!");
1507 
1508   if (GV->getName() == "llvm.global_ctors") {
1509     EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
1510                        /* isCtor */ true);
1511 
1512     if (TM.getRelocationModel() == Reloc::Static &&
1513         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1514       StringRef Sym(".constructors_used");
1515       OutStreamer->EmitSymbolAttribute(OutContext.getOrCreateSymbol(Sym),
1516                                        MCSA_Reference);
1517     }
1518     return true;
1519   }
1520 
1521   if (GV->getName() == "llvm.global_dtors") {
1522     EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
1523                        /* isCtor */ false);
1524 
1525     if (TM.getRelocationModel() == Reloc::Static &&
1526         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1527       StringRef Sym(".destructors_used");
1528       OutStreamer->EmitSymbolAttribute(OutContext.getOrCreateSymbol(Sym),
1529                                        MCSA_Reference);
1530     }
1531     return true;
1532   }
1533 
1534   return false;
1535 }
1536 
1537 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1538 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1539 /// is true, as being used with this directive.
1540 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1541   // Should be an array of 'i8*'.
1542   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1543     const GlobalValue *GV =
1544       dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1545     if (GV)
1546       OutStreamer->EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1547   }
1548 }
1549 
1550 namespace {
1551 struct Structor {
1552   Structor() : Priority(0), Func(nullptr), ComdatKey(nullptr) {}
1553   int Priority;
1554   llvm::Constant *Func;
1555   llvm::GlobalValue *ComdatKey;
1556 };
1557 } // end namespace
1558 
1559 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1560 /// priority.
1561 void AsmPrinter::EmitXXStructorList(const DataLayout &DL, const Constant *List,
1562                                     bool isCtor) {
1563   // Should be an array of '{ int, void ()* }' structs.  The first value is the
1564   // init priority.
1565   if (!isa<ConstantArray>(List)) return;
1566 
1567   // Sanity check the structors list.
1568   const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1569   if (!InitList) return; // Not an array!
1570   StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1571   // FIXME: Only allow the 3-field form in LLVM 4.0.
1572   if (!ETy || ETy->getNumElements() < 2 || ETy->getNumElements() > 3)
1573     return; // Not an array of two or three elements!
1574   if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1575       !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1576   if (ETy->getNumElements() == 3 && !isa<PointerType>(ETy->getTypeAtIndex(2U)))
1577     return; // Not (int, ptr, ptr).
1578 
1579   // Gather the structors in a form that's convenient for sorting by priority.
1580   SmallVector<Structor, 8> Structors;
1581   for (Value *O : InitList->operands()) {
1582     ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
1583     if (!CS) continue; // Malformed.
1584     if (CS->getOperand(1)->isNullValue())
1585       break;  // Found a null terminator, skip the rest.
1586     ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1587     if (!Priority) continue; // Malformed.
1588     Structors.push_back(Structor());
1589     Structor &S = Structors.back();
1590     S.Priority = Priority->getLimitedValue(65535);
1591     S.Func = CS->getOperand(1);
1592     if (ETy->getNumElements() == 3 && !CS->getOperand(2)->isNullValue())
1593       S.ComdatKey = dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
1594   }
1595 
1596   // Emit the function pointers in the target-specific order
1597   unsigned Align = Log2_32(DL.getPointerPrefAlignment());
1598   std::stable_sort(Structors.begin(), Structors.end(),
1599                    [](const Structor &L,
1600                       const Structor &R) { return L.Priority < R.Priority; });
1601   for (Structor &S : Structors) {
1602     const TargetLoweringObjectFile &Obj = getObjFileLowering();
1603     const MCSymbol *KeySym = nullptr;
1604     if (GlobalValue *GV = S.ComdatKey) {
1605       if (GV->hasAvailableExternallyLinkage())
1606         // If the associated variable is available_externally, some other TU
1607         // will provide its dynamic initializer.
1608         continue;
1609 
1610       KeySym = getSymbol(GV);
1611     }
1612     MCSection *OutputSection =
1613         (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
1614                 : Obj.getStaticDtorSection(S.Priority, KeySym));
1615     OutStreamer->SwitchSection(OutputSection);
1616     if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
1617       EmitAlignment(Align);
1618     EmitXXStructor(DL, S.Func);
1619   }
1620 }
1621 
1622 void AsmPrinter::EmitModuleIdents(Module &M) {
1623   if (!MAI->hasIdentDirective())
1624     return;
1625 
1626   if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1627     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1628       const MDNode *N = NMD->getOperand(i);
1629       assert(N->getNumOperands() == 1 &&
1630              "llvm.ident metadata entry can have only one operand");
1631       const MDString *S = cast<MDString>(N->getOperand(0));
1632       OutStreamer->EmitIdent(S->getString());
1633     }
1634   }
1635 }
1636 
1637 //===--------------------------------------------------------------------===//
1638 // Emission and print routines
1639 //
1640 
1641 /// EmitInt8 - Emit a byte directive and value.
1642 ///
1643 void AsmPrinter::EmitInt8(int Value) const {
1644   OutStreamer->EmitIntValue(Value, 1);
1645 }
1646 
1647 /// EmitInt16 - Emit a short directive and value.
1648 ///
1649 void AsmPrinter::EmitInt16(int Value) const {
1650   OutStreamer->EmitIntValue(Value, 2);
1651 }
1652 
1653 /// EmitInt32 - Emit a long directive and value.
1654 ///
1655 void AsmPrinter::EmitInt32(int Value) const {
1656   OutStreamer->EmitIntValue(Value, 4);
1657 }
1658 
1659 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
1660 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
1661 /// .set if it avoids relocations.
1662 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1663                                      unsigned Size) const {
1664   OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
1665 }
1666 
1667 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1668 /// where the size in bytes of the directive is specified by Size and Label
1669 /// specifies the label.  This implicitly uses .set if it is available.
1670 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1671                                      unsigned Size,
1672                                      bool IsSectionRelative) const {
1673   if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
1674     OutStreamer->EmitCOFFSecRel32(Label);
1675     return;
1676   }
1677 
1678   // Emit Label+Offset (or just Label if Offset is zero)
1679   const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
1680   if (Offset)
1681     Expr = MCBinaryExpr::createAdd(
1682         Expr, MCConstantExpr::create(Offset, OutContext), OutContext);
1683 
1684   OutStreamer->EmitValue(Expr, Size);
1685 }
1686 
1687 //===----------------------------------------------------------------------===//
1688 
1689 // EmitAlignment - Emit an alignment directive to the specified power of
1690 // two boundary.  For example, if you pass in 3 here, you will get an 8
1691 // byte alignment.  If a global value is specified, and if that global has
1692 // an explicit alignment requested, it will override the alignment request
1693 // if required for correctness.
1694 //
1695 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalObject *GV) const {
1696   if (GV)
1697     NumBits = getGVAlignmentLog2(GV, GV->getParent()->getDataLayout(), NumBits);
1698 
1699   if (NumBits == 0) return;   // 1-byte aligned: no need to emit alignment.
1700 
1701   assert(NumBits <
1702              static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
1703          "undefined behavior");
1704   if (getCurrentSection()->getKind().isText())
1705     OutStreamer->EmitCodeAlignment(1u << NumBits);
1706   else
1707     OutStreamer->EmitValueToAlignment(1u << NumBits);
1708 }
1709 
1710 //===----------------------------------------------------------------------===//
1711 // Constant emission.
1712 //===----------------------------------------------------------------------===//
1713 
1714 const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) {
1715   MCContext &Ctx = OutContext;
1716 
1717   if (CV->isNullValue() || isa<UndefValue>(CV))
1718     return MCConstantExpr::create(0, Ctx);
1719 
1720   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1721     return MCConstantExpr::create(CI->getZExtValue(), Ctx);
1722 
1723   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1724     return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
1725 
1726   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1727     return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx);
1728 
1729   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1730   if (!CE) {
1731     llvm_unreachable("Unknown constant value to lower!");
1732   }
1733 
1734   if (const MCExpr *RelocExpr
1735       = getObjFileLowering().getExecutableRelativeSymbol(CE, *Mang, TM))
1736     return RelocExpr;
1737 
1738   switch (CE->getOpcode()) {
1739   default:
1740     // If the code isn't optimized, there may be outstanding folding
1741     // opportunities. Attempt to fold the expression using DataLayout as a
1742     // last resort before giving up.
1743     if (Constant *C = ConstantFoldConstantExpression(CE, getDataLayout()))
1744       if (C != CE)
1745         return lowerConstant(C);
1746 
1747     // Otherwise report the problem to the user.
1748     {
1749       std::string S;
1750       raw_string_ostream OS(S);
1751       OS << "Unsupported expression in static initializer: ";
1752       CE->printAsOperand(OS, /*PrintType=*/false,
1753                      !MF ? nullptr : MF->getFunction()->getParent());
1754       report_fatal_error(OS.str());
1755     }
1756   case Instruction::GetElementPtr: {
1757     // Generate a symbolic expression for the byte address
1758     APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
1759     cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
1760 
1761     const MCExpr *Base = lowerConstant(CE->getOperand(0));
1762     if (!OffsetAI)
1763       return Base;
1764 
1765     int64_t Offset = OffsetAI.getSExtValue();
1766     return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
1767                                    Ctx);
1768   }
1769 
1770   case Instruction::Trunc:
1771     // We emit the value and depend on the assembler to truncate the generated
1772     // expression properly.  This is important for differences between
1773     // blockaddress labels.  Since the two labels are in the same function, it
1774     // is reasonable to treat their delta as a 32-bit value.
1775     // FALL THROUGH.
1776   case Instruction::BitCast:
1777     return lowerConstant(CE->getOperand(0));
1778 
1779   case Instruction::IntToPtr: {
1780     const DataLayout &DL = getDataLayout();
1781 
1782     // Handle casts to pointers by changing them into casts to the appropriate
1783     // integer type.  This promotes constant folding and simplifies this code.
1784     Constant *Op = CE->getOperand(0);
1785     Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
1786                                       false/*ZExt*/);
1787     return lowerConstant(Op);
1788   }
1789 
1790   case Instruction::PtrToInt: {
1791     const DataLayout &DL = getDataLayout();
1792 
1793     // Support only foldable casts to/from pointers that can be eliminated by
1794     // changing the pointer to the appropriately sized integer type.
1795     Constant *Op = CE->getOperand(0);
1796     Type *Ty = CE->getType();
1797 
1798     const MCExpr *OpExpr = lowerConstant(Op);
1799 
1800     // We can emit the pointer value into this slot if the slot is an
1801     // integer slot equal to the size of the pointer.
1802     if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
1803       return OpExpr;
1804 
1805     // Otherwise the pointer is smaller than the resultant integer, mask off
1806     // the high bits so we are sure to get a proper truncation if the input is
1807     // a constant expr.
1808     unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1809     const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
1810     return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
1811   }
1812 
1813   // The MC library also has a right-shift operator, but it isn't consistently
1814   // signed or unsigned between different targets.
1815   case Instruction::Add:
1816   case Instruction::Sub:
1817   case Instruction::Mul:
1818   case Instruction::SDiv:
1819   case Instruction::SRem:
1820   case Instruction::Shl:
1821   case Instruction::And:
1822   case Instruction::Or:
1823   case Instruction::Xor: {
1824     const MCExpr *LHS = lowerConstant(CE->getOperand(0));
1825     const MCExpr *RHS = lowerConstant(CE->getOperand(1));
1826     switch (CE->getOpcode()) {
1827     default: llvm_unreachable("Unknown binary operator constant cast expr");
1828     case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
1829     case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx);
1830     case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx);
1831     case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx);
1832     case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx);
1833     case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx);
1834     case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx);
1835     case Instruction::Or:  return MCBinaryExpr::createOr (LHS, RHS, Ctx);
1836     case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx);
1837     }
1838   }
1839   }
1840 }
1841 
1842 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
1843                                    AsmPrinter &AP,
1844                                    const Constant *BaseCV = nullptr,
1845                                    uint64_t Offset = 0);
1846 
1847 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
1848 
1849 /// isRepeatedByteSequence - Determine whether the given value is
1850 /// composed of a repeated sequence of identical bytes and return the
1851 /// byte value.  If it is not a repeated sequence, return -1.
1852 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1853   StringRef Data = V->getRawDataValues();
1854   assert(!Data.empty() && "Empty aggregates should be CAZ node");
1855   char C = Data[0];
1856   for (unsigned i = 1, e = Data.size(); i != e; ++i)
1857     if (Data[i] != C) return -1;
1858   return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1859 }
1860 
1861 
1862 /// isRepeatedByteSequence - Determine whether the given value is
1863 /// composed of a repeated sequence of identical bytes and return the
1864 /// byte value.  If it is not a repeated sequence, return -1.
1865 static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
1866   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1867     uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
1868     assert(Size % 8 == 0);
1869 
1870     // Extend the element to take zero padding into account.
1871     APInt Value = CI->getValue().zextOrSelf(Size);
1872     if (!Value.isSplat(8))
1873       return -1;
1874 
1875     return Value.zextOrTrunc(8).getZExtValue();
1876   }
1877   if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1878     // Make sure all array elements are sequences of the same repeated
1879     // byte.
1880     assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1881     Constant *Op0 = CA->getOperand(0);
1882     int Byte = isRepeatedByteSequence(Op0, DL);
1883     if (Byte == -1)
1884       return -1;
1885 
1886     // All array elements must be equal.
1887     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
1888       if (CA->getOperand(i) != Op0)
1889         return -1;
1890     return Byte;
1891   }
1892 
1893   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1894     return isRepeatedByteSequence(CDS);
1895 
1896   return -1;
1897 }
1898 
1899 static void emitGlobalConstantDataSequential(const DataLayout &DL,
1900                                              const ConstantDataSequential *CDS,
1901                                              AsmPrinter &AP) {
1902 
1903   // See if we can aggregate this into a .fill, if so, emit it as such.
1904   int Value = isRepeatedByteSequence(CDS, DL);
1905   if (Value != -1) {
1906     uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
1907     // Don't emit a 1-byte object as a .fill.
1908     if (Bytes > 1)
1909       return AP.OutStreamer->EmitFill(Bytes, Value);
1910   }
1911 
1912   // If this can be emitted with .ascii/.asciz, emit it as such.
1913   if (CDS->isString())
1914     return AP.OutStreamer->EmitBytes(CDS->getAsString());
1915 
1916   // Otherwise, emit the values in successive locations.
1917   unsigned ElementByteSize = CDS->getElementByteSize();
1918   if (isa<IntegerType>(CDS->getElementType())) {
1919     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1920       if (AP.isVerbose())
1921         AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
1922                                                  CDS->getElementAsInteger(i));
1923       AP.OutStreamer->EmitIntValue(CDS->getElementAsInteger(i),
1924                                    ElementByteSize);
1925     }
1926   } else {
1927     for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I)
1928       emitGlobalConstantFP(cast<ConstantFP>(CDS->getElementAsConstant(I)), AP);
1929   }
1930 
1931   unsigned Size = DL.getTypeAllocSize(CDS->getType());
1932   unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
1933                         CDS->getNumElements();
1934   if (unsigned Padding = Size - EmittedSize)
1935     AP.OutStreamer->EmitZeros(Padding);
1936 
1937 }
1938 
1939 static void emitGlobalConstantArray(const DataLayout &DL,
1940                                     const ConstantArray *CA, AsmPrinter &AP,
1941                                     const Constant *BaseCV, uint64_t Offset) {
1942   // See if we can aggregate some values.  Make sure it can be
1943   // represented as a series of bytes of the constant value.
1944   int Value = isRepeatedByteSequence(CA, DL);
1945 
1946   if (Value != -1) {
1947     uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
1948     AP.OutStreamer->EmitFill(Bytes, Value);
1949   }
1950   else {
1951     for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1952       emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset);
1953       Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
1954     }
1955   }
1956 }
1957 
1958 static void emitGlobalConstantVector(const DataLayout &DL,
1959                                      const ConstantVector *CV, AsmPrinter &AP) {
1960   for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1961     emitGlobalConstantImpl(DL, CV->getOperand(i), AP);
1962 
1963   unsigned Size = DL.getTypeAllocSize(CV->getType());
1964   unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
1965                          CV->getType()->getNumElements();
1966   if (unsigned Padding = Size - EmittedSize)
1967     AP.OutStreamer->EmitZeros(Padding);
1968 }
1969 
1970 static void emitGlobalConstantStruct(const DataLayout &DL,
1971                                      const ConstantStruct *CS, AsmPrinter &AP,
1972                                      const Constant *BaseCV, uint64_t Offset) {
1973   // Print the fields in successive locations. Pad to align if needed!
1974   unsigned Size = DL.getTypeAllocSize(CS->getType());
1975   const StructLayout *Layout = DL.getStructLayout(CS->getType());
1976   uint64_t SizeSoFar = 0;
1977   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1978     const Constant *Field = CS->getOperand(i);
1979 
1980     // Print the actual field value.
1981     emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar);
1982 
1983     // Check if padding is needed and insert one or more 0s.
1984     uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
1985     uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1986                         - Layout->getElementOffset(i)) - FieldSize;
1987     SizeSoFar += FieldSize + PadSize;
1988 
1989     // Insert padding - this may include padding to increase the size of the
1990     // current field up to the ABI size (if the struct is not packed) as well
1991     // as padding to ensure that the next field starts at the right offset.
1992     AP.OutStreamer->EmitZeros(PadSize);
1993   }
1994   assert(SizeSoFar == Layout->getSizeInBytes() &&
1995          "Layout of constant struct may be incorrect!");
1996 }
1997 
1998 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
1999   APInt API = CFP->getValueAPF().bitcastToAPInt();
2000 
2001   // First print a comment with what we think the original floating-point value
2002   // should have been.
2003   if (AP.isVerbose()) {
2004     SmallString<8> StrVal;
2005     CFP->getValueAPF().toString(StrVal);
2006 
2007     if (CFP->getType())
2008       CFP->getType()->print(AP.OutStreamer->GetCommentOS());
2009     else
2010       AP.OutStreamer->GetCommentOS() << "Printing <null> Type";
2011     AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n';
2012   }
2013 
2014   // Now iterate through the APInt chunks, emitting them in endian-correct
2015   // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
2016   // floats).
2017   unsigned NumBytes = API.getBitWidth() / 8;
2018   unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
2019   const uint64_t *p = API.getRawData();
2020 
2021   // PPC's long double has odd notions of endianness compared to how LLVM
2022   // handles it: p[0] goes first for *big* endian on PPC.
2023   if (AP.getDataLayout().isBigEndian() && !CFP->getType()->isPPC_FP128Ty()) {
2024     int Chunk = API.getNumWords() - 1;
2025 
2026     if (TrailingBytes)
2027       AP.OutStreamer->EmitIntValue(p[Chunk--], TrailingBytes);
2028 
2029     for (; Chunk >= 0; --Chunk)
2030       AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
2031   } else {
2032     unsigned Chunk;
2033     for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
2034       AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
2035 
2036     if (TrailingBytes)
2037       AP.OutStreamer->EmitIntValue(p[Chunk], TrailingBytes);
2038   }
2039 
2040   // Emit the tail padding for the long double.
2041   const DataLayout &DL = AP.getDataLayout();
2042   AP.OutStreamer->EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
2043                             DL.getTypeStoreSize(CFP->getType()));
2044 }
2045 
2046 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
2047   const DataLayout &DL = AP.getDataLayout();
2048   unsigned BitWidth = CI->getBitWidth();
2049 
2050   // Copy the value as we may massage the layout for constants whose bit width
2051   // is not a multiple of 64-bits.
2052   APInt Realigned(CI->getValue());
2053   uint64_t ExtraBits = 0;
2054   unsigned ExtraBitsSize = BitWidth & 63;
2055 
2056   if (ExtraBitsSize) {
2057     // The bit width of the data is not a multiple of 64-bits.
2058     // The extra bits are expected to be at the end of the chunk of the memory.
2059     // Little endian:
2060     // * Nothing to be done, just record the extra bits to emit.
2061     // Big endian:
2062     // * Record the extra bits to emit.
2063     // * Realign the raw data to emit the chunks of 64-bits.
2064     if (DL.isBigEndian()) {
2065       // Basically the structure of the raw data is a chunk of 64-bits cells:
2066       //    0        1         BitWidth / 64
2067       // [chunk1][chunk2] ... [chunkN].
2068       // The most significant chunk is chunkN and it should be emitted first.
2069       // However, due to the alignment issue chunkN contains useless bits.
2070       // Realign the chunks so that they contain only useless information:
2071       // ExtraBits     0       1       (BitWidth / 64) - 1
2072       //       chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
2073       ExtraBits = Realigned.getRawData()[0] &
2074         (((uint64_t)-1) >> (64 - ExtraBitsSize));
2075       Realigned = Realigned.lshr(ExtraBitsSize);
2076     } else
2077       ExtraBits = Realigned.getRawData()[BitWidth / 64];
2078   }
2079 
2080   // We don't expect assemblers to support integer data directives
2081   // for more than 64 bits, so we emit the data in at most 64-bit
2082   // quantities at a time.
2083   const uint64_t *RawData = Realigned.getRawData();
2084   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
2085     uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
2086     AP.OutStreamer->EmitIntValue(Val, 8);
2087   }
2088 
2089   if (ExtraBitsSize) {
2090     // Emit the extra bits after the 64-bits chunks.
2091 
2092     // Emit a directive that fills the expected size.
2093     uint64_t Size = AP.getDataLayout().getTypeAllocSize(CI->getType());
2094     Size -= (BitWidth / 64) * 8;
2095     assert(Size && Size * 8 >= ExtraBitsSize &&
2096            (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
2097            == ExtraBits && "Directive too small for extra bits.");
2098     AP.OutStreamer->EmitIntValue(ExtraBits, Size);
2099   }
2100 }
2101 
2102 /// \brief Transform a not absolute MCExpr containing a reference to a GOT
2103 /// equivalent global, by a target specific GOT pc relative access to the
2104 /// final symbol.
2105 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
2106                                          const Constant *BaseCst,
2107                                          uint64_t Offset) {
2108   // The global @foo below illustrates a global that uses a got equivalent.
2109   //
2110   //  @bar = global i32 42
2111   //  @gotequiv = private unnamed_addr constant i32* @bar
2112   //  @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
2113   //                             i64 ptrtoint (i32* @foo to i64))
2114   //                        to i32)
2115   //
2116   // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
2117   // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
2118   // form:
2119   //
2120   //  foo = cstexpr, where
2121   //    cstexpr := <gotequiv> - "." + <cst>
2122   //    cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
2123   //
2124   // After canonicalization by evaluateAsRelocatable `ME` turns into:
2125   //
2126   //  cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
2127   //    gotpcrelcst := <offset from @foo base> + <cst>
2128   //
2129   MCValue MV;
2130   if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
2131     return;
2132   const MCSymbolRefExpr *SymA = MV.getSymA();
2133   if (!SymA)
2134     return;
2135 
2136   // Check that GOT equivalent symbol is cached.
2137   const MCSymbol *GOTEquivSym = &SymA->getSymbol();
2138   if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
2139     return;
2140 
2141   const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
2142   if (!BaseGV)
2143     return;
2144 
2145   // Check for a valid base symbol
2146   const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
2147   const MCSymbolRefExpr *SymB = MV.getSymB();
2148 
2149   if (!SymB || BaseSym != &SymB->getSymbol())
2150     return;
2151 
2152   // Make sure to match:
2153   //
2154   //    gotpcrelcst := <offset from @foo base> + <cst>
2155   //
2156   // If gotpcrelcst is positive it means that we can safely fold the pc rel
2157   // displacement into the GOTPCREL. We can also can have an extra offset <cst>
2158   // if the target knows how to encode it.
2159   //
2160   int64_t GOTPCRelCst = Offset + MV.getConstant();
2161   if (GOTPCRelCst < 0)
2162     return;
2163   if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
2164     return;
2165 
2166   // Emit the GOT PC relative to replace the got equivalent global, i.e.:
2167   //
2168   //  bar:
2169   //    .long 42
2170   //  gotequiv:
2171   //    .quad bar
2172   //  foo:
2173   //    .long gotequiv - "." + <cst>
2174   //
2175   // is replaced by the target specific equivalent to:
2176   //
2177   //  bar:
2178   //    .long 42
2179   //  foo:
2180   //    .long bar@GOTPCREL+<gotpcrelcst>
2181   //
2182   AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
2183   const GlobalVariable *GV = Result.first;
2184   int NumUses = (int)Result.second;
2185   const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
2186   const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
2187   *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel(
2188       FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
2189 
2190   // Update GOT equivalent usage information
2191   --NumUses;
2192   if (NumUses >= 0)
2193     AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
2194 }
2195 
2196 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
2197                                    AsmPrinter &AP, const Constant *BaseCV,
2198                                    uint64_t Offset) {
2199   uint64_t Size = DL.getTypeAllocSize(CV->getType());
2200 
2201   // Globals with sub-elements such as combinations of arrays and structs
2202   // are handled recursively by emitGlobalConstantImpl. Keep track of the
2203   // constant symbol base and the current position with BaseCV and Offset.
2204   if (!BaseCV && CV->hasOneUse())
2205     BaseCV = dyn_cast<Constant>(CV->user_back());
2206 
2207   if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
2208     return AP.OutStreamer->EmitZeros(Size);
2209 
2210   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
2211     switch (Size) {
2212     case 1:
2213     case 2:
2214     case 4:
2215     case 8:
2216       if (AP.isVerbose())
2217         AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
2218                                                  CI->getZExtValue());
2219       AP.OutStreamer->EmitIntValue(CI->getZExtValue(), Size);
2220       return;
2221     default:
2222       emitGlobalConstantLargeInt(CI, AP);
2223       return;
2224     }
2225   }
2226 
2227   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
2228     return emitGlobalConstantFP(CFP, AP);
2229 
2230   if (isa<ConstantPointerNull>(CV)) {
2231     AP.OutStreamer->EmitIntValue(0, Size);
2232     return;
2233   }
2234 
2235   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
2236     return emitGlobalConstantDataSequential(DL, CDS, AP);
2237 
2238   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
2239     return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset);
2240 
2241   if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
2242     return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset);
2243 
2244   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
2245     // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
2246     // vectors).
2247     if (CE->getOpcode() == Instruction::BitCast)
2248       return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
2249 
2250     if (Size > 8) {
2251       // If the constant expression's size is greater than 64-bits, then we have
2252       // to emit the value in chunks. Try to constant fold the value and emit it
2253       // that way.
2254       Constant *New = ConstantFoldConstantExpression(CE, DL);
2255       if (New && New != CE)
2256         return emitGlobalConstantImpl(DL, New, AP);
2257     }
2258   }
2259 
2260   if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
2261     return emitGlobalConstantVector(DL, V, AP);
2262 
2263   // Otherwise, it must be a ConstantExpr.  Lower it to an MCExpr, then emit it
2264   // thread the streamer with EmitValue.
2265   const MCExpr *ME = AP.lowerConstant(CV);
2266 
2267   // Since lowerConstant already folded and got rid of all IR pointer and
2268   // integer casts, detect GOT equivalent accesses by looking into the MCExpr
2269   // directly.
2270   if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel())
2271     handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
2272 
2273   AP.OutStreamer->EmitValue(ME, Size);
2274 }
2275 
2276 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
2277 void AsmPrinter::EmitGlobalConstant(const DataLayout &DL, const Constant *CV) {
2278   uint64_t Size = DL.getTypeAllocSize(CV->getType());
2279   if (Size)
2280     emitGlobalConstantImpl(DL, CV, *this);
2281   else if (MAI->hasSubsectionsViaSymbols()) {
2282     // If the global has zero size, emit a single byte so that two labels don't
2283     // look like they are at the same location.
2284     OutStreamer->EmitIntValue(0, 1);
2285   }
2286 }
2287 
2288 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
2289   // Target doesn't support this yet!
2290   llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
2291 }
2292 
2293 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
2294   if (Offset > 0)
2295     OS << '+' << Offset;
2296   else if (Offset < 0)
2297     OS << Offset;
2298 }
2299 
2300 //===----------------------------------------------------------------------===//
2301 // Symbol Lowering Routines.
2302 //===----------------------------------------------------------------------===//
2303 
2304 MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const {
2305   return OutContext.createTempSymbol(Name, true);
2306 }
2307 
2308 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2309   return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2310 }
2311 
2312 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2313   return MMI->getAddrLabelSymbol(BB);
2314 }
2315 
2316 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
2317 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2318   const DataLayout &DL = getDataLayout();
2319   return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
2320                                       "CPI" + Twine(getFunctionNumber()) + "_" +
2321                                       Twine(CPID));
2322 }
2323 
2324 /// GetJTISymbol - Return the symbol for the specified jump table entry.
2325 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2326   return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2327 }
2328 
2329 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2330 /// FIXME: privatize to AsmPrinter.
2331 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2332   const DataLayout &DL = getDataLayout();
2333   return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
2334                                       Twine(getFunctionNumber()) + "_" +
2335                                       Twine(UID) + "_set_" + Twine(MBBID));
2336 }
2337 
2338 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
2339                                                    StringRef Suffix) const {
2340   return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, *Mang,
2341                                                            TM);
2342 }
2343 
2344 /// Return the MCSymbol for the specified ExternalSymbol.
2345 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2346   SmallString<60> NameStr;
2347   Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout());
2348   return OutContext.getOrCreateSymbol(NameStr);
2349 }
2350 
2351 
2352 
2353 /// PrintParentLoopComment - Print comments about parent loops of this one.
2354 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2355                                    unsigned FunctionNumber) {
2356   if (!Loop) return;
2357   PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2358   OS.indent(Loop->getLoopDepth()*2)
2359     << "Parent Loop BB" << FunctionNumber << "_"
2360     << Loop->getHeader()->getNumber()
2361     << " Depth=" << Loop->getLoopDepth() << '\n';
2362 }
2363 
2364 
2365 /// PrintChildLoopComment - Print comments about child loops within
2366 /// the loop for this basic block, with nesting.
2367 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2368                                   unsigned FunctionNumber) {
2369   // Add child loop information
2370   for (const MachineLoop *CL : *Loop) {
2371     OS.indent(CL->getLoopDepth()*2)
2372       << "Child Loop BB" << FunctionNumber << "_"
2373       << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
2374       << '\n';
2375     PrintChildLoopComment(OS, CL, FunctionNumber);
2376   }
2377 }
2378 
2379 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2380 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2381                                        const MachineLoopInfo *LI,
2382                                        const AsmPrinter &AP) {
2383   // Add loop depth information
2384   const MachineLoop *Loop = LI->getLoopFor(&MBB);
2385   if (!Loop) return;
2386 
2387   MachineBasicBlock *Header = Loop->getHeader();
2388   assert(Header && "No header for loop");
2389 
2390   // If this block is not a loop header, just print out what is the loop header
2391   // and return.
2392   if (Header != &MBB) {
2393     AP.OutStreamer->AddComment("  in Loop: Header=BB" +
2394                                Twine(AP.getFunctionNumber())+"_" +
2395                                Twine(Loop->getHeader()->getNumber())+
2396                                " Depth="+Twine(Loop->getLoopDepth()));
2397     return;
2398   }
2399 
2400   // Otherwise, it is a loop header.  Print out information about child and
2401   // parent loops.
2402   raw_ostream &OS = AP.OutStreamer->GetCommentOS();
2403 
2404   PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2405 
2406   OS << "=>";
2407   OS.indent(Loop->getLoopDepth()*2-2);
2408 
2409   OS << "This ";
2410   if (Loop->empty())
2411     OS << "Inner ";
2412   OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2413 
2414   PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2415 }
2416 
2417 
2418 /// EmitBasicBlockStart - This method prints the label for the specified
2419 /// MachineBasicBlock, an alignment (if present) and a comment describing
2420 /// it if appropriate.
2421 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
2422   // End the previous funclet and start a new one.
2423   if (MBB.isEHFuncletEntry()) {
2424     for (const HandlerInfo &HI : Handlers) {
2425       HI.Handler->endFunclet();
2426       HI.Handler->beginFunclet(MBB);
2427     }
2428   }
2429 
2430   // Emit an alignment directive for this block, if needed.
2431   if (unsigned Align = MBB.getAlignment())
2432     EmitAlignment(Align);
2433 
2434   // If the block has its address taken, emit any labels that were used to
2435   // reference the block.  It is possible that there is more than one label
2436   // here, because multiple LLVM BB's may have been RAUW'd to this block after
2437   // the references were generated.
2438   if (MBB.hasAddressTaken()) {
2439     const BasicBlock *BB = MBB.getBasicBlock();
2440     if (isVerbose())
2441       OutStreamer->AddComment("Block address taken");
2442 
2443     // MBBs can have their address taken as part of CodeGen without having
2444     // their corresponding BB's address taken in IR
2445     if (BB->hasAddressTaken())
2446       for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB))
2447         OutStreamer->EmitLabel(Sym);
2448   }
2449 
2450   // Print some verbose block comments.
2451   if (isVerbose()) {
2452     if (const BasicBlock *BB = MBB.getBasicBlock()) {
2453       if (BB->hasName()) {
2454         BB->printAsOperand(OutStreamer->GetCommentOS(),
2455                            /*PrintType=*/false, BB->getModule());
2456         OutStreamer->GetCommentOS() << '\n';
2457       }
2458     }
2459     emitBasicBlockLoopComments(MBB, LI, *this);
2460   }
2461 
2462   // Print the main label for the block.
2463   if (MBB.pred_empty() ||
2464       (isBlockOnlyReachableByFallthrough(&MBB) && !MBB.isEHFuncletEntry())) {
2465     if (isVerbose()) {
2466       // NOTE: Want this comment at start of line, don't emit with AddComment.
2467       OutStreamer->emitRawComment(" BB#" + Twine(MBB.getNumber()) + ":", false);
2468     }
2469   } else {
2470     OutStreamer->EmitLabel(MBB.getSymbol());
2471   }
2472 }
2473 
2474 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2475                                 bool IsDefinition) const {
2476   MCSymbolAttr Attr = MCSA_Invalid;
2477 
2478   switch (Visibility) {
2479   default: break;
2480   case GlobalValue::HiddenVisibility:
2481     if (IsDefinition)
2482       Attr = MAI->getHiddenVisibilityAttr();
2483     else
2484       Attr = MAI->getHiddenDeclarationVisibilityAttr();
2485     break;
2486   case GlobalValue::ProtectedVisibility:
2487     Attr = MAI->getProtectedVisibilityAttr();
2488     break;
2489   }
2490 
2491   if (Attr != MCSA_Invalid)
2492     OutStreamer->EmitSymbolAttribute(Sym, Attr);
2493 }
2494 
2495 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2496 /// exactly one predecessor and the control transfer mechanism between
2497 /// the predecessor and this block is a fall-through.
2498 bool AsmPrinter::
2499 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2500   // If this is a landing pad, it isn't a fall through.  If it has no preds,
2501   // then nothing falls through to it.
2502   if (MBB->isEHPad() || MBB->pred_empty())
2503     return false;
2504 
2505   // If there isn't exactly one predecessor, it can't be a fall through.
2506   if (MBB->pred_size() > 1)
2507     return false;
2508 
2509   // The predecessor has to be immediately before this block.
2510   MachineBasicBlock *Pred = *MBB->pred_begin();
2511   if (!Pred->isLayoutSuccessor(MBB))
2512     return false;
2513 
2514   // If the block is completely empty, then it definitely does fall through.
2515   if (Pred->empty())
2516     return true;
2517 
2518   // Check the terminators in the previous blocks
2519   for (const auto &MI : Pred->terminators()) {
2520     // If it is not a simple branch, we are in a table somewhere.
2521     if (!MI.isBranch() || MI.isIndirectBranch())
2522       return false;
2523 
2524     // If we are the operands of one of the branches, this is not a fall
2525     // through. Note that targets with delay slots will usually bundle
2526     // terminators with the delay slot instruction.
2527     for (ConstMIBundleOperands OP(&MI); OP.isValid(); ++OP) {
2528       if (OP->isJTI())
2529         return false;
2530       if (OP->isMBB() && OP->getMBB() == MBB)
2531         return false;
2532     }
2533   }
2534 
2535   return true;
2536 }
2537 
2538 
2539 
2540 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
2541   if (!S.usesMetadata())
2542     return nullptr;
2543 
2544   assert(!S.useStatepoints() && "statepoints do not currently support custom"
2545          " stackmap formats, please see the documentation for a description of"
2546          " the default format.  If you really need a custom serialized format,"
2547          " please file a bug");
2548 
2549   gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2550   gcp_map_type::iterator GCPI = GCMap.find(&S);
2551   if (GCPI != GCMap.end())
2552     return GCPI->second.get();
2553 
2554   const char *Name = S.getName().c_str();
2555 
2556   for (GCMetadataPrinterRegistry::iterator
2557          I = GCMetadataPrinterRegistry::begin(),
2558          E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2559     if (strcmp(Name, I->getName()) == 0) {
2560       std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
2561       GMP->S = &S;
2562       auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
2563       return IterBool.first->second.get();
2564     }
2565 
2566   report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
2567 }
2568 
2569 /// Pin vtable to this file.
2570 AsmPrinterHandler::~AsmPrinterHandler() {}
2571 
2572 void AsmPrinterHandler::markFunctionEnd() {}
2573