3e8c9131e01017b31d9fadb98b744a4165c22702
[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/GCMetadataPrinter.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineJumpTableInfo.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/DwarfWriter.h"
26 #include "llvm/Analysis/DebugInfo.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCInst.h"
29 #include "llvm/MC/MCSection.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/Mangler.h"
35 #include "llvm/MC/MCAsmInfo.h"
36 #include "llvm/Target/TargetData.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetLoweringObjectFile.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/ADT/SmallPtrSet.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/StringExtras.h"
44 #include <cerrno>
45 using namespace llvm;
46
47 static cl::opt<cl::boolOrDefault>
48 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
49            cl::init(cl::BOU_UNSET));
50
51 char AsmPrinter::ID = 0;
52 AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
53                        const MCAsmInfo *T, bool VDef)
54   : MachineFunctionPass(&ID), FunctionNumber(0), O(o),
55     TM(tm), MAI(T), TRI(tm.getRegisterInfo()),
56
57     OutContext(*new MCContext()),
58     OutStreamer(*createAsmStreamer(OutContext, O, *T, this)),
59
60     LastMI(0), LastFn(0), Counter(~0U),
61     PrevDLT(0, ~0U, ~0U) {
62   DW = 0; MMI = 0;
63   switch (AsmVerbose) {
64   case cl::BOU_UNSET: VerboseAsm = VDef;  break;
65   case cl::BOU_TRUE:  VerboseAsm = true;  break;
66   case cl::BOU_FALSE: VerboseAsm = false; break;
67   }
68 }
69
70 AsmPrinter::~AsmPrinter() {
71   for (gcp_iterator I = GCMetadataPrinters.begin(),
72                     E = GCMetadataPrinters.end(); I != E; ++I)
73     delete I->second;
74   
75   delete &OutStreamer;
76   delete &OutContext;
77 }
78
79 TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
80   return TM.getTargetLowering()->getObjFileLowering();
81 }
82
83 /// getCurrentSection() - Return the current section we are emitting to.
84 const MCSection *AsmPrinter::getCurrentSection() const {
85   return OutStreamer.getCurrentSection();
86 }
87
88
89 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
90   AU.setPreservesAll();
91   MachineFunctionPass::getAnalysisUsage(AU);
92   AU.addRequired<GCModuleInfo>();
93   if (VerboseAsm)
94     AU.addRequired<MachineLoopInfo>();
95 }
96
97 bool AsmPrinter::doInitialization(Module &M) {
98   // Initialize TargetLoweringObjectFile.
99   const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
100     .Initialize(OutContext, TM);
101   
102   Mang = new Mangler(M, MAI->getGlobalPrefix(), MAI->getPrivateGlobalPrefix(),
103                      MAI->getLinkerPrivateGlobalPrefix());
104   
105   if (MAI->doesAllowQuotesInName())
106     Mang->setUseQuotes(true);
107   
108   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
109   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
110
111   if (MAI->hasSingleParameterDotFile()) {
112     /* Very minimal debug info. It is ignored if we emit actual
113        debug info. If we don't, this at helps the user find where
114        a function came from. */
115     O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
116   }
117
118   for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
119     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
120       MP->beginAssembly(O, *this, *MAI);
121   
122   if (!M.getModuleInlineAsm().empty())
123     O << MAI->getCommentString() << " Start of file scope inline assembly\n"
124       << M.getModuleInlineAsm()
125       << '\n' << MAI->getCommentString()
126       << " End of file scope inline assembly\n";
127
128   if (MAI->doesSupportDebugInformation() ||
129       MAI->doesSupportExceptionHandling()) {
130     MMI = getAnalysisIfAvailable<MachineModuleInfo>();
131     if (MMI)
132       MMI->AnalyzeModule(M);
133     DW = getAnalysisIfAvailable<DwarfWriter>();
134     if (DW)
135       DW->BeginModule(&M, MMI, O, this, MAI);
136   }
137
138   return false;
139 }
140
141 bool AsmPrinter::doFinalization(Module &M) {
142   // Emit global variables.
143   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
144        I != E; ++I)
145     PrintGlobalVariable(I);
146   
147   // Emit final debug information.
148   if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
149     DW->EndModule();
150   
151   // If the target wants to know about weak references, print them all.
152   if (MAI->getWeakRefDirective()) {
153     // FIXME: This is not lazy, it would be nice to only print weak references
154     // to stuff that is actually used.  Note that doing so would require targets
155     // to notice uses in operands (due to constant exprs etc).  This should
156     // happen with the MC stuff eventually.
157
158     // Print out module-level global variables here.
159     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
160          I != E; ++I) {
161       if (I->hasExternalWeakLinkage())
162         O << MAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n';
163     }
164     
165     for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
166       if (I->hasExternalWeakLinkage())
167         O << MAI->getWeakRefDirective() << Mang->getMangledName(I) << '\n';
168     }
169   }
170
171   if (MAI->getSetDirective()) {
172     O << '\n';
173     for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
174          I != E; ++I) {
175       std::string Name = Mang->getMangledName(I);
176
177       const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
178       std::string Target = Mang->getMangledName(GV);
179
180       if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
181         O << "\t.globl\t" << Name << '\n';
182       else if (I->hasWeakLinkage())
183         O << MAI->getWeakRefDirective() << Name << '\n';
184       else if (!I->hasLocalLinkage())
185         llvm_unreachable("Invalid alias linkage");
186
187       printVisibility(Name, I->getVisibility());
188
189       O << MAI->getSetDirective() << ' ' << Name << ", " << Target << '\n';
190     }
191   }
192
193   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
194   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
195   for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
196     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
197       MP->finishAssembly(O, *this, *MAI);
198
199   // If we don't have any trampolines, then we don't require stack memory
200   // to be executable. Some targets have a directive to declare this.
201   Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
202   if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
203     if (MAI->getNonexecutableStackDirective())
204       O << MAI->getNonexecutableStackDirective() << '\n';
205
206   delete Mang; Mang = 0;
207   DW = 0; MMI = 0;
208   
209   OutStreamer.Finish();
210   return false;
211 }
212
213 std::string 
214 AsmPrinter::getCurrentFunctionEHName(const MachineFunction *MF) const {
215   assert(MF && "No machine function?");
216   return Mang->getMangledName(MF->getFunction(), ".eh",
217                               MAI->is_EHSymbolPrivate());
218 }
219
220 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
221   // What's my mangled name?
222   CurrentFnName = Mang->getMangledName(MF.getFunction());
223   IncrementFunctionNumber();
224
225   if (VerboseAsm) {
226     LI = &getAnalysis<MachineLoopInfo>();
227   }
228 }
229
230 namespace {
231   // SectionCPs - Keep track the alignment, constpool entries per Section.
232   struct SectionCPs {
233     const MCSection *S;
234     unsigned Alignment;
235     SmallVector<unsigned, 4> CPEs;
236     SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {};
237   };
238 }
239
240 /// EmitConstantPool - Print to the current output stream assembly
241 /// representations of the constants in the constant pool MCP. This is
242 /// used to print out constants which have been "spilled to memory" by
243 /// the code generator.
244 ///
245 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
246   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
247   if (CP.empty()) return;
248
249   // Calculate sections for constant pool entries. We collect entries to go into
250   // the same section together to reduce amount of section switch statements.
251   SmallVector<SectionCPs, 4> CPSections;
252   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
253     const MachineConstantPoolEntry &CPE = CP[i];
254     unsigned Align = CPE.getAlignment();
255     
256     SectionKind Kind;
257     switch (CPE.getRelocationInfo()) {
258     default: llvm_unreachable("Unknown section kind");
259     case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
260     case 1:
261       Kind = SectionKind::getReadOnlyWithRelLocal();
262       break;
263     case 0:
264     switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
265     case 4:  Kind = SectionKind::getMergeableConst4(); break;
266     case 8:  Kind = SectionKind::getMergeableConst8(); break;
267     case 16: Kind = SectionKind::getMergeableConst16();break;
268     default: Kind = SectionKind::getMergeableConst(); break;
269     }
270     }
271
272     const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
273     
274     // The number of sections are small, just do a linear search from the
275     // last section to the first.
276     bool Found = false;
277     unsigned SecIdx = CPSections.size();
278     while (SecIdx != 0) {
279       if (CPSections[--SecIdx].S == S) {
280         Found = true;
281         break;
282       }
283     }
284     if (!Found) {
285       SecIdx = CPSections.size();
286       CPSections.push_back(SectionCPs(S, Align));
287     }
288
289     if (Align > CPSections[SecIdx].Alignment)
290       CPSections[SecIdx].Alignment = Align;
291     CPSections[SecIdx].CPEs.push_back(i);
292   }
293
294   // Now print stuff into the calculated sections.
295   for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
296     OutStreamer.SwitchSection(CPSections[i].S);
297     EmitAlignment(Log2_32(CPSections[i].Alignment));
298
299     unsigned Offset = 0;
300     for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
301       unsigned CPI = CPSections[i].CPEs[j];
302       MachineConstantPoolEntry CPE = CP[CPI];
303
304       // Emit inter-object padding for alignment.
305       unsigned AlignMask = CPE.getAlignment() - 1;
306       unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
307       EmitZeros(NewOffset - Offset);
308
309       const Type *Ty = CPE.getType();
310       Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
311
312       O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
313         << CPI << ':';
314       if (VerboseAsm) {
315         O.PadToColumn(MAI->getCommentColumn());
316         O << MAI->getCommentString() << " constant ";
317         WriteTypeSymbolic(O, CPE.getType(), MF->getFunction()->getParent());
318       }
319       O << '\n';
320       if (CPE.isMachineConstantPoolEntry())
321         EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
322       else
323         EmitGlobalConstant(CPE.Val.ConstVal);
324     }
325   }
326 }
327
328 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
329 /// by the current function to the current output stream.  
330 ///
331 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
332                                    MachineFunction &MF) {
333   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
334   if (JT.empty()) return;
335
336   bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
337   
338   // Pick the directive to use to print the jump table entries, and switch to 
339   // the appropriate section.
340   TargetLowering *LoweringInfo = TM.getTargetLowering();
341
342   const Function *F = MF.getFunction();
343   bool JTInDiffSection = false;
344   if (F->isWeakForLinker() ||
345       (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
346     // In PIC mode, we need to emit the jump table to the same section as the
347     // function body itself, otherwise the label differences won't make sense.
348     // We should also do if the section name is NULL or function is declared in
349     // discardable section.
350     OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
351                                                                     TM));
352   } else {
353     // Otherwise, drop it in the readonly section.
354     const MCSection *ReadOnlySection = 
355       getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
356     OutStreamer.SwitchSection(ReadOnlySection);
357     JTInDiffSection = true;
358   }
359   
360   EmitAlignment(Log2_32(MJTI->getAlignment()));
361   
362   for (unsigned i = 0, e = JT.size(); i != e; ++i) {
363     const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
364     
365     // If this jump table was deleted, ignore it. 
366     if (JTBBs.empty()) continue;
367
368     // For PIC codegen, if possible we want to use the SetDirective to reduce
369     // the number of relocations the assembler will generate for the jump table.
370     // Set directives are all printed before the jump table itself.
371     SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
372     if (MAI->getSetDirective() && IsPic)
373       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
374         if (EmittedSets.insert(JTBBs[ii]))
375           printPICJumpTableSetLabel(i, JTBBs[ii]);
376     
377     // On some targets (e.g. darwin) we want to emit two consequtive labels
378     // before each jump table.  The first label is never referenced, but tells
379     // the assembler and linker the extents of the jump table object.  The
380     // second label is actually referenced by the code.
381     if (JTInDiffSection) {
382       if (const char *JTLabelPrefix = MAI->getJumpTableSpecialLabelPrefix())
383         O << JTLabelPrefix << "JTI" << getFunctionNumber() << '_' << i << ":\n";
384     }
385     
386     O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 
387       << '_' << i << ":\n";
388     
389     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
390       printPICJumpTableEntry(MJTI, JTBBs[ii], i);
391       O << '\n';
392     }
393   }
394 }
395
396 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
397                                         const MachineBasicBlock *MBB,
398                                         unsigned uid)  const {
399   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
400   
401   // Use JumpTableDirective otherwise honor the entry size from the jump table
402   // info.
403   const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC);
404   bool HadJTEntryDirective = JTEntryDirective != NULL;
405   if (!HadJTEntryDirective) {
406     JTEntryDirective = MJTI->getEntrySize() == 4 ?
407       MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
408   }
409
410   O << JTEntryDirective << ' ';
411
412   // If we have emitted set directives for the jump table entries, print 
413   // them rather than the entries themselves.  If we're emitting PIC, then
414   // emit the table entries as differences between two text section labels.
415   // If we're emitting non-PIC code, then emit the entries as direct
416   // references to the target basic blocks.
417   if (!isPIC) {
418     printBasicBlockLabel(MBB, false, false, false);
419   } else if (MAI->getSetDirective()) {
420     O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
421       << '_' << uid << "_set_" << MBB->getNumber();
422   } else {
423     printBasicBlockLabel(MBB, false, false, false);
424     // If the arch uses custom Jump Table directives, don't calc relative to
425     // JT
426     if (!HadJTEntryDirective) 
427       O << '-' << MAI->getPrivateGlobalPrefix() << "JTI"
428         << getFunctionNumber() << '_' << uid;
429   }
430 }
431
432
433 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
434 /// special global used by LLVM.  If so, emit it and return true, otherwise
435 /// do nothing and return false.
436 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
437   if (GV->getName() == "llvm.used") {
438     if (MAI->getUsedDirective() != 0)    // No need to emit this at all.
439       EmitLLVMUsedList(GV->getInitializer());
440     return true;
441   }
442
443   // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
444   if (GV->getSection() == "llvm.metadata" ||
445       GV->hasAvailableExternallyLinkage())
446     return true;
447   
448   if (!GV->hasAppendingLinkage()) return false;
449
450   assert(GV->hasInitializer() && "Not a special LLVM global!");
451   
452   const TargetData *TD = TM.getTargetData();
453   unsigned Align = Log2_32(TD->getPointerPrefAlignment());
454   if (GV->getName() == "llvm.global_ctors") {
455     OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
456     EmitAlignment(Align, 0);
457     EmitXXStructorList(GV->getInitializer());
458     return true;
459   } 
460   
461   if (GV->getName() == "llvm.global_dtors") {
462     OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
463     EmitAlignment(Align, 0);
464     EmitXXStructorList(GV->getInitializer());
465     return true;
466   }
467   
468   return false;
469 }
470
471 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
472 /// global in the specified llvm.used list for which emitUsedDirectiveFor
473 /// is true, as being used with this directive.
474 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
475   const char *Directive = MAI->getUsedDirective();
476
477   // Should be an array of 'i8*'.
478   ConstantArray *InitList = dyn_cast<ConstantArray>(List);
479   if (InitList == 0) return;
480   
481   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
482     const GlobalValue *GV =
483       dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
484     if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) {
485       O << Directive;
486       EmitConstantValueOnly(InitList->getOperand(i));
487       O << '\n';
488     }
489   }
490 }
491
492 /// EmitXXStructorList - Emit the ctor or dtor list.  This just prints out the 
493 /// function pointers, ignoring the init priority.
494 void AsmPrinter::EmitXXStructorList(Constant *List) {
495   // Should be an array of '{ int, void ()* }' structs.  The first value is the
496   // init priority, which we ignore.
497   if (!isa<ConstantArray>(List)) return;
498   ConstantArray *InitList = cast<ConstantArray>(List);
499   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
500     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
501       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
502
503       if (CS->getOperand(1)->isNullValue())
504         return;  // Found a null terminator, exit printing.
505       // Emit the function pointer.
506       EmitGlobalConstant(CS->getOperand(1));
507     }
508 }
509
510 /// getGlobalLinkName - Returns the asm/link name of of the specified
511 /// global variable.  Should be overridden by each target asm printer to
512 /// generate the appropriate value.
513 const std::string &AsmPrinter::getGlobalLinkName(const GlobalVariable *GV,
514                                                  std::string &LinkName) const {
515   if (isa<Function>(GV)) {
516     LinkName += MAI->getFunctionAddrPrefix();
517     LinkName += Mang->getMangledName(GV);
518     LinkName += MAI->getFunctionAddrSuffix();
519   } else {
520     LinkName += MAI->getGlobalVarAddrPrefix();
521     LinkName += Mang->getMangledName(GV);
522     LinkName += MAI->getGlobalVarAddrSuffix();
523   }  
524   
525   return LinkName;
526 }
527
528 /// EmitExternalGlobal - Emit the external reference to a global variable.
529 /// Should be overridden if an indirect reference should be used.
530 void AsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
531   std::string GLN;
532   O << getGlobalLinkName(GV, GLN);
533 }
534
535
536
537 //===----------------------------------------------------------------------===//
538 /// LEB 128 number encoding.
539
540 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
541 /// representing an unsigned leb128 value.
542 void AsmPrinter::PrintULEB128(unsigned Value) const {
543   char Buffer[20];
544   do {
545     unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
546     Value >>= 7;
547     if (Value) Byte |= 0x80;
548     O << "0x" << utohex_buffer(Byte, Buffer+20);
549     if (Value) O << ", ";
550   } while (Value);
551 }
552
553 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
554 /// representing a signed leb128 value.
555 void AsmPrinter::PrintSLEB128(int Value) const {
556   int Sign = Value >> (8 * sizeof(Value) - 1);
557   bool IsMore;
558   char Buffer[20];
559
560   do {
561     unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
562     Value >>= 7;
563     IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
564     if (IsMore) Byte |= 0x80;
565     O << "0x" << utohex_buffer(Byte, Buffer+20);
566     if (IsMore) O << ", ";
567   } while (IsMore);
568 }
569
570 //===--------------------------------------------------------------------===//
571 // Emission and print routines
572 //
573
574 /// PrintHex - Print a value as a hexidecimal value.
575 ///
576 void AsmPrinter::PrintHex(int Value) const { 
577   char Buffer[20];
578   O << "0x" << utohex_buffer(static_cast<unsigned>(Value), Buffer+20);
579 }
580
581 /// EOL - Print a newline character to asm stream.  If a comment is present
582 /// then it will be printed first.  Comments should not contain '\n'.
583 void AsmPrinter::EOL() const {
584   O << '\n';
585 }
586
587 void AsmPrinter::EOL(const std::string &Comment) const {
588   if (VerboseAsm && !Comment.empty()) {
589     O.PadToColumn(MAI->getCommentColumn());
590     O << MAI->getCommentString()
591       << ' '
592       << Comment;
593   }
594   O << '\n';
595 }
596
597 void AsmPrinter::EOL(const char* Comment) const {
598   if (VerboseAsm && *Comment) {
599     O.PadToColumn(MAI->getCommentColumn());
600     O << MAI->getCommentString()
601       << ' '
602       << Comment;
603   }
604   O << '\n';
605 }
606
607 static const char *DecodeDWARFEncoding(unsigned Encoding) {
608   switch (Encoding) {
609   case dwarf::DW_EH_PE_absptr:
610     return "absptr";
611   case dwarf::DW_EH_PE_omit:
612     return "omit";
613   case dwarf::DW_EH_PE_pcrel:
614     return "pcrel";
615   case dwarf::DW_EH_PE_udata4:
616     return "udata4";
617   case dwarf::DW_EH_PE_udata8:
618     return "udata8";
619   case dwarf::DW_EH_PE_sdata4:
620     return "sdata4";
621   case dwarf::DW_EH_PE_sdata8:
622     return "sdata8";
623   case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
624     return "pcrel udata4";
625   case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
626     return "pcrel sdata4";
627   case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
628     return "pcrel udata8";
629   case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
630     return "pcrel sdata8";
631   case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4:
632     return "indirect pcrel udata4";
633   case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4:
634     return "indirect pcrel sdata4";
635   case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8:
636     return "indirect pcrel udata8";
637   case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8:
638     return "indirect pcrel sdata8";
639   }
640
641   return 0;
642 }
643
644 void AsmPrinter::EOL(const char *Comment, unsigned Encoding) const {
645   if (VerboseAsm && *Comment) {
646     O.PadToColumn(MAI->getCommentColumn());
647     O << MAI->getCommentString()
648       << ' '
649       << Comment;
650
651     if (const char *EncStr = DecodeDWARFEncoding(Encoding))
652       O << " (" << EncStr << ')';
653   }
654   O << '\n';
655 }
656
657 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
658 /// unsigned leb128 value.
659 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
660   if (MAI->hasLEB128()) {
661     O << "\t.uleb128\t"
662       << Value;
663   } else {
664     O << MAI->getData8bitsDirective();
665     PrintULEB128(Value);
666   }
667 }
668
669 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
670 /// signed leb128 value.
671 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
672   if (MAI->hasLEB128()) {
673     O << "\t.sleb128\t"
674       << Value;
675   } else {
676     O << MAI->getData8bitsDirective();
677     PrintSLEB128(Value);
678   }
679 }
680
681 /// EmitInt8 - Emit a byte directive and value.
682 ///
683 void AsmPrinter::EmitInt8(int Value) const {
684   O << MAI->getData8bitsDirective();
685   PrintHex(Value & 0xFF);
686 }
687
688 /// EmitInt16 - Emit a short directive and value.
689 ///
690 void AsmPrinter::EmitInt16(int Value) const {
691   O << MAI->getData16bitsDirective();
692   PrintHex(Value & 0xFFFF);
693 }
694
695 /// EmitInt32 - Emit a long directive and value.
696 ///
697 void AsmPrinter::EmitInt32(int Value) const {
698   O << MAI->getData32bitsDirective();
699   PrintHex(Value);
700 }
701
702 /// EmitInt64 - Emit a long long directive and value.
703 ///
704 void AsmPrinter::EmitInt64(uint64_t Value) const {
705   if (MAI->getData64bitsDirective()) {
706     O << MAI->getData64bitsDirective();
707     PrintHex(Value);
708   } else {
709     if (TM.getTargetData()->isBigEndian()) {
710       EmitInt32(unsigned(Value >> 32)); O << '\n';
711       EmitInt32(unsigned(Value));
712     } else {
713       EmitInt32(unsigned(Value)); O << '\n';
714       EmitInt32(unsigned(Value >> 32));
715     }
716   }
717 }
718
719 /// toOctal - Convert the low order bits of X into an octal digit.
720 ///
721 static inline char toOctal(int X) {
722   return (X&7)+'0';
723 }
724
725 /// printStringChar - Print a char, escaped if necessary.
726 ///
727 static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
728   if (C == '"') {
729     O << "\\\"";
730   } else if (C == '\\') {
731     O << "\\\\";
732   } else if (isprint((unsigned char)C)) {
733     O << C;
734   } else {
735     switch(C) {
736     case '\b': O << "\\b"; break;
737     case '\f': O << "\\f"; break;
738     case '\n': O << "\\n"; break;
739     case '\r': O << "\\r"; break;
740     case '\t': O << "\\t"; break;
741     default:
742       O << '\\';
743       O << toOctal(C >> 6);
744       O << toOctal(C >> 3);
745       O << toOctal(C >> 0);
746       break;
747     }
748   }
749 }
750
751 /// EmitString - Emit a string with quotes and a null terminator.
752 /// Special characters are emitted properly.
753 /// \literal (Eg. '\t') \endliteral
754 void AsmPrinter::EmitString(const std::string &String) const {
755   EmitString(String.c_str(), String.size());
756 }
757
758 void AsmPrinter::EmitString(const char *String, unsigned Size) const {
759   const char* AscizDirective = MAI->getAscizDirective();
760   if (AscizDirective)
761     O << AscizDirective;
762   else
763     O << MAI->getAsciiDirective();
764   O << '\"';
765   for (unsigned i = 0; i < Size; ++i)
766     printStringChar(O, String[i]);
767   if (AscizDirective)
768     O << '\"';
769   else
770     O << "\\0\"";
771 }
772
773
774 /// EmitFile - Emit a .file directive.
775 void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
776   O << "\t.file\t" << Number << " \"";
777   for (unsigned i = 0, N = Name.size(); i < N; ++i)
778     printStringChar(O, Name[i]);
779   O << '\"';
780 }
781
782
783 //===----------------------------------------------------------------------===//
784
785 // EmitAlignment - Emit an alignment directive to the specified power of
786 // two boundary.  For example, if you pass in 3 here, you will get an 8
787 // byte alignment.  If a global value is specified, and if that global has
788 // an explicit alignment requested, it will unconditionally override the
789 // alignment request.  However, if ForcedAlignBits is specified, this value
790 // has final say: the ultimate alignment will be the max of ForcedAlignBits
791 // and the alignment computed with NumBits and the global.
792 //
793 // The algorithm is:
794 //     Align = NumBits;
795 //     if (GV && GV->hasalignment) Align = GV->getalignment();
796 //     Align = std::max(Align, ForcedAlignBits);
797 //
798 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
799                                unsigned ForcedAlignBits,
800                                bool UseFillExpr) const {
801   if (GV && GV->getAlignment())
802     NumBits = Log2_32(GV->getAlignment());
803   NumBits = std::max(NumBits, ForcedAlignBits);
804   
805   if (NumBits == 0) return;   // No need to emit alignment.
806   
807   unsigned FillValue = 0;
808   if (getCurrentSection()->getKind().isText())
809     FillValue = MAI->getTextAlignFillValue();
810   
811   OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
812 }
813
814 /// EmitZeros - Emit a block of zeros.
815 ///
816 void AsmPrinter::EmitZeros(uint64_t NumZeros, unsigned AddrSpace) const {
817   if (NumZeros) {
818     if (MAI->getZeroDirective()) {
819       O << MAI->getZeroDirective() << NumZeros;
820       if (MAI->getZeroDirectiveSuffix())
821         O << MAI->getZeroDirectiveSuffix();
822       O << '\n';
823     } else {
824       for (; NumZeros; --NumZeros)
825         O << MAI->getData8bitsDirective(AddrSpace) << "0\n";
826     }
827   }
828 }
829
830 // Print out the specified constant, without a storage class.  Only the
831 // constants valid in constant expressions can occur here.
832 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
833   if (CV->isNullValue() || isa<UndefValue>(CV))
834     O << '0';
835   else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
836     O << CI->getZExtValue();
837   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
838     // This is a constant address for a global variable or function. Use the
839     // name of the variable or function as the address value, possibly
840     // decorating it with GlobalVarAddrPrefix/Suffix or
841     // FunctionAddrPrefix/Suffix (these all default to "" )
842     if (isa<Function>(GV)) {
843       O << MAI->getFunctionAddrPrefix()
844         << Mang->getMangledName(GV)
845         << MAI->getFunctionAddrSuffix();
846     } else {
847       O << MAI->getGlobalVarAddrPrefix()
848         << Mang->getMangledName(GV)
849         << MAI->getGlobalVarAddrSuffix();
850     }
851   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
852     const TargetData *TD = TM.getTargetData();
853     unsigned Opcode = CE->getOpcode();    
854     switch (Opcode) {
855     case Instruction::Trunc:
856     case Instruction::ZExt:
857     case Instruction::SExt:
858     case Instruction::FPTrunc:
859     case Instruction::FPExt:
860     case Instruction::UIToFP:
861     case Instruction::SIToFP:
862     case Instruction::FPToUI:
863     case Instruction::FPToSI:
864       llvm_unreachable("FIXME: Don't support this constant cast expr");
865     case Instruction::GetElementPtr: {
866       // generate a symbolic expression for the byte address
867       const Constant *ptrVal = CE->getOperand(0);
868       SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
869       if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
870                                                 idxVec.size())) {
871         // Truncate/sext the offset to the pointer size.
872         if (TD->getPointerSizeInBits() != 64) {
873           int SExtAmount = 64-TD->getPointerSizeInBits();
874           Offset = (Offset << SExtAmount) >> SExtAmount;
875         }
876         
877         if (Offset)
878           O << '(';
879         EmitConstantValueOnly(ptrVal);
880         if (Offset > 0)
881           O << ") + " << Offset;
882         else if (Offset < 0)
883           O << ") - " << -Offset;
884       } else {
885         EmitConstantValueOnly(ptrVal);
886       }
887       break;
888     }
889     case Instruction::BitCast:
890       return EmitConstantValueOnly(CE->getOperand(0));
891
892     case Instruction::IntToPtr: {
893       // Handle casts to pointers by changing them into casts to the appropriate
894       // integer type.  This promotes constant folding and simplifies this code.
895       Constant *Op = CE->getOperand(0);
896       Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
897                                         false/*ZExt*/);
898       return EmitConstantValueOnly(Op);
899     }
900       
901       
902     case Instruction::PtrToInt: {
903       // Support only foldable casts to/from pointers that can be eliminated by
904       // changing the pointer to the appropriately sized integer type.
905       Constant *Op = CE->getOperand(0);
906       const Type *Ty = CE->getType();
907
908       // We can emit the pointer value into this slot if the slot is an
909       // integer slot greater or equal to the size of the pointer.
910       if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
911         return EmitConstantValueOnly(Op);
912
913       O << "((";
914       EmitConstantValueOnly(Op);
915       APInt ptrMask =
916         APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
917       
918       SmallString<40> S;
919       ptrMask.toStringUnsigned(S);
920       O << ") & " << S.str() << ')';
921       break;
922     }
923     case Instruction::Add:
924     case Instruction::Sub:
925     case Instruction::And:
926     case Instruction::Or:
927     case Instruction::Xor:
928       O << '(';
929       EmitConstantValueOnly(CE->getOperand(0));
930       O << ')';
931       switch (Opcode) {
932       case Instruction::Add:
933        O << " + ";
934        break;
935       case Instruction::Sub:
936        O << " - ";
937        break;
938       case Instruction::And:
939        O << " & ";
940        break;
941       case Instruction::Or:
942        O << " | ";
943        break;
944       case Instruction::Xor:
945        O << " ^ ";
946        break;
947       default:
948        break;
949       }
950       O << '(';
951       EmitConstantValueOnly(CE->getOperand(1));
952       O << ')';
953       break;
954     default:
955       llvm_unreachable("Unsupported operator!");
956     }
957   } else {
958     llvm_unreachable("Unknown constant value!");
959   }
960 }
961
962 /// printAsCString - Print the specified array as a C compatible string, only if
963 /// the predicate isString is true.
964 ///
965 static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
966                            unsigned LastElt) {
967   assert(CVA->isString() && "Array is not string compatible!");
968
969   O << '\"';
970   for (unsigned i = 0; i != LastElt; ++i) {
971     unsigned char C =
972         (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
973     printStringChar(O, C);
974   }
975   O << '\"';
976 }
977
978 /// EmitString - Emit a zero-byte-terminated string constant.
979 ///
980 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
981   unsigned NumElts = CVA->getNumOperands();
982   if (MAI->getAscizDirective() && NumElts && 
983       cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
984     O << MAI->getAscizDirective();
985     printAsCString(O, CVA, NumElts-1);
986   } else {
987     O << MAI->getAsciiDirective();
988     printAsCString(O, CVA, NumElts);
989   }
990   O << '\n';
991 }
992
993 void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA,
994                                          unsigned AddrSpace) {
995   if (CVA->isString()) {
996     EmitString(CVA);
997   } else { // Not a string.  Print the values in successive locations
998     for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
999       EmitGlobalConstant(CVA->getOperand(i), AddrSpace);
1000   }
1001 }
1002
1003 void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) {
1004   const VectorType *PTy = CP->getType();
1005   
1006   for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
1007     EmitGlobalConstant(CP->getOperand(I));
1008 }
1009
1010 void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
1011                                           unsigned AddrSpace) {
1012   // Print the fields in successive locations. Pad to align if needed!
1013   const TargetData *TD = TM.getTargetData();
1014   unsigned Size = TD->getTypeAllocSize(CVS->getType());
1015   const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
1016   uint64_t sizeSoFar = 0;
1017   for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
1018     const Constant* field = CVS->getOperand(i);
1019
1020     // Check if padding is needed and insert one or more 0s.
1021     uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
1022     uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
1023                         - cvsLayout->getElementOffset(i)) - fieldSize;
1024     sizeSoFar += fieldSize + padSize;
1025
1026     // Now print the actual field value.
1027     EmitGlobalConstant(field, AddrSpace);
1028
1029     // Insert padding - this may include padding to increase the size of the
1030     // current field up to the ABI size (if the struct is not packed) as well
1031     // as padding to ensure that the next field starts at the right offset.
1032     EmitZeros(padSize, AddrSpace);
1033   }
1034   assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
1035          "Layout of constant struct may be incorrect!");
1036 }
1037
1038 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP, 
1039                                       unsigned AddrSpace) {
1040   // FP Constants are printed as integer constants to avoid losing
1041   // precision...
1042   LLVMContext &Context = CFP->getContext();
1043   const TargetData *TD = TM.getTargetData();
1044   if (CFP->getType() == Type::getDoubleTy(Context)) {
1045     double Val = CFP->getValueAPF().convertToDouble();  // for comment only
1046     uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1047     if (MAI->getData64bitsDirective(AddrSpace)) {
1048       O << MAI->getData64bitsDirective(AddrSpace) << i;
1049       if (VerboseAsm) {
1050         O.PadToColumn(MAI->getCommentColumn());
1051         O << MAI->getCommentString() << " double " << Val;
1052       }
1053       O << '\n';
1054     } else if (TD->isBigEndian()) {
1055       O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1056       if (VerboseAsm) {
1057         O.PadToColumn(MAI->getCommentColumn());
1058         O << MAI->getCommentString()
1059           << " most significant word of double " << Val;
1060       }
1061       O << '\n';
1062       O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1063       if (VerboseAsm) {
1064         O.PadToColumn(MAI->getCommentColumn());
1065         O << MAI->getCommentString()
1066           << " least significant word of double " << Val;
1067       }
1068       O << '\n';
1069     } else {
1070       O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1071       if (VerboseAsm) {
1072         O.PadToColumn(MAI->getCommentColumn());
1073         O << MAI->getCommentString()
1074           << " least significant word of double " << Val;
1075       }
1076       O << '\n';
1077       O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1078       if (VerboseAsm) {
1079         O.PadToColumn(MAI->getCommentColumn());
1080         O << MAI->getCommentString()
1081           << " most significant word of double " << Val;
1082       }
1083       O << '\n';
1084     }
1085     return;
1086   } else if (CFP->getType() == Type::getFloatTy(Context)) {
1087     float Val = CFP->getValueAPF().convertToFloat();  // for comment only
1088     O << MAI->getData32bitsDirective(AddrSpace)
1089       << CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1090     if (VerboseAsm) {
1091       O.PadToColumn(MAI->getCommentColumn());
1092       O << MAI->getCommentString() << " float " << Val;
1093     }
1094     O << '\n';
1095     return;
1096   } else if (CFP->getType() == Type::getX86_FP80Ty(Context)) {
1097     // all long double variants are printed as hex
1098     // api needed to prevent premature destruction
1099     APInt api = CFP->getValueAPF().bitcastToAPInt();
1100     const uint64_t *p = api.getRawData();
1101     // Convert to double so we can print the approximate val as a comment.
1102     APFloat DoubleVal = CFP->getValueAPF();
1103     bool ignored;
1104     DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1105                       &ignored);
1106     if (TD->isBigEndian()) {
1107       O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1108       if (VerboseAsm) {
1109         O.PadToColumn(MAI->getCommentColumn());
1110         O << MAI->getCommentString()
1111           << " most significant halfword of x86_fp80 ~"
1112           << DoubleVal.convertToDouble();
1113       }
1114       O << '\n';
1115       O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1116       if (VerboseAsm) {
1117         O.PadToColumn(MAI->getCommentColumn());
1118         O << MAI->getCommentString() << " next halfword";
1119       }
1120       O << '\n';
1121       O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1122       if (VerboseAsm) {
1123         O.PadToColumn(MAI->getCommentColumn());
1124         O << MAI->getCommentString() << " next halfword";
1125       }
1126       O << '\n';
1127       O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1128       if (VerboseAsm) {
1129         O.PadToColumn(MAI->getCommentColumn());
1130         O << MAI->getCommentString() << " next halfword";
1131       }
1132       O << '\n';
1133       O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1134       if (VerboseAsm) {
1135         O.PadToColumn(MAI->getCommentColumn());
1136         O << MAI->getCommentString()
1137           << " least significant halfword";
1138       }
1139       O << '\n';
1140      } else {
1141       O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1142       if (VerboseAsm) {
1143         O.PadToColumn(MAI->getCommentColumn());
1144         O << MAI->getCommentString()
1145           << " least significant halfword of x86_fp80 ~"
1146           << DoubleVal.convertToDouble();
1147       }
1148       O << '\n';
1149       O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1150       if (VerboseAsm) {
1151         O.PadToColumn(MAI->getCommentColumn());
1152         O << MAI->getCommentString()
1153           << " next halfword";
1154       }
1155       O << '\n';
1156       O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1157       if (VerboseAsm) {
1158         O.PadToColumn(MAI->getCommentColumn());
1159         O << MAI->getCommentString()
1160           << " next halfword";
1161       }
1162       O << '\n';
1163       O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1164       if (VerboseAsm) {
1165         O.PadToColumn(MAI->getCommentColumn());
1166         O << MAI->getCommentString()
1167           << " next halfword";
1168       }
1169       O << '\n';
1170       O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1171       if (VerboseAsm) {
1172         O.PadToColumn(MAI->getCommentColumn());
1173         O << MAI->getCommentString()
1174           << " most significant halfword";
1175       }
1176       O << '\n';
1177     }
1178     EmitZeros(TD->getTypeAllocSize(Type::getX86_FP80Ty(Context)) -
1179               TD->getTypeStoreSize(Type::getX86_FP80Ty(Context)), AddrSpace);
1180     return;
1181   } else if (CFP->getType() == Type::getPPC_FP128Ty(Context)) {
1182     // all long double variants are printed as hex
1183     // api needed to prevent premature destruction
1184     APInt api = CFP->getValueAPF().bitcastToAPInt();
1185     const uint64_t *p = api.getRawData();
1186     if (TD->isBigEndian()) {
1187       O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1188       if (VerboseAsm) {
1189         O.PadToColumn(MAI->getCommentColumn());
1190         O << MAI->getCommentString()
1191           << " most significant word of ppc_fp128";
1192       }
1193       O << '\n';
1194       O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1195       if (VerboseAsm) {
1196         O.PadToColumn(MAI->getCommentColumn());
1197         O << MAI->getCommentString()
1198         << " next word";
1199       }
1200       O << '\n';
1201       O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1202       if (VerboseAsm) {
1203         O.PadToColumn(MAI->getCommentColumn());
1204         O << MAI->getCommentString()
1205           << " next word";
1206       }
1207       O << '\n';
1208       O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1209       if (VerboseAsm) {
1210         O.PadToColumn(MAI->getCommentColumn());
1211         O << MAI->getCommentString()
1212           << " least significant word";
1213       }
1214       O << '\n';
1215      } else {
1216       O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1217       if (VerboseAsm) {
1218         O.PadToColumn(MAI->getCommentColumn());
1219         O << MAI->getCommentString()
1220           << " least significant word of ppc_fp128";
1221       }
1222       O << '\n';
1223       O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1224       if (VerboseAsm) {
1225         O.PadToColumn(MAI->getCommentColumn());
1226         O << MAI->getCommentString()
1227           << " next word";
1228       }
1229       O << '\n';
1230       O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1231       if (VerboseAsm) {
1232         O.PadToColumn(MAI->getCommentColumn());
1233         O << MAI->getCommentString()
1234           << " next word";
1235       }
1236       O << '\n';
1237       O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1238       if (VerboseAsm) {
1239         O.PadToColumn(MAI->getCommentColumn());
1240         O << MAI->getCommentString()
1241           << " most significant word";
1242       }
1243       O << '\n';
1244     }
1245     return;
1246   } else llvm_unreachable("Floating point constant type not handled");
1247 }
1248
1249 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
1250                                             unsigned AddrSpace) {
1251   const TargetData *TD = TM.getTargetData();
1252   unsigned BitWidth = CI->getBitWidth();
1253   assert(isPowerOf2_32(BitWidth) &&
1254          "Non-power-of-2-sized integers not handled!");
1255
1256   // We don't expect assemblers to support integer data directives
1257   // for more than 64 bits, so we emit the data in at most 64-bit
1258   // quantities at a time.
1259   const uint64_t *RawData = CI->getValue().getRawData();
1260   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1261     uint64_t Val;
1262     if (TD->isBigEndian())
1263       Val = RawData[e - i - 1];
1264     else
1265       Val = RawData[i];
1266
1267     if (MAI->getData64bitsDirective(AddrSpace))
1268       O << MAI->getData64bitsDirective(AddrSpace) << Val << '\n';
1269     else if (TD->isBigEndian()) {
1270       O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1271       if (VerboseAsm) {
1272         O.PadToColumn(MAI->getCommentColumn());
1273         O << MAI->getCommentString()
1274           << " most significant half of i64 " << Val;
1275       }
1276       O << '\n';
1277       O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1278       if (VerboseAsm) {
1279         O.PadToColumn(MAI->getCommentColumn());
1280         O << MAI->getCommentString()
1281           << " least significant half of i64 " << Val;
1282       }
1283       O << '\n';
1284     } else {
1285       O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1286       if (VerboseAsm) {
1287         O.PadToColumn(MAI->getCommentColumn());
1288         O << MAI->getCommentString()
1289           << " least significant half of i64 " << Val;
1290       }
1291       O << '\n';
1292       O << MAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1293       if (VerboseAsm) {
1294         O.PadToColumn(MAI->getCommentColumn());
1295         O << MAI->getCommentString()
1296           << " most significant half of i64 " << Val;
1297       }
1298       O << '\n';
1299     }
1300   }
1301 }
1302
1303 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1304 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1305   const TargetData *TD = TM.getTargetData();
1306   const Type *type = CV->getType();
1307   unsigned Size = TD->getTypeAllocSize(type);
1308
1309   if (CV->isNullValue() || isa<UndefValue>(CV)) {
1310     EmitZeros(Size, AddrSpace);
1311     return;
1312   } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
1313     EmitGlobalConstantArray(CVA , AddrSpace);
1314     return;
1315   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
1316     EmitGlobalConstantStruct(CVS, AddrSpace);
1317     return;
1318   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1319     EmitGlobalConstantFP(CFP, AddrSpace);
1320     return;
1321   } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1322     // Small integers are handled below; large integers are handled here.
1323     if (Size > 4) {
1324       EmitGlobalConstantLargeInt(CI, AddrSpace);
1325       return;
1326     }
1327   } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1328     EmitGlobalConstantVector(CP);
1329     return;
1330   }
1331
1332   printDataDirective(type, AddrSpace);
1333   EmitConstantValueOnly(CV);
1334   if (VerboseAsm) {
1335     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1336       SmallString<40> S;
1337       CI->getValue().toStringUnsigned(S, 16);
1338       O.PadToColumn(MAI->getCommentColumn());
1339       O << MAI->getCommentString() << " 0x" << S.str();
1340     }
1341   }
1342   O << '\n';
1343 }
1344
1345 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1346   // Target doesn't support this yet!
1347   llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1348 }
1349
1350 /// PrintSpecial - Print information related to the specified machine instr
1351 /// that is independent of the operand, and may be independent of the instr
1352 /// itself.  This can be useful for portably encoding the comment character
1353 /// or other bits of target-specific knowledge into the asmstrings.  The
1354 /// syntax used is ${:comment}.  Targets can override this to add support
1355 /// for their own strange codes.
1356 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1357   if (!strcmp(Code, "private")) {
1358     O << MAI->getPrivateGlobalPrefix();
1359   } else if (!strcmp(Code, "comment")) {
1360     if (VerboseAsm)
1361       O << MAI->getCommentString();
1362   } else if (!strcmp(Code, "uid")) {
1363     // Comparing the address of MI isn't sufficient, because machineinstrs may
1364     // be allocated to the same address across functions.
1365     const Function *ThisF = MI->getParent()->getParent()->getFunction();
1366     
1367     // If this is a new LastFn instruction, bump the counter.
1368     if (LastMI != MI || LastFn != ThisF) {
1369       ++Counter;
1370       LastMI = MI;
1371       LastFn = ThisF;
1372     }
1373     O << Counter;
1374   } else {
1375     std::string msg;
1376     raw_string_ostream Msg(msg);
1377     Msg << "Unknown special formatter '" << Code
1378          << "' for machine instr: " << *MI;
1379     llvm_report_error(Msg.str());
1380   }    
1381 }
1382
1383 /// processDebugLoc - Processes the debug information of each machine
1384 /// instruction's DebugLoc.
1385 void AsmPrinter::processDebugLoc(DebugLoc DL) {
1386   if (!MAI || !DW)
1387     return;
1388   
1389   if (MAI->doesSupportDebugInformation() && DW->ShouldEmitDwarfDebug()) {
1390     if (!DL.isUnknown()) {
1391       DebugLocTuple CurDLT = MF->getDebugLocTuple(DL);
1392
1393       if (CurDLT.CompileUnit != 0 && PrevDLT != CurDLT) {
1394         printLabel(DW->RecordSourceLine(CurDLT.Line, CurDLT.Col,
1395                                         DICompileUnit(CurDLT.CompileUnit)));
1396         O << '\n';
1397       }
1398
1399       PrevDLT = CurDLT;
1400     }
1401   }
1402 }
1403
1404 /// printInlineAsm - This method formats and prints the specified machine
1405 /// instruction that is an inline asm.
1406 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1407   unsigned NumOperands = MI->getNumOperands();
1408   
1409   // Count the number of register definitions.
1410   unsigned NumDefs = 0;
1411   for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1412        ++NumDefs)
1413     assert(NumDefs != NumOperands-1 && "No asm string?");
1414   
1415   assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1416
1417   // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1418   const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1419
1420   // If this asmstr is empty, just print the #APP/#NOAPP markers.
1421   // These are useful to see where empty asm's wound up.
1422   if (AsmStr[0] == 0) {
1423     O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1424     O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
1425     return;
1426   }
1427   
1428   O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1429
1430   // The variant of the current asmprinter.
1431   int AsmPrinterVariant = MAI->getAssemblerDialect();
1432
1433   int CurVariant = -1;            // The number of the {.|.|.} region we are in.
1434   const char *LastEmitted = AsmStr; // One past the last character emitted.
1435   
1436   while (*LastEmitted) {
1437     switch (*LastEmitted) {
1438     default: {
1439       // Not a special case, emit the string section literally.
1440       const char *LiteralEnd = LastEmitted+1;
1441       while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1442              *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1443         ++LiteralEnd;
1444       if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1445         O.write(LastEmitted, LiteralEnd-LastEmitted);
1446       LastEmitted = LiteralEnd;
1447       break;
1448     }
1449     case '\n':
1450       ++LastEmitted;   // Consume newline character.
1451       O << '\n';       // Indent code with newline.
1452       break;
1453     case '$': {
1454       ++LastEmitted;   // Consume '$' character.
1455       bool Done = true;
1456
1457       // Handle escapes.
1458       switch (*LastEmitted) {
1459       default: Done = false; break;
1460       case '$':     // $$ -> $
1461         if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1462           O << '$';
1463         ++LastEmitted;  // Consume second '$' character.
1464         break;
1465       case '(':             // $( -> same as GCC's { character.
1466         ++LastEmitted;      // Consume '(' character.
1467         if (CurVariant != -1) {
1468           llvm_report_error("Nested variants found in inline asm string: '"
1469                             + std::string(AsmStr) + "'");
1470         }
1471         CurVariant = 0;     // We're in the first variant now.
1472         break;
1473       case '|':
1474         ++LastEmitted;  // consume '|' character.
1475         if (CurVariant == -1)
1476           O << '|';       // this is gcc's behavior for | outside a variant
1477         else
1478           ++CurVariant;   // We're in the next variant.
1479         break;
1480       case ')':         // $) -> same as GCC's } char.
1481         ++LastEmitted;  // consume ')' character.
1482         if (CurVariant == -1)
1483           O << '}';     // this is gcc's behavior for } outside a variant
1484         else 
1485           CurVariant = -1;
1486         break;
1487       }
1488       if (Done) break;
1489       
1490       bool HasCurlyBraces = false;
1491       if (*LastEmitted == '{') {     // ${variable}
1492         ++LastEmitted;               // Consume '{' character.
1493         HasCurlyBraces = true;
1494       }
1495       
1496       // If we have ${:foo}, then this is not a real operand reference, it is a
1497       // "magic" string reference, just like in .td files.  Arrange to call
1498       // PrintSpecial.
1499       if (HasCurlyBraces && *LastEmitted == ':') {
1500         ++LastEmitted;
1501         const char *StrStart = LastEmitted;
1502         const char *StrEnd = strchr(StrStart, '}');
1503         if (StrEnd == 0) {
1504           llvm_report_error("Unterminated ${:foo} operand in inline asm string: '" 
1505                             + std::string(AsmStr) + "'");
1506         }
1507         
1508         std::string Val(StrStart, StrEnd);
1509         PrintSpecial(MI, Val.c_str());
1510         LastEmitted = StrEnd+1;
1511         break;
1512       }
1513             
1514       const char *IDStart = LastEmitted;
1515       char *IDEnd;
1516       errno = 0;
1517       long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1518       if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1519         llvm_report_error("Bad $ operand number in inline asm string: '" 
1520                           + std::string(AsmStr) + "'");
1521       }
1522       LastEmitted = IDEnd;
1523       
1524       char Modifier[2] = { 0, 0 };
1525       
1526       if (HasCurlyBraces) {
1527         // If we have curly braces, check for a modifier character.  This
1528         // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1529         if (*LastEmitted == ':') {
1530           ++LastEmitted;    // Consume ':' character.
1531           if (*LastEmitted == 0) {
1532             llvm_report_error("Bad ${:} expression in inline asm string: '" 
1533                               + std::string(AsmStr) + "'");
1534           }
1535           
1536           Modifier[0] = *LastEmitted;
1537           ++LastEmitted;    // Consume modifier character.
1538         }
1539         
1540         if (*LastEmitted != '}') {
1541           llvm_report_error("Bad ${} expression in inline asm string: '" 
1542                             + std::string(AsmStr) + "'");
1543         }
1544         ++LastEmitted;    // Consume '}' character.
1545       }
1546       
1547       if ((unsigned)Val >= NumOperands-1) {
1548         llvm_report_error("Invalid $ operand number in inline asm string: '" 
1549                           + std::string(AsmStr) + "'");
1550       }
1551       
1552       // Okay, we finally have a value number.  Ask the target to print this
1553       // operand!
1554       if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1555         unsigned OpNo = 1;
1556
1557         bool Error = false;
1558
1559         // Scan to find the machine operand number for the operand.
1560         for (; Val; --Val) {
1561           if (OpNo >= MI->getNumOperands()) break;
1562           unsigned OpFlags = MI->getOperand(OpNo).getImm();
1563           OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1564         }
1565
1566         if (OpNo >= MI->getNumOperands()) {
1567           Error = true;
1568         } else {
1569           unsigned OpFlags = MI->getOperand(OpNo).getImm();
1570           ++OpNo;  // Skip over the ID number.
1571
1572           if (Modifier[0]=='l')  // labels are target independent
1573             printBasicBlockLabel(MI->getOperand(OpNo).getMBB(), 
1574                                  false, false, false);
1575           else {
1576             AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1577             if ((OpFlags & 7) == 4) {
1578               Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1579                                                 Modifier[0] ? Modifier : 0);
1580             } else {
1581               Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1582                                           Modifier[0] ? Modifier : 0);
1583             }
1584           }
1585         }
1586         if (Error) {
1587           std::string msg;
1588           raw_string_ostream Msg(msg);
1589           Msg << "Invalid operand found in inline asm: '"
1590                << AsmStr << "'\n";
1591           MI->print(Msg);
1592           llvm_report_error(Msg.str());
1593         }
1594       }
1595       break;
1596     }
1597     }
1598   }
1599   O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
1600 }
1601
1602 /// printImplicitDef - This method prints the specified machine instruction
1603 /// that is an implicit def.
1604 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1605   if (!VerboseAsm) return;
1606   O.PadToColumn(MAI->getCommentColumn());
1607   O << MAI->getCommentString() << " implicit-def: "
1608     << TRI->getAsmName(MI->getOperand(0).getReg());
1609 }
1610
1611 /// printLabel - This method prints a local label used by debug and
1612 /// exception handling tables.
1613 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1614   printLabel(MI->getOperand(0).getImm());
1615 }
1616
1617 void AsmPrinter::printLabel(unsigned Id) const {
1618   O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
1619 }
1620
1621 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1622 /// instruction, using the specified assembler variant.  Targets should
1623 /// overried this to format as appropriate.
1624 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1625                                  unsigned AsmVariant, const char *ExtraCode) {
1626   // Target doesn't support this yet!
1627   return true;
1628 }
1629
1630 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1631                                        unsigned AsmVariant,
1632                                        const char *ExtraCode) {
1633   // Target doesn't support this yet!
1634   return true;
1635 }
1636
1637 /// printBasicBlockLabel - This method prints the label for the specified
1638 /// MachineBasicBlock
1639 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
1640                                       bool printAlign, 
1641                                       bool printColon,
1642                                       bool printComment) const {
1643   if (printAlign) {
1644     unsigned Align = MBB->getAlignment();
1645     if (Align)
1646       EmitAlignment(Log2_32(Align));
1647   }
1648
1649   O << MAI->getPrivateGlobalPrefix() << "BB" << getFunctionNumber() << '_'
1650     << MBB->getNumber();
1651   if (printColon)
1652     O << ':';
1653   if (printComment) {
1654     if (const BasicBlock *BB = MBB->getBasicBlock())
1655       if (BB->hasName()) {
1656         O.PadToColumn(MAI->getCommentColumn());
1657         O << MAI->getCommentString() << ' ';
1658         WriteAsOperand(O, BB, /*PrintType=*/false);
1659       }
1660
1661     if (printColon)
1662       EmitComments(*MBB);
1663   }
1664 }
1665
1666 /// printPICJumpTableSetLabel - This method prints a set label for the
1667 /// specified MachineBasicBlock for a jumptable entry.
1668 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, 
1669                                            const MachineBasicBlock *MBB) const {
1670   if (!MAI->getSetDirective())
1671     return;
1672   
1673   O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1674     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1675   printBasicBlockLabel(MBB, false, false, false);
1676   O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 
1677     << '_' << uid << '\n';
1678 }
1679
1680 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1681                                            const MachineBasicBlock *MBB) const {
1682   if (!MAI->getSetDirective())
1683     return;
1684   
1685   O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
1686     << getFunctionNumber() << '_' << uid << '_' << uid2
1687     << "_set_" << MBB->getNumber() << ',';
1688   printBasicBlockLabel(MBB, false, false, false);
1689   O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 
1690     << '_' << uid << '_' << uid2 << '\n';
1691 }
1692
1693 /// printDataDirective - This method prints the asm directive for the
1694 /// specified type.
1695 void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1696   const TargetData *TD = TM.getTargetData();
1697   switch (type->getTypeID()) {
1698   case Type::FloatTyID: case Type::DoubleTyID:
1699   case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1700     assert(0 && "Should have already output floating point constant.");
1701   default:
1702     assert(0 && "Can't handle printing this type of thing");
1703   case Type::IntegerTyID: {
1704     unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1705     if (BitWidth <= 8)
1706       O << MAI->getData8bitsDirective(AddrSpace);
1707     else if (BitWidth <= 16)
1708       O << MAI->getData16bitsDirective(AddrSpace);
1709     else if (BitWidth <= 32)
1710       O << MAI->getData32bitsDirective(AddrSpace);
1711     else if (BitWidth <= 64) {
1712       assert(MAI->getData64bitsDirective(AddrSpace) &&
1713              "Target cannot handle 64-bit constant exprs!");
1714       O << MAI->getData64bitsDirective(AddrSpace);
1715     } else {
1716       llvm_unreachable("Target cannot handle given data directive width!");
1717     }
1718     break;
1719   }
1720   case Type::PointerTyID:
1721     if (TD->getPointerSize() == 8) {
1722       assert(MAI->getData64bitsDirective(AddrSpace) &&
1723              "Target cannot handle 64-bit pointer exprs!");
1724       O << MAI->getData64bitsDirective(AddrSpace);
1725     } else if (TD->getPointerSize() == 2) {
1726       O << MAI->getData16bitsDirective(AddrSpace);
1727     } else if (TD->getPointerSize() == 1) {
1728       O << MAI->getData8bitsDirective(AddrSpace);
1729     } else {
1730       O << MAI->getData32bitsDirective(AddrSpace);
1731     }
1732     break;
1733   }
1734 }
1735
1736 void AsmPrinter::printVisibility(const std::string& Name,
1737                                  unsigned Visibility) const {
1738   if (Visibility == GlobalValue::HiddenVisibility) {
1739     if (const char *Directive = MAI->getHiddenDirective())
1740       O << Directive << Name << '\n';
1741   } else if (Visibility == GlobalValue::ProtectedVisibility) {
1742     if (const char *Directive = MAI->getProtectedDirective())
1743       O << Directive << Name << '\n';
1744   }
1745 }
1746
1747 void AsmPrinter::printOffset(int64_t Offset) const {
1748   if (Offset > 0)
1749     O << '+' << Offset;
1750   else if (Offset < 0)
1751     O << Offset;
1752 }
1753
1754 void AsmPrinter::printMCInst(const MCInst *MI) {
1755   llvm_unreachable("MCInst printing unavailable on this target!");
1756 }
1757
1758 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1759   if (!S->usesMetadata())
1760     return 0;
1761   
1762   gcp_iterator GCPI = GCMetadataPrinters.find(S);
1763   if (GCPI != GCMetadataPrinters.end())
1764     return GCPI->second;
1765   
1766   const char *Name = S->getName().c_str();
1767   
1768   for (GCMetadataPrinterRegistry::iterator
1769          I = GCMetadataPrinterRegistry::begin(),
1770          E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1771     if (strcmp(Name, I->getName()) == 0) {
1772       GCMetadataPrinter *GMP = I->instantiate();
1773       GMP->S = S;
1774       GCMetadataPrinters.insert(std::make_pair(S, GMP));
1775       return GMP;
1776     }
1777   
1778   errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n";
1779   llvm_unreachable(0);
1780 }
1781
1782 /// EmitComments - Pretty-print comments for instructions
1783 void AsmPrinter::EmitComments(const MachineInstr &MI) const {
1784   assert(VerboseAsm && !MI.getDebugLoc().isUnknown());
1785   
1786   DebugLocTuple DLT = MF->getDebugLocTuple(MI.getDebugLoc());
1787
1788   // Print source line info.
1789   O.PadToColumn(MAI->getCommentColumn());
1790   O << MAI->getCommentString() << " SrcLine ";
1791   if (DLT.CompileUnit) {
1792     std::string Str;
1793     DICompileUnit CU(DLT.CompileUnit);
1794     O << CU.getFilename(Str) << " ";
1795   }
1796   O << DLT.Line;
1797   if (DLT.Col != 0) 
1798     O << ":" << DLT.Col;
1799 }
1800
1801 /// PrintChildLoopComment - Print comments about child loops within
1802 /// the loop for this basic block, with nesting.
1803 ///
1804 static void PrintChildLoopComment(formatted_raw_ostream &O,
1805                                   const MachineLoop *loop,
1806                                   const MCAsmInfo *MAI,
1807                                   int FunctionNumber) {
1808   // Add child loop information
1809   for(MachineLoop::iterator cl = loop->begin(),
1810         clend = loop->end();
1811       cl != clend;
1812       ++cl) {
1813     MachineBasicBlock *Header = (*cl)->getHeader();
1814     assert(Header && "No header for loop");
1815
1816     O << '\n';
1817     O.PadToColumn(MAI->getCommentColumn());
1818
1819     O << MAI->getCommentString();
1820     O.indent(((*cl)->getLoopDepth()-1)*2)
1821       << " Child Loop BB" << FunctionNumber << "_"
1822       << Header->getNumber() << " Depth " << (*cl)->getLoopDepth();
1823
1824     PrintChildLoopComment(O, *cl, MAI, FunctionNumber);
1825   }
1826 }
1827
1828 /// EmitComments - Pretty-print comments for basic blocks
1829 void AsmPrinter::EmitComments(const MachineBasicBlock &MBB) const
1830 {
1831   if (VerboseAsm) {
1832     // Add loop depth information
1833     const MachineLoop *loop = LI->getLoopFor(&MBB);
1834
1835     if (loop) {
1836       // Print a newline after bb# annotation.
1837       O << "\n";
1838       O.PadToColumn(MAI->getCommentColumn());
1839       O << MAI->getCommentString() << " Loop Depth " << loop->getLoopDepth()
1840         << '\n';
1841
1842       O.PadToColumn(MAI->getCommentColumn());
1843
1844       MachineBasicBlock *Header = loop->getHeader();
1845       assert(Header && "No header for loop");
1846       
1847       if (Header == &MBB) {
1848         O << MAI->getCommentString() << " Loop Header";
1849         PrintChildLoopComment(O, loop, MAI, getFunctionNumber());
1850       }
1851       else {
1852         O << MAI->getCommentString() << " Loop Header is BB"
1853           << getFunctionNumber() << "_" << loop->getHeader()->getNumber();
1854       }
1855
1856       if (loop->empty()) {
1857         O << '\n';
1858         O.PadToColumn(MAI->getCommentColumn());
1859         O << MAI->getCommentString() << " Inner Loop";
1860       }
1861
1862       // Add parent loop information
1863       for (const MachineLoop *CurLoop = loop->getParentLoop();
1864            CurLoop;
1865            CurLoop = CurLoop->getParentLoop()) {
1866         MachineBasicBlock *Header = CurLoop->getHeader();
1867         assert(Header && "No header for loop");
1868
1869         O << '\n';
1870         O.PadToColumn(MAI->getCommentColumn());
1871         O << MAI->getCommentString();
1872         O.indent((CurLoop->getLoopDepth()-1)*2)
1873           << " Inside Loop BB" << getFunctionNumber() << "_"
1874           << Header->getNumber() << " Depth " << CurLoop->getLoopDepth();
1875       }
1876     }
1877   }
1878 }