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