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