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