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