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