use EmitLinkage for functions as well as globals. One output
[oota-llvm.git] / lib / CodeGen / AsmPrinter / AsmPrinter.cpp
1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the AsmPrinter class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/AsmPrinter.h"
15 #include "llvm/Assembly/Writer.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Module.h"
19 #include "llvm/CodeGen/DwarfWriter.h"
20 #include "llvm/CodeGen/GCMetadataPrinter.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineLoopInfo.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/Analysis/DebugInfo.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCExpr.h"
30 #include "llvm/MC/MCInst.h"
31 #include "llvm/MC/MCSection.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/Format.h"
37 #include "llvm/Support/FormattedStream.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/Target/Mangler.h"
40 #include "llvm/Target/TargetData.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Target/TargetLoweringObjectFile.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/Target/TargetRegisterInfo.h"
46 #include "llvm/ADT/SmallPtrSet.h"
47 #include "llvm/ADT/SmallString.h"
48 #include <cerrno>
49 using namespace llvm;
50
51 static cl::opt<cl::boolOrDefault>
52 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
53            cl::init(cl::BOU_UNSET));
54
55 static bool getVerboseAsm(bool VDef) {
56   switch (AsmVerbose) {
57   default:
58   case cl::BOU_UNSET: return VDef;
59   case cl::BOU_TRUE:  return true;
60   case cl::BOU_FALSE: return false;
61   }      
62 }
63
64 char AsmPrinter::ID = 0;
65 AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
66                        const MCAsmInfo *T, bool VDef)
67   : MachineFunctionPass(&ID), O(o),
68     TM(tm), MAI(T), TRI(tm.getRegisterInfo()),
69
70     OutContext(*new MCContext()),
71     // FIXME: Pass instprinter to streamer.
72     OutStreamer(*createAsmStreamer(OutContext, O, *T,
73                                    TM.getTargetData()->isLittleEndian(),
74                                    getVerboseAsm(VDef), 0)),
75
76     LastMI(0), LastFn(0), Counter(~0U), PrevDLT(NULL) {
77   DW = 0; MMI = 0;
78   VerboseAsm = getVerboseAsm(VDef);
79 }
80
81 AsmPrinter::~AsmPrinter() {
82   for (gcp_iterator I = GCMetadataPrinters.begin(),
83                     E = GCMetadataPrinters.end(); I != E; ++I)
84     delete I->second;
85   
86   delete &OutStreamer;
87   delete &OutContext;
88 }
89
90 /// getFunctionNumber - Return a unique ID for the current function.
91 ///
92 unsigned AsmPrinter::getFunctionNumber() const {
93   return MF->getFunctionNumber();
94 }
95
96 TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
97   return TM.getTargetLowering()->getObjFileLowering();
98 }
99
100 /// getCurrentSection() - Return the current section we are emitting to.
101 const MCSection *AsmPrinter::getCurrentSection() const {
102   return OutStreamer.getCurrentSection();
103 }
104
105
106 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
107   AU.setPreservesAll();
108   MachineFunctionPass::getAnalysisUsage(AU);
109   AU.addRequired<GCModuleInfo>();
110   if (VerboseAsm)
111     AU.addRequired<MachineLoopInfo>();
112 }
113
114 bool AsmPrinter::doInitialization(Module &M) {
115   // Initialize TargetLoweringObjectFile.
116   const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
117     .Initialize(OutContext, TM);
118   
119   Mang = new Mangler(*MAI);
120   
121   // Allow the target to emit any magic that it wants at the start of the file.
122   EmitStartOfAsmFile(M);
123
124   // Very minimal debug info. It is ignored if we emit actual debug info. If we
125   // don't, this at least helps the user find where a global came from.
126   if (MAI->hasSingleParameterDotFile()) {
127     // .file "foo.c"
128     OutStreamer.EmitFileDirective(M.getModuleIdentifier());
129   }
130
131   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
132   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
133   for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
134     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
135       MP->beginAssembly(O, *this, *MAI);
136   
137   if (!M.getModuleInlineAsm().empty())
138     O << MAI->getCommentString() << " Start of file scope inline assembly\n"
139       << M.getModuleInlineAsm()
140       << '\n' << MAI->getCommentString()
141       << " End of file scope inline assembly\n";
142
143   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
144   if (MMI)
145     MMI->AnalyzeModule(M);
146   DW = getAnalysisIfAvailable<DwarfWriter>();
147   if (DW)
148     DW->BeginModule(&M, MMI, O, this, MAI);
149
150   return false;
151 }
152
153 void AsmPrinter::EmitLinkage(unsigned Linkage, MCSymbol *GVSym) {
154   switch ((GlobalValue::LinkageTypes)Linkage) {
155   case GlobalValue::CommonLinkage:
156   case GlobalValue::LinkOnceAnyLinkage:
157   case GlobalValue::LinkOnceODRLinkage:
158   case GlobalValue::WeakAnyLinkage:
159   case GlobalValue::WeakODRLinkage:
160   case GlobalValue::LinkerPrivateLinkage:
161     if (MAI->getWeakDefDirective() != 0) {
162       // .globl _foo
163       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
164       // .weak_definition _foo
165       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
166     } else if (const char *LinkOnce = MAI->getLinkOnceDirective()) {
167       // .globl _foo
168       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
169       // FIXME: linkonce should be a section attribute, handled by COFF Section
170       // assignment.
171       // http://sourceware.org/binutils/docs-2.20/as/Linkonce.html#Linkonce
172       // .linkonce discard
173       // FIXME: It would be nice to use .linkonce samesize for non-common
174       // globals.
175       O << LinkOnce;
176     } else {
177       // .weak _foo
178       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
179     }
180     break;
181   case GlobalValue::DLLExportLinkage:
182   case GlobalValue::AppendingLinkage:
183     // FIXME: appending linkage variables should go into a section of
184     // their name or something.  For now, just emit them as external.
185   case GlobalValue::ExternalLinkage:
186     // If external or appending, declare as a global symbol.
187     // .globl _foo
188     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
189     break;
190   case GlobalValue::PrivateLinkage:
191   case GlobalValue::InternalLinkage:
192     break;
193   default:
194     llvm_unreachable("Unknown linkage type!");
195   }
196 }
197
198
199 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
200 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
201   if (!GV->hasInitializer())   // External globals require no code.
202     return;
203   
204   // Check to see if this is a special global used by LLVM, if so, emit it.
205   if (EmitSpecialLLVMGlobal(GV))
206     return;
207
208   MCSymbol *GVSym = GetGlobalValueSymbol(GV);
209   printVisibility(GVSym, GV->getVisibility());
210
211   if (MAI->hasDotTypeDotSizeDirective())
212     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
213   
214   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
215
216   const TargetData *TD = TM.getTargetData();
217   unsigned Size = TD->getTypeAllocSize(GV->getType()->getElementType());
218   unsigned AlignLog = TD->getPreferredAlignmentLog(GV);
219   
220   // Handle common and BSS local symbols (.lcomm).
221   if (GVKind.isCommon() || GVKind.isBSSLocal()) {
222     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
223     
224     if (VerboseAsm) {
225       WriteAsOperand(OutStreamer.GetCommentOS(), GV,
226                      /*PrintType=*/false, GV->getParent());
227       OutStreamer.GetCommentOS() << '\n';
228     }
229     
230     // Handle common symbols.
231     if (GVKind.isCommon()) {
232       // .comm _foo, 42, 4
233       OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
234       return;
235     }
236     
237     // Handle local BSS symbols.
238     if (MAI->hasMachoZeroFillDirective()) {
239       const MCSection *TheSection =
240         getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
241       // .zerofill __DATA, __bss, _foo, 400, 5
242       OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
243       return;
244     }
245     
246     if (MAI->hasLCOMMDirective()) {
247       // .lcomm _foo, 42
248       OutStreamer.EmitLocalCommonSymbol(GVSym, Size);
249       return;
250     }
251     
252     // .local _foo
253     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
254     // .comm _foo, 42, 4
255     OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
256     return;
257   }
258   
259   const MCSection *TheSection =
260     getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
261
262   // Handle the zerofill directive on darwin, which is a special form of BSS
263   // emission.
264   if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
265     // .globl _foo
266     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
267     // .zerofill __DATA, __common, _foo, 400, 5
268     OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
269     return;
270   }
271
272   OutStreamer.SwitchSection(TheSection);
273
274   EmitLinkage(GV->getLinkage(), GVSym);
275   EmitAlignment(AlignLog, GV);
276
277   if (VerboseAsm) {
278     WriteAsOperand(OutStreamer.GetCommentOS(), GV,
279                    /*PrintType=*/false, GV->getParent());
280     OutStreamer.GetCommentOS() << '\n';
281   }
282   OutStreamer.EmitLabel(GVSym);
283
284   EmitGlobalConstant(GV->getInitializer());
285
286   if (MAI->hasDotTypeDotSizeDirective())
287     // .size foo, 42
288     OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
289   
290   OutStreamer.AddBlankLine();
291 }
292
293 /// EmitFunctionHeader - This method emits the header for the current
294 /// function.
295 void AsmPrinter::EmitFunctionHeader() {
296   // Print out constants referenced by the function
297   EmitConstantPool(MF->getConstantPool());
298   
299   // Print the 'header' of function.
300   const Function *F = MF->getFunction();
301
302   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
303   printVisibility(CurrentFnSym, F->getVisibility());
304
305   EmitLinkage(F->getLinkage(), CurrentFnSym);
306   EmitAlignment(MF->getAlignment(), F);
307
308   if (MAI->hasDotTypeDotSizeDirective())
309     OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
310
311   O << *CurrentFnSym << ':';
312   if (VerboseAsm) {
313     O.PadToColumn(MAI->getCommentColumn());
314     O << MAI->getCommentString() << ' ';
315     WriteAsOperand(O, F, /*PrintType=*/false, F->getParent());
316   }
317   O << '\n';
318
319   // Add some workaround for linkonce linkage on Cygwin\MinGW.
320   if (MAI->getLinkOnceDirective() != 0 &&
321       (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
322     O << "Lllvm$workaround$fake$stub$" << *CurrentFnSym << ":\n";
323   
324   // Emit pre-function debug and/or EH information.
325   if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
326     DW->BeginFunction(MF);
327 }
328
329
330
331
332 bool AsmPrinter::doFinalization(Module &M) {
333   // Emit global variables.
334   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
335        I != E; ++I)
336     EmitGlobalVariable(I);
337   
338   // Emit final debug information.
339   if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
340     DW->EndModule();
341   
342   // If the target wants to know about weak references, print them all.
343   if (MAI->getWeakRefDirective()) {
344     // FIXME: This is not lazy, it would be nice to only print weak references
345     // to stuff that is actually used.  Note that doing so would require targets
346     // to notice uses in operands (due to constant exprs etc).  This should
347     // happen with the MC stuff eventually.
348
349     // Print out module-level global variables here.
350     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
351          I != E; ++I) {
352       if (!I->hasExternalWeakLinkage()) continue;
353       OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(I),
354                                       MCSA_WeakReference);
355     }
356     
357     for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
358       if (!I->hasExternalWeakLinkage()) continue;
359       OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(I),
360                                       MCSA_WeakReference);
361     }
362   }
363
364   if (MAI->hasSetDirective()) {
365     OutStreamer.AddBlankLine();
366     for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
367          I != E; ++I) {
368       MCSymbol *Name = GetGlobalValueSymbol(I);
369
370       const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
371       MCSymbol *Target = GetGlobalValueSymbol(GV);
372
373       if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
374         OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
375       else if (I->hasWeakLinkage())
376         OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
377       else
378         assert(I->hasLocalLinkage() && "Invalid alias linkage");
379
380       printVisibility(Name, I->getVisibility());
381
382       // Emit the directives as assignments aka .set:
383       OutStreamer.EmitAssignment(Name, 
384                                  MCSymbolRefExpr::Create(Target, OutContext));
385     }
386   }
387
388   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
389   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
390   for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
391     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
392       MP->finishAssembly(O, *this, *MAI);
393
394   // If we don't have any trampolines, then we don't require stack memory
395   // to be executable. Some targets have a directive to declare this.
396   Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
397   if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
398     if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
399       OutStreamer.SwitchSection(S);
400   
401   // Allow the target to emit any magic that it wants at the end of the file,
402   // after everything else has gone out.
403   EmitEndOfAsmFile(M);
404   
405   delete Mang; Mang = 0;
406   DW = 0; MMI = 0;
407   
408   OutStreamer.Finish();
409   return false;
410 }
411
412 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
413   this->MF = &MF;
414   // Get the function symbol.
415   CurrentFnSym = GetGlobalValueSymbol(MF.getFunction());
416
417   if (VerboseAsm)
418     LI = &getAnalysis<MachineLoopInfo>();
419 }
420
421 namespace {
422   // SectionCPs - Keep track the alignment, constpool entries per Section.
423   struct SectionCPs {
424     const MCSection *S;
425     unsigned Alignment;
426     SmallVector<unsigned, 4> CPEs;
427     SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
428   };
429 }
430
431 /// EmitConstantPool - Print to the current output stream assembly
432 /// representations of the constants in the constant pool MCP. This is
433 /// used to print out constants which have been "spilled to memory" by
434 /// the code generator.
435 ///
436 void AsmPrinter::EmitConstantPool(const MachineConstantPool *MCP) {
437   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
438   if (CP.empty()) return;
439
440   // Calculate sections for constant pool entries. We collect entries to go into
441   // the same section together to reduce amount of section switch statements.
442   SmallVector<SectionCPs, 4> CPSections;
443   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
444     const MachineConstantPoolEntry &CPE = CP[i];
445     unsigned Align = CPE.getAlignment();
446     
447     SectionKind Kind;
448     switch (CPE.getRelocationInfo()) {
449     default: llvm_unreachable("Unknown section kind");
450     case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
451     case 1:
452       Kind = SectionKind::getReadOnlyWithRelLocal();
453       break;
454     case 0:
455     switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
456     case 4:  Kind = SectionKind::getMergeableConst4(); break;
457     case 8:  Kind = SectionKind::getMergeableConst8(); break;
458     case 16: Kind = SectionKind::getMergeableConst16();break;
459     default: Kind = SectionKind::getMergeableConst(); break;
460     }
461     }
462
463     const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
464     
465     // The number of sections are small, just do a linear search from the
466     // last section to the first.
467     bool Found = false;
468     unsigned SecIdx = CPSections.size();
469     while (SecIdx != 0) {
470       if (CPSections[--SecIdx].S == S) {
471         Found = true;
472         break;
473       }
474     }
475     if (!Found) {
476       SecIdx = CPSections.size();
477       CPSections.push_back(SectionCPs(S, Align));
478     }
479
480     if (Align > CPSections[SecIdx].Alignment)
481       CPSections[SecIdx].Alignment = Align;
482     CPSections[SecIdx].CPEs.push_back(i);
483   }
484
485   // Now print stuff into the calculated sections.
486   for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
487     OutStreamer.SwitchSection(CPSections[i].S);
488     EmitAlignment(Log2_32(CPSections[i].Alignment));
489
490     unsigned Offset = 0;
491     for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
492       unsigned CPI = CPSections[i].CPEs[j];
493       MachineConstantPoolEntry CPE = CP[CPI];
494
495       // Emit inter-object padding for alignment.
496       unsigned AlignMask = CPE.getAlignment() - 1;
497       unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
498       OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
499
500       const Type *Ty = CPE.getType();
501       Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
502
503       // Emit the label with a comment on it.
504       if (VerboseAsm) {
505         OutStreamer.GetCommentOS() << "constant pool ";
506         WriteTypeSymbolic(OutStreamer.GetCommentOS(), CPE.getType(),
507                           MF->getFunction()->getParent());
508         OutStreamer.GetCommentOS() << '\n';
509       }
510       OutStreamer.EmitLabel(GetCPISymbol(CPI));
511
512       if (CPE.isMachineConstantPoolEntry())
513         EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
514       else
515         EmitGlobalConstant(CPE.Val.ConstVal);
516     }
517   }
518 }
519
520 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
521 /// by the current function to the current output stream.  
522 ///
523 void AsmPrinter::EmitJumpTableInfo(MachineFunction &MF) {
524   MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
525   if (MJTI == 0) return;
526   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
527   if (JT.empty()) return;
528
529   // Pick the directive to use to print the jump table entries, and switch to 
530   // the appropriate section.
531   const Function *F = MF.getFunction();
532   bool JTInDiffSection = false;
533   if (// In PIC mode, we need to emit the jump table to the same section as the
534       // function body itself, otherwise the label differences won't make sense.
535       // FIXME: Need a better predicate for this: what about custom entries?
536       MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
537       // We should also do if the section name is NULL or function is declared
538       // in discardable section
539       // FIXME: this isn't the right predicate, should be based on the MCSection
540       // for the function.
541       F->isWeakForLinker()) {
542     OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
543                                                                     TM));
544   } else {
545     // Otherwise, drop it in the readonly section.
546     const MCSection *ReadOnlySection = 
547       getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
548     OutStreamer.SwitchSection(ReadOnlySection);
549     JTInDiffSection = true;
550   }
551
552   EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getTargetData())));
553   
554   for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
555     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
556     
557     // If this jump table was deleted, ignore it. 
558     if (JTBBs.empty()) continue;
559
560     // For the EK_LabelDifference32 entry, if the target supports .set, emit a
561     // .set directive for each unique entry.  This reduces the number of
562     // relocations the assembler will generate for the jump table.
563     if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
564         MAI->hasSetDirective()) {
565       SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
566       const TargetLowering *TLI = TM.getTargetLowering();
567       const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(&MF, JTI,
568                                                              OutContext);
569       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
570         const MachineBasicBlock *MBB = JTBBs[ii];
571         if (!EmittedSets.insert(MBB)) continue;
572         
573         // .set LJTSet, LBB32-base
574         const MCExpr *LHS =
575           MCSymbolRefExpr::Create(MBB->getSymbol(OutContext), OutContext);
576         OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
577                                 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
578       }
579     }          
580     
581     // On some targets (e.g. Darwin) we want to emit two consequtive labels
582     // before each jump table.  The first label is never referenced, but tells
583     // the assembler and linker the extents of the jump table object.  The
584     // second label is actually referenced by the code.
585     if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
586       // FIXME: This doesn't have to have any specific name, just any randomly
587       // named and numbered 'l' label would work.  Simplify GetJTISymbol.
588       OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
589
590     OutStreamer.EmitLabel(GetJTISymbol(JTI));
591
592     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
593       EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
594   }
595 }
596
597 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
598 /// current stream.
599 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
600                                     const MachineBasicBlock *MBB,
601                                     unsigned UID) const {
602   const MCExpr *Value = 0;
603   switch (MJTI->getEntryKind()) {
604   case MachineJumpTableInfo::EK_Custom32:
605     Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
606                                                               OutContext);
607     break;
608   case MachineJumpTableInfo::EK_BlockAddress:
609     // EK_BlockAddress - Each entry is a plain address of block, e.g.:
610     //     .word LBB123
611     Value = MCSymbolRefExpr::Create(MBB->getSymbol(OutContext), OutContext);
612     break;
613   case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
614     // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
615     // with a relocation as gp-relative, e.g.:
616     //     .gprel32 LBB123
617     MCSymbol *MBBSym = MBB->getSymbol(OutContext);
618     OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
619     return;
620   }
621
622   case MachineJumpTableInfo::EK_LabelDifference32: {
623     // EK_LabelDifference32 - Each entry is the address of the block minus
624     // the address of the jump table.  This is used for PIC jump tables where
625     // gprel32 is not supported.  e.g.:
626     //      .word LBB123 - LJTI1_2
627     // If the .set directive is supported, this is emitted as:
628     //      .set L4_5_set_123, LBB123 - LJTI1_2
629     //      .word L4_5_set_123
630     
631     // If we have emitted set directives for the jump table entries, print 
632     // them rather than the entries themselves.  If we're emitting PIC, then
633     // emit the table entries as differences between two text section labels.
634     if (MAI->hasSetDirective()) {
635       // If we used .set, reference the .set's symbol.
636       Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
637                                       OutContext);
638       break;
639     }
640     // Otherwise, use the difference as the jump table entry.
641     Value = MCSymbolRefExpr::Create(MBB->getSymbol(OutContext), OutContext);
642     const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
643     Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
644     break;
645   }
646   }
647   
648   assert(Value && "Unknown entry kind!");
649  
650   unsigned EntrySize = MJTI->getEntrySize(*TM.getTargetData());
651   OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0);
652 }
653
654
655 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
656 /// special global used by LLVM.  If so, emit it and return true, otherwise
657 /// do nothing and return false.
658 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
659   if (GV->getName() == "llvm.used") {
660     if (MAI->hasNoDeadStrip())    // No need to emit this at all.
661       EmitLLVMUsedList(GV->getInitializer());
662     return true;
663   }
664
665   // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
666   if (GV->getSection() == "llvm.metadata" ||
667       GV->hasAvailableExternallyLinkage())
668     return true;
669   
670   if (!GV->hasAppendingLinkage()) return false;
671
672   assert(GV->hasInitializer() && "Not a special LLVM global!");
673   
674   const TargetData *TD = TM.getTargetData();
675   unsigned Align = Log2_32(TD->getPointerPrefAlignment());
676   if (GV->getName() == "llvm.global_ctors") {
677     OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
678     EmitAlignment(Align, 0);
679     EmitXXStructorList(GV->getInitializer());
680     
681     if (TM.getRelocationModel() == Reloc::Static &&
682         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
683       StringRef Sym(".constructors_used");
684       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
685                                       MCSA_Reference);
686     }
687     return true;
688   } 
689   
690   if (GV->getName() == "llvm.global_dtors") {
691     OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
692     EmitAlignment(Align, 0);
693     EmitXXStructorList(GV->getInitializer());
694
695     if (TM.getRelocationModel() == Reloc::Static &&
696         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
697       StringRef Sym(".destructors_used");
698       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
699                                       MCSA_Reference);
700     }
701     return true;
702   }
703   
704   return false;
705 }
706
707 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
708 /// global in the specified llvm.used list for which emitUsedDirectiveFor
709 /// is true, as being used with this directive.
710 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
711   // Should be an array of 'i8*'.
712   ConstantArray *InitList = dyn_cast<ConstantArray>(List);
713   if (InitList == 0) return;
714   
715   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
716     const GlobalValue *GV =
717       dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
718     if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
719       OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(GV),
720                                       MCSA_NoDeadStrip);
721   }
722 }
723
724 /// EmitXXStructorList - Emit the ctor or dtor list.  This just prints out the 
725 /// function pointers, ignoring the init priority.
726 void AsmPrinter::EmitXXStructorList(Constant *List) {
727   // Should be an array of '{ int, void ()* }' structs.  The first value is the
728   // init priority, which we ignore.
729   if (!isa<ConstantArray>(List)) return;
730   ConstantArray *InitList = cast<ConstantArray>(List);
731   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
732     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
733       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
734
735       if (CS->getOperand(1)->isNullValue())
736         return;  // Found a null terminator, exit printing.
737       // Emit the function pointer.
738       EmitGlobalConstant(CS->getOperand(1));
739     }
740 }
741
742 //===--------------------------------------------------------------------===//
743 // Emission and print routines
744 //
745
746 /// EmitInt8 - Emit a byte directive and value.
747 ///
748 void AsmPrinter::EmitInt8(int Value) const {
749   OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
750 }
751
752 /// EmitInt16 - Emit a short directive and value.
753 ///
754 void AsmPrinter::EmitInt16(int Value) const {
755   OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
756 }
757
758 /// EmitInt32 - Emit a long directive and value.
759 ///
760 void AsmPrinter::EmitInt32(int Value) const {
761   OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
762 }
763
764 /// EmitInt64 - Emit a long long directive and value.
765 ///
766 void AsmPrinter::EmitInt64(uint64_t Value) const {
767   OutStreamer.EmitIntValue(Value, 8, 0/*addrspace*/);
768 }
769
770 //===----------------------------------------------------------------------===//
771
772 // EmitAlignment - Emit an alignment directive to the specified power of
773 // two boundary.  For example, if you pass in 3 here, you will get an 8
774 // byte alignment.  If a global value is specified, and if that global has
775 // an explicit alignment requested, it will unconditionally override the
776 // alignment request.  However, if ForcedAlignBits is specified, this value
777 // has final say: the ultimate alignment will be the max of ForcedAlignBits
778 // and the alignment computed with NumBits and the global.
779 //
780 // The algorithm is:
781 //     Align = NumBits;
782 //     if (GV && GV->hasalignment) Align = GV->getalignment();
783 //     Align = std::max(Align, ForcedAlignBits);
784 //
785 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
786                                unsigned ForcedAlignBits,
787                                bool UseFillExpr) const {
788   if (GV && GV->getAlignment())
789     NumBits = Log2_32(GV->getAlignment());
790   NumBits = std::max(NumBits, ForcedAlignBits);
791   
792   if (NumBits == 0) return;   // No need to emit alignment.
793   
794   unsigned FillValue = 0;
795   if (getCurrentSection()->getKind().isText())
796     FillValue = MAI->getTextAlignFillValue();
797   
798   OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
799 }
800
801 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
802 ///
803 static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) {
804   MCContext &Ctx = AP.OutContext;
805   
806   if (CV->isNullValue() || isa<UndefValue>(CV))
807     return MCConstantExpr::Create(0, Ctx);
808
809   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
810     return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
811   
812   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
813     return MCSymbolRefExpr::Create(AP.GetGlobalValueSymbol(GV), Ctx);
814   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
815     return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
816   
817   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
818   if (CE == 0) {
819     llvm_unreachable("Unknown constant value to lower!");
820     return MCConstantExpr::Create(0, Ctx);
821   }
822   
823   switch (CE->getOpcode()) {
824   case Instruction::ZExt:
825   case Instruction::SExt:
826   case Instruction::FPTrunc:
827   case Instruction::FPExt:
828   case Instruction::UIToFP:
829   case Instruction::SIToFP:
830   case Instruction::FPToUI:
831   case Instruction::FPToSI:
832   default: llvm_unreachable("FIXME: Don't support this constant cast expr");
833   case Instruction::GetElementPtr: {
834     const TargetData &TD = *AP.TM.getTargetData();
835     // Generate a symbolic expression for the byte address
836     const Constant *PtrVal = CE->getOperand(0);
837     SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
838     int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), &IdxVec[0],
839                                          IdxVec.size());
840     
841     const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
842     if (Offset == 0)
843       return Base;
844     
845     // Truncate/sext the offset to the pointer size.
846     if (TD.getPointerSizeInBits() != 64) {
847       int SExtAmount = 64-TD.getPointerSizeInBits();
848       Offset = (Offset << SExtAmount) >> SExtAmount;
849     }
850     
851     return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
852                                    Ctx);
853   }
854       
855   case Instruction::Trunc:
856     // We emit the value and depend on the assembler to truncate the generated
857     // expression properly.  This is important for differences between
858     // blockaddress labels.  Since the two labels are in the same function, it
859     // is reasonable to treat their delta as a 32-bit value.
860     // FALL THROUGH.
861   case Instruction::BitCast:
862     return LowerConstant(CE->getOperand(0), AP);
863
864   case Instruction::IntToPtr: {
865     const TargetData &TD = *AP.TM.getTargetData();
866     // Handle casts to pointers by changing them into casts to the appropriate
867     // integer type.  This promotes constant folding and simplifies this code.
868     Constant *Op = CE->getOperand(0);
869     Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
870                                       false/*ZExt*/);
871     return LowerConstant(Op, AP);
872   }
873     
874   case Instruction::PtrToInt: {
875     const TargetData &TD = *AP.TM.getTargetData();
876     // Support only foldable casts to/from pointers that can be eliminated by
877     // changing the pointer to the appropriately sized integer type.
878     Constant *Op = CE->getOperand(0);
879     const Type *Ty = CE->getType();
880
881     const MCExpr *OpExpr = LowerConstant(Op, AP);
882
883     // We can emit the pointer value into this slot if the slot is an
884     // integer slot equal to the size of the pointer.
885     if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
886       return OpExpr;
887
888     // Otherwise the pointer is smaller than the resultant integer, mask off
889     // the high bits so we are sure to get a proper truncation if the input is
890     // a constant expr.
891     unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
892     const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
893     return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
894   }
895       
896   case Instruction::Add:
897   case Instruction::Sub:
898   case Instruction::And:
899   case Instruction::Or:
900   case Instruction::Xor: {
901     const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
902     const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
903     switch (CE->getOpcode()) {
904     default: llvm_unreachable("Unknown binary operator constant cast expr");
905     case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
906     case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
907     case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
908     case Instruction::Or:  return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
909     case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
910     }
911   }
912   }
913 }
914
915 static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
916                                     AsmPrinter &AP) {
917   if (AddrSpace != 0 || !CA->isString()) {
918     // Not a string.  Print the values in successive locations
919     for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
920       AP.EmitGlobalConstant(CA->getOperand(i), AddrSpace);
921     return;
922   }
923   
924   // Otherwise, it can be emitted as .ascii.
925   SmallVector<char, 128> TmpVec;
926   TmpVec.reserve(CA->getNumOperands());
927   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
928     TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
929
930   AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
931 }
932
933 static void EmitGlobalConstantVector(const ConstantVector *CV,
934                                      unsigned AddrSpace, AsmPrinter &AP) {
935   for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
936     AP.EmitGlobalConstant(CV->getOperand(i), AddrSpace);
937 }
938
939 static void EmitGlobalConstantStruct(const ConstantStruct *CS,
940                                      unsigned AddrSpace, AsmPrinter &AP) {
941   // Print the fields in successive locations. Pad to align if needed!
942   const TargetData *TD = AP.TM.getTargetData();
943   unsigned Size = TD->getTypeAllocSize(CS->getType());
944   const StructLayout *Layout = TD->getStructLayout(CS->getType());
945   uint64_t SizeSoFar = 0;
946   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
947     const Constant *Field = CS->getOperand(i);
948
949     // Check if padding is needed and insert one or more 0s.
950     uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
951     uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
952                         - Layout->getElementOffset(i)) - FieldSize;
953     SizeSoFar += FieldSize + PadSize;
954
955     // Now print the actual field value.
956     AP.EmitGlobalConstant(Field, AddrSpace);
957
958     // Insert padding - this may include padding to increase the size of the
959     // current field up to the ABI size (if the struct is not packed) as well
960     // as padding to ensure that the next field starts at the right offset.
961     AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
962   }
963   assert(SizeSoFar == Layout->getSizeInBytes() &&
964          "Layout of constant struct may be incorrect!");
965 }
966
967 static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
968                                  AsmPrinter &AP) {
969   // FP Constants are printed as integer constants to avoid losing
970   // precision.
971   if (CFP->getType()->isDoubleTy()) {
972     if (AP.VerboseAsm) {
973       double Val = CFP->getValueAPF().convertToDouble();
974       AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
975     }
976
977     uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
978     AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
979     return;
980   }
981   
982   if (CFP->getType()->isFloatTy()) {
983     if (AP.VerboseAsm) {
984       float Val = CFP->getValueAPF().convertToFloat();
985       AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
986     }
987     uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
988     AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
989     return;
990   }
991   
992   if (CFP->getType()->isX86_FP80Ty()) {
993     // all long double variants are printed as hex
994     // api needed to prevent premature destruction
995     APInt API = CFP->getValueAPF().bitcastToAPInt();
996     const uint64_t *p = API.getRawData();
997     if (AP.VerboseAsm) {
998       // Convert to double so we can print the approximate val as a comment.
999       APFloat DoubleVal = CFP->getValueAPF();
1000       bool ignored;
1001       DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1002                         &ignored);
1003       AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
1004         << DoubleVal.convertToDouble() << '\n';
1005     }
1006     
1007     if (AP.TM.getTargetData()->isBigEndian()) {
1008       AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1009       AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1010     } else {
1011       AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1012       AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1013     }
1014     
1015     // Emit the tail padding for the long double.
1016     const TargetData &TD = *AP.TM.getTargetData();
1017     AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1018                              TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1019     return;
1020   }
1021   
1022   assert(CFP->getType()->isPPC_FP128Ty() &&
1023          "Floating point constant type not handled");
1024   // All long double variants are printed as hex api needed to prevent
1025   // premature destruction.
1026   APInt API = CFP->getValueAPF().bitcastToAPInt();
1027   const uint64_t *p = API.getRawData();
1028   if (AP.TM.getTargetData()->isBigEndian()) {
1029     AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1030     AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1031   } else {
1032     AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1033     AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1034   }
1035 }
1036
1037 static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1038                                        unsigned AddrSpace, AsmPrinter &AP) {
1039   const TargetData *TD = AP.TM.getTargetData();
1040   unsigned BitWidth = CI->getBitWidth();
1041   assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1042
1043   // We don't expect assemblers to support integer data directives
1044   // for more than 64 bits, so we emit the data in at most 64-bit
1045   // quantities at a time.
1046   const uint64_t *RawData = CI->getValue().getRawData();
1047   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1048     uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1049     AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1050   }
1051 }
1052
1053 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1054 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1055   if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
1056     uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1057     return OutStreamer.EmitZeros(Size, AddrSpace);
1058   }
1059
1060   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1061     unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1062     switch (Size) {
1063     case 1:
1064     case 2:
1065     case 4:
1066     case 8:
1067       if (VerboseAsm)
1068         OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
1069       OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1070       return;
1071     default:
1072       EmitGlobalConstantLargeInt(CI, AddrSpace, *this);
1073       return;
1074     }
1075   }
1076   
1077   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1078     return EmitGlobalConstantArray(CVA, AddrSpace, *this);
1079   
1080   if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1081     return EmitGlobalConstantStruct(CVS, AddrSpace, *this);
1082
1083   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1084     return EmitGlobalConstantFP(CFP, AddrSpace, *this);
1085   
1086   if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1087     return EmitGlobalConstantVector(V, AddrSpace, *this);
1088
1089   if (isa<ConstantPointerNull>(CV)) {
1090     unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1091     OutStreamer.EmitIntValue(0, Size, AddrSpace);
1092     return;
1093   }
1094   
1095   // Otherwise, it must be a ConstantExpr.  Lower it to an MCExpr, then emit it
1096   // thread the streamer with EmitValue.
1097   OutStreamer.EmitValue(LowerConstant(CV, *this),
1098                         TM.getTargetData()->getTypeAllocSize(CV->getType()),
1099                         AddrSpace);
1100 }
1101
1102 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1103   // Target doesn't support this yet!
1104   llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1105 }
1106
1107 /// PrintSpecial - Print information related to the specified machine instr
1108 /// that is independent of the operand, and may be independent of the instr
1109 /// itself.  This can be useful for portably encoding the comment character
1110 /// or other bits of target-specific knowledge into the asmstrings.  The
1111 /// syntax used is ${:comment}.  Targets can override this to add support
1112 /// for their own strange codes.
1113 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1114   if (!strcmp(Code, "private")) {
1115     O << MAI->getPrivateGlobalPrefix();
1116   } else if (!strcmp(Code, "comment")) {
1117     if (VerboseAsm)
1118       O << MAI->getCommentString();
1119   } else if (!strcmp(Code, "uid")) {
1120     // Comparing the address of MI isn't sufficient, because machineinstrs may
1121     // be allocated to the same address across functions.
1122     const Function *ThisF = MI->getParent()->getParent()->getFunction();
1123     
1124     // If this is a new LastFn instruction, bump the counter.
1125     if (LastMI != MI || LastFn != ThisF) {
1126       ++Counter;
1127       LastMI = MI;
1128       LastFn = ThisF;
1129     }
1130     O << Counter;
1131   } else {
1132     std::string msg;
1133     raw_string_ostream Msg(msg);
1134     Msg << "Unknown special formatter '" << Code
1135          << "' for machine instr: " << *MI;
1136     llvm_report_error(Msg.str());
1137   }    
1138 }
1139
1140 /// processDebugLoc - Processes the debug information of each machine
1141 /// instruction's DebugLoc.
1142 void AsmPrinter::processDebugLoc(const MachineInstr *MI, 
1143                                  bool BeforePrintingInsn) {
1144   if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1145       || !DW->ShouldEmitDwarfDebug())
1146     return;
1147   DebugLoc DL = MI->getDebugLoc();
1148   if (DL.isUnknown())
1149     return;
1150   DILocation CurDLT = MF->getDILocation(DL);
1151   if (CurDLT.getScope().isNull())
1152     return;
1153
1154   if (!BeforePrintingInsn) {
1155     // After printing instruction
1156     DW->EndScope(MI);
1157   } else if (CurDLT.getNode() != PrevDLT) {
1158     unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(), 
1159                                       CurDLT.getColumnNumber(),
1160                                       CurDLT.getScope().getNode());
1161     printLabel(L);
1162     O << '\n';
1163     DW->BeginScope(MI, L);
1164     PrevDLT = CurDLT.getNode();
1165   }
1166 }
1167
1168
1169 /// printInlineAsm - This method formats and prints the specified machine
1170 /// instruction that is an inline asm.
1171 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1172   unsigned NumOperands = MI->getNumOperands();
1173   
1174   // Count the number of register definitions.
1175   unsigned NumDefs = 0;
1176   for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1177        ++NumDefs)
1178     assert(NumDefs != NumOperands-1 && "No asm string?");
1179   
1180   assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1181
1182   // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1183   const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1184
1185   O << '\t';
1186
1187   // If this asmstr is empty, just print the #APP/#NOAPP markers.
1188   // These are useful to see where empty asm's wound up.
1189   if (AsmStr[0] == 0) {
1190     O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1191     O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1192     return;
1193   }
1194   
1195   O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1196
1197   // The variant of the current asmprinter.
1198   int AsmPrinterVariant = MAI->getAssemblerDialect();
1199
1200   int CurVariant = -1;            // The number of the {.|.|.} region we are in.
1201   const char *LastEmitted = AsmStr; // One past the last character emitted.
1202   
1203   while (*LastEmitted) {
1204     switch (*LastEmitted) {
1205     default: {
1206       // Not a special case, emit the string section literally.
1207       const char *LiteralEnd = LastEmitted+1;
1208       while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1209              *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1210         ++LiteralEnd;
1211       if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1212         O.write(LastEmitted, LiteralEnd-LastEmitted);
1213       LastEmitted = LiteralEnd;
1214       break;
1215     }
1216     case '\n':
1217       ++LastEmitted;   // Consume newline character.
1218       O << '\n';       // Indent code with newline.
1219       break;
1220     case '$': {
1221       ++LastEmitted;   // Consume '$' character.
1222       bool Done = true;
1223
1224       // Handle escapes.
1225       switch (*LastEmitted) {
1226       default: Done = false; break;
1227       case '$':     // $$ -> $
1228         if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1229           O << '$';
1230         ++LastEmitted;  // Consume second '$' character.
1231         break;
1232       case '(':             // $( -> same as GCC's { character.
1233         ++LastEmitted;      // Consume '(' character.
1234         if (CurVariant != -1) {
1235           llvm_report_error("Nested variants found in inline asm string: '"
1236                             + std::string(AsmStr) + "'");
1237         }
1238         CurVariant = 0;     // We're in the first variant now.
1239         break;
1240       case '|':
1241         ++LastEmitted;  // consume '|' character.
1242         if (CurVariant == -1)
1243           O << '|';       // this is gcc's behavior for | outside a variant
1244         else
1245           ++CurVariant;   // We're in the next variant.
1246         break;
1247       case ')':         // $) -> same as GCC's } char.
1248         ++LastEmitted;  // consume ')' character.
1249         if (CurVariant == -1)
1250           O << '}';     // this is gcc's behavior for } outside a variant
1251         else 
1252           CurVariant = -1;
1253         break;
1254       }
1255       if (Done) break;
1256       
1257       bool HasCurlyBraces = false;
1258       if (*LastEmitted == '{') {     // ${variable}
1259         ++LastEmitted;               // Consume '{' character.
1260         HasCurlyBraces = true;
1261       }
1262       
1263       // If we have ${:foo}, then this is not a real operand reference, it is a
1264       // "magic" string reference, just like in .td files.  Arrange to call
1265       // PrintSpecial.
1266       if (HasCurlyBraces && *LastEmitted == ':') {
1267         ++LastEmitted;
1268         const char *StrStart = LastEmitted;
1269         const char *StrEnd = strchr(StrStart, '}');
1270         if (StrEnd == 0) {
1271           llvm_report_error("Unterminated ${:foo} operand in inline asm string: '" 
1272                             + std::string(AsmStr) + "'");
1273         }
1274         
1275         std::string Val(StrStart, StrEnd);
1276         PrintSpecial(MI, Val.c_str());
1277         LastEmitted = StrEnd+1;
1278         break;
1279       }
1280             
1281       const char *IDStart = LastEmitted;
1282       char *IDEnd;
1283       errno = 0;
1284       long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1285       if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1286         llvm_report_error("Bad $ operand number in inline asm string: '" 
1287                           + std::string(AsmStr) + "'");
1288       }
1289       LastEmitted = IDEnd;
1290       
1291       char Modifier[2] = { 0, 0 };
1292       
1293       if (HasCurlyBraces) {
1294         // If we have curly braces, check for a modifier character.  This
1295         // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1296         if (*LastEmitted == ':') {
1297           ++LastEmitted;    // Consume ':' character.
1298           if (*LastEmitted == 0) {
1299             llvm_report_error("Bad ${:} expression in inline asm string: '" 
1300                               + std::string(AsmStr) + "'");
1301           }
1302           
1303           Modifier[0] = *LastEmitted;
1304           ++LastEmitted;    // Consume modifier character.
1305         }
1306         
1307         if (*LastEmitted != '}') {
1308           llvm_report_error("Bad ${} expression in inline asm string: '" 
1309                             + std::string(AsmStr) + "'");
1310         }
1311         ++LastEmitted;    // Consume '}' character.
1312       }
1313       
1314       if ((unsigned)Val >= NumOperands-1) {
1315         llvm_report_error("Invalid $ operand number in inline asm string: '" 
1316                           + std::string(AsmStr) + "'");
1317       }
1318       
1319       // Okay, we finally have a value number.  Ask the target to print this
1320       // operand!
1321       if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1322         unsigned OpNo = 1;
1323
1324         bool Error = false;
1325
1326         // Scan to find the machine operand number for the operand.
1327         for (; Val; --Val) {
1328           if (OpNo >= MI->getNumOperands()) break;
1329           unsigned OpFlags = MI->getOperand(OpNo).getImm();
1330           OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1331         }
1332
1333         if (OpNo >= MI->getNumOperands()) {
1334           Error = true;
1335         } else {
1336           unsigned OpFlags = MI->getOperand(OpNo).getImm();
1337           ++OpNo;  // Skip over the ID number.
1338
1339           if (Modifier[0] == 'l')  // labels are target independent
1340             O << *MI->getOperand(OpNo).getMBB()->getSymbol(OutContext);
1341           else {
1342             AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1343             if ((OpFlags & 7) == 4) {
1344               Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1345                                                 Modifier[0] ? Modifier : 0);
1346             } else {
1347               Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1348                                           Modifier[0] ? Modifier : 0);
1349             }
1350           }
1351         }
1352         if (Error) {
1353           std::string msg;
1354           raw_string_ostream Msg(msg);
1355           Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n";
1356           MI->print(Msg);
1357           llvm_report_error(Msg.str());
1358         }
1359       }
1360       break;
1361     }
1362     }
1363   }
1364   O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1365 }
1366
1367 /// printImplicitDef - This method prints the specified machine instruction
1368 /// that is an implicit def.
1369 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1370   if (!VerboseAsm) return;
1371   O.PadToColumn(MAI->getCommentColumn());
1372   O << MAI->getCommentString() << " implicit-def: "
1373     << TRI->getName(MI->getOperand(0).getReg());
1374 }
1375
1376 void AsmPrinter::printKill(const MachineInstr *MI) const {
1377   if (!VerboseAsm) return;
1378   O.PadToColumn(MAI->getCommentColumn());
1379   O << MAI->getCommentString() << " kill:";
1380   for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1381     const MachineOperand &op = MI->getOperand(n);
1382     assert(op.isReg() && "KILL instruction must have only register operands");
1383     O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1384   }
1385 }
1386
1387 /// printLabel - This method prints a local label used by debug and
1388 /// exception handling tables.
1389 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1390   printLabel(MI->getOperand(0).getImm());
1391 }
1392
1393 void AsmPrinter::printLabel(unsigned Id) const {
1394   O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1395 }
1396
1397 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1398 /// instruction, using the specified assembler variant.  Targets should
1399 /// override this to format as appropriate.
1400 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1401                                  unsigned AsmVariant, const char *ExtraCode) {
1402   // Target doesn't support this yet!
1403   return true;
1404 }
1405
1406 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1407                                        unsigned AsmVariant,
1408                                        const char *ExtraCode) {
1409   // Target doesn't support this yet!
1410   return true;
1411 }
1412
1413 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1414                                             const char *Suffix) const {
1415   return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
1416 }
1417
1418 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
1419                                             const BasicBlock *BB,
1420                                             const char *Suffix) const {
1421   assert(BB->hasName() &&
1422          "Address of anonymous basic block not supported yet!");
1423
1424   // This code must use the function name itself, and not the function number,
1425   // since it must be possible to generate the label name from within other
1426   // functions.
1427   SmallString<60> FnName;
1428   Mang->getNameWithPrefix(FnName, F, false);
1429
1430   // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
1431   SmallString<60> NameResult;
1432   Mang->getNameWithPrefix(NameResult,
1433                           StringRef("BA") + Twine((unsigned)FnName.size()) + 
1434                           "_" + FnName.str() + "_" + BB->getName() + Suffix, 
1435                           Mangler::Private);
1436
1437   return OutContext.GetOrCreateSymbol(NameResult.str());
1438 }
1439
1440 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
1441 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
1442   SmallString<60> Name;
1443   raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "CPI"
1444     << getFunctionNumber() << '_' << CPID;
1445   return OutContext.GetOrCreateSymbol(Name.str());
1446 }
1447
1448 /// GetJTISymbol - Return the symbol for the specified jump table entry.
1449 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1450   return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
1451 }
1452
1453 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
1454 /// FIXME: privatize to AsmPrinter.
1455 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
1456   SmallString<60> Name;
1457   raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix()
1458     << getFunctionNumber() << '_' << UID << "_set_" << MBBID;
1459   return OutContext.GetOrCreateSymbol(Name.str());
1460 }
1461
1462 /// GetGlobalValueSymbol - Return the MCSymbol for the specified global
1463 /// value.
1464 MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
1465   SmallString<60> NameStr;
1466   Mang->getNameWithPrefix(NameStr, GV, false);
1467   return OutContext.GetOrCreateSymbol(NameStr.str());
1468 }
1469
1470 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1471 /// global value name as its base, with the specified suffix, and where the
1472 /// symbol is forced to have private linkage if ForcePrivate is true.
1473 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1474                                                    StringRef Suffix,
1475                                                    bool ForcePrivate) const {
1476   SmallString<60> NameStr;
1477   Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1478   NameStr.append(Suffix.begin(), Suffix.end());
1479   return OutContext.GetOrCreateSymbol(NameStr.str());
1480 }
1481
1482 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1483 /// ExternalSymbol.
1484 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1485   SmallString<60> NameStr;
1486   Mang->getNameWithPrefix(NameStr, Sym);
1487   return OutContext.GetOrCreateSymbol(NameStr.str());
1488 }  
1489
1490
1491
1492 /// PrintParentLoopComment - Print comments about parent loops of this one.
1493 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1494                                    unsigned FunctionNumber) {
1495   if (Loop == 0) return;
1496   PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1497   OS.indent(Loop->getLoopDepth()*2)
1498     << "Parent Loop BB" << FunctionNumber << "_"
1499     << Loop->getHeader()->getNumber()
1500     << " Depth=" << Loop->getLoopDepth() << '\n';
1501 }
1502
1503
1504 /// PrintChildLoopComment - Print comments about child loops within
1505 /// the loop for this basic block, with nesting.
1506 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1507                                   unsigned FunctionNumber) {
1508   // Add child loop information
1509   for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1510     OS.indent((*CL)->getLoopDepth()*2)
1511       << "Child Loop BB" << FunctionNumber << "_"
1512       << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1513       << '\n';
1514     PrintChildLoopComment(OS, *CL, FunctionNumber);
1515   }
1516 }
1517
1518 /// EmitComments - Pretty-print comments for basic blocks.
1519 static void PrintBasicBlockLoopComments(const MachineBasicBlock &MBB,
1520                                         const MachineLoopInfo *LI,
1521                                         const AsmPrinter &AP) {
1522   // Add loop depth information
1523   const MachineLoop *Loop = LI->getLoopFor(&MBB);
1524   if (Loop == 0) return;
1525   
1526   MachineBasicBlock *Header = Loop->getHeader();
1527   assert(Header && "No header for loop");
1528   
1529   // If this block is not a loop header, just print out what is the loop header
1530   // and return.
1531   if (Header != &MBB) {
1532     AP.OutStreamer.AddComment("  in Loop: Header=BB" +
1533                               Twine(AP.getFunctionNumber())+"_" +
1534                               Twine(Loop->getHeader()->getNumber())+
1535                               " Depth="+Twine(Loop->getLoopDepth()));
1536     return;
1537   }
1538   
1539   // Otherwise, it is a loop header.  Print out information about child and
1540   // parent loops.
1541   raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1542   
1543   PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber()); 
1544   
1545   OS << "=>";
1546   OS.indent(Loop->getLoopDepth()*2-2);
1547   
1548   OS << "This ";
1549   if (Loop->empty())
1550     OS << "Inner ";
1551   OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1552   
1553   PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1554 }
1555
1556
1557 /// EmitBasicBlockStart - This method prints the label for the specified
1558 /// MachineBasicBlock, an alignment (if present) and a comment describing
1559 /// it if appropriate.
1560 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1561   // Emit an alignment directive for this block, if needed.
1562   if (unsigned Align = MBB->getAlignment())
1563     EmitAlignment(Log2_32(Align));
1564
1565   // If the block has its address taken, emit a special label to satisfy
1566   // references to the block. This is done so that we don't need to
1567   // remember the number of this label, and so that we can make
1568   // forward references to labels without knowing what their numbers
1569   // will be.
1570   if (MBB->hasAddressTaken()) {
1571     const BasicBlock *BB = MBB->getBasicBlock();
1572     if (VerboseAsm)
1573       OutStreamer.AddComment("Address Taken");
1574     OutStreamer.EmitLabel(GetBlockAddressSymbol(BB->getParent(), BB));
1575   }
1576
1577   // Print the main label for the block.
1578   if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
1579     if (VerboseAsm) {
1580       // NOTE: Want this comment at start of line.
1581       O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
1582       if (const BasicBlock *BB = MBB->getBasicBlock())
1583         if (BB->hasName())
1584           OutStreamer.AddComment("%" + BB->getName());
1585       
1586       PrintBasicBlockLoopComments(*MBB, LI, *this);
1587       OutStreamer.AddBlankLine();
1588     }
1589   } else {
1590     if (VerboseAsm) {
1591       if (const BasicBlock *BB = MBB->getBasicBlock())
1592         if (BB->hasName())
1593           OutStreamer.AddComment("%" + BB->getName());
1594       PrintBasicBlockLoopComments(*MBB, LI, *this);
1595     }
1596
1597     OutStreamer.EmitLabel(MBB->getSymbol(OutContext));
1598   }
1599 }
1600
1601 void AsmPrinter::printVisibility(MCSymbol *Sym, unsigned Visibility) const {
1602   // FIXME: RENAME TO EmitVisibility.
1603   MCSymbolAttr Attr = MCSA_Invalid;
1604   
1605   switch (Visibility) {
1606   default: break;
1607   case GlobalValue::HiddenVisibility:
1608     Attr = MAI->getHiddenVisibilityAttr();
1609     break;
1610   case GlobalValue::ProtectedVisibility:
1611     Attr = MAI->getProtectedVisibilityAttr();
1612     break;
1613   }
1614
1615   if (Attr != MCSA_Invalid)
1616     OutStreamer.EmitSymbolAttribute(Sym, Attr);
1617 }
1618
1619 void AsmPrinter::printOffset(int64_t Offset) const {
1620   if (Offset > 0)
1621     O << '+' << Offset;
1622   else if (Offset < 0)
1623     O << Offset;
1624 }
1625
1626 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1627   if (!S->usesMetadata())
1628     return 0;
1629   
1630   gcp_iterator GCPI = GCMetadataPrinters.find(S);
1631   if (GCPI != GCMetadataPrinters.end())
1632     return GCPI->second;
1633   
1634   const char *Name = S->getName().c_str();
1635   
1636   for (GCMetadataPrinterRegistry::iterator
1637          I = GCMetadataPrinterRegistry::begin(),
1638          E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1639     if (strcmp(Name, I->getName()) == 0) {
1640       GCMetadataPrinter *GMP = I->instantiate();
1641       GMP->S = S;
1642       GCMetadataPrinters.insert(std::make_pair(S, GMP));
1643       return GMP;
1644     }
1645   
1646   llvm_report_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
1647   return 0;
1648 }
1649
1650 /// EmitComments - Pretty-print comments for instructions
1651 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1652   if (!VerboseAsm)
1653     return;
1654
1655   bool Newline = false;
1656
1657   if (!MI.getDebugLoc().isUnknown()) {
1658     DILocation DLT = MF->getDILocation(MI.getDebugLoc());
1659
1660     // Print source line info.
1661     O.PadToColumn(MAI->getCommentColumn());
1662     O << MAI->getCommentString() << ' ';
1663     DIScope Scope = DLT.getScope();
1664     // Omit the directory, because it's likely to be long and uninteresting.
1665     if (!Scope.isNull())
1666       O << Scope.getFilename();
1667     else
1668       O << "<unknown>";
1669     O << ':' << DLT.getLineNumber();
1670     if (DLT.getColumnNumber() != 0)
1671       O << ':' << DLT.getColumnNumber();
1672     Newline = true;
1673   }
1674
1675   // Check for spills and reloads
1676   int FI;
1677
1678   const MachineFrameInfo *FrameInfo =
1679     MI.getParent()->getParent()->getFrameInfo();
1680
1681   // We assume a single instruction only has a spill or reload, not
1682   // both.
1683   const MachineMemOperand *MMO;
1684   if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
1685     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1686       MMO = *MI.memoperands_begin();
1687       if (Newline) O << '\n';
1688       O.PadToColumn(MAI->getCommentColumn());
1689       O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload";
1690       Newline = true;
1691     }
1692   }
1693   else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
1694     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1695       if (Newline) O << '\n';
1696       O.PadToColumn(MAI->getCommentColumn());
1697       O << MAI->getCommentString() << ' '
1698         << MMO->getSize() << "-byte Folded Reload";
1699       Newline = true;
1700     }
1701   }
1702   else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
1703     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1704       MMO = *MI.memoperands_begin();
1705       if (Newline) O << '\n';
1706       O.PadToColumn(MAI->getCommentColumn());
1707       O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill";
1708       Newline = true;
1709     }
1710   }
1711   else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
1712     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1713       if (Newline) O << '\n';
1714       O.PadToColumn(MAI->getCommentColumn());
1715       O << MAI->getCommentString() << ' '
1716         << MMO->getSize() << "-byte Folded Spill";
1717       Newline = true;
1718     }
1719   }
1720
1721   // Check for spill-induced copies
1722   unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1723   if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
1724                                       SrcSubIdx, DstSubIdx)) {
1725     if (MI.getAsmPrinterFlag(ReloadReuse)) {
1726       if (Newline) O << '\n';
1727       O.PadToColumn(MAI->getCommentColumn());
1728       O << MAI->getCommentString() << " Reload Reuse";
1729     }
1730   }
1731 }
1732