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