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