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