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