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