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