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