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