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