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