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