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