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