6967cdf2216786f55c727c0e920f92d03c6cb4ae
[oota-llvm.git] / lib / VMCore / AsmWriter.cpp
1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
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 library implements the functionality defined in llvm/Assembly/Writer.h
11 //
12 // Note that these routines must be extremely tolerant of various errors in the
13 // LLVM code, because it can be used for debugging transformations.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/Assembly/AsmAnnotationWriter.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/InlineAsm.h"
24 #include "llvm/Instruction.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Module.h"
27 #include "llvm/ValueSymbolTable.h"
28 #include "llvm/TypeSymbolTable.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <algorithm>
36 #include <cctype>
37 using namespace llvm;
38
39 // Make virtual table appear in this compilation unit.
40 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
41
42 //===----------------------------------------------------------------------===//
43 // Helper Functions
44 //===----------------------------------------------------------------------===//
45
46 static const Module *getModuleFromVal(const Value *V) {
47   if (const Argument *MA = dyn_cast<Argument>(V))
48     return MA->getParent() ? MA->getParent()->getParent() : 0;
49   
50   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
51     return BB->getParent() ? BB->getParent()->getParent() : 0;
52   
53   if (const Instruction *I = dyn_cast<Instruction>(V)) {
54     const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
55     return M ? M->getParent() : 0;
56   }
57   
58   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
59     return GV->getParent();
60   return 0;
61 }
62
63 // PrintEscapedString - Print each character of the specified string, escaping
64 // it if it is not printable or if it is an escape char.
65 static void PrintEscapedString(const char *Str, unsigned Length,
66                                raw_ostream &Out) {
67   for (unsigned i = 0; i != Length; ++i) {
68     unsigned char C = Str[i];
69     if (isprint(C) && C != '\\' && C != '"' && isprint(C))
70       Out << C;
71     else
72       Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
73   }
74 }
75
76 // PrintEscapedString - Print each character of the specified string, escaping
77 // it if it is not printable or if it is an escape char.
78 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
79   PrintEscapedString(Str.c_str(), Str.size(), Out);
80 }
81
82 enum PrefixType {
83   GlobalPrefix,
84   LabelPrefix,
85   LocalPrefix,
86   NoPrefix
87 };
88
89 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
90 /// prefixed with % (if the string only contains simple characters) or is
91 /// surrounded with ""'s (if it has special chars in it).  Print it out.
92 static void PrintLLVMName(raw_ostream &OS, const char *NameStr,
93                           unsigned NameLen, PrefixType Prefix) {
94   assert(NameStr && "Cannot get empty name!");
95   switch (Prefix) {
96   default: assert(0 && "Bad prefix!");
97   case NoPrefix: break;
98   case GlobalPrefix: OS << '@'; break;
99   case LabelPrefix:  break;
100   case LocalPrefix:  OS << '%'; break;
101   }      
102   
103   // Scan the name to see if it needs quotes first.
104   bool NeedsQuotes = isdigit(NameStr[0]);
105   if (!NeedsQuotes) {
106     for (unsigned i = 0; i != NameLen; ++i) {
107       char C = NameStr[i];
108       if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
109         NeedsQuotes = true;
110         break;
111       }
112     }
113   }
114   
115   // If we didn't need any quotes, just write out the name in one blast.
116   if (!NeedsQuotes) {
117     OS.write(NameStr, NameLen);
118     return;
119   }
120   
121   // Okay, we need quotes.  Output the quotes and escape any scary characters as
122   // needed.
123   OS << '"';
124   PrintEscapedString(NameStr, NameLen, OS);
125   OS << '"';
126 }
127
128 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
129 /// prefixed with % (if the string only contains simple characters) or is
130 /// surrounded with ""'s (if it has special chars in it).  Print it out.
131 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
132   PrintLLVMName(OS, V->getNameStart(), V->getNameLen(),
133                 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
134 }
135
136 //===----------------------------------------------------------------------===//
137 // TypePrinting Class: Type printing machinery
138 //===----------------------------------------------------------------------===//
139
140 namespace {
141   /// TypePrinting - Type printing machinery.
142   class TypePrinting {
143     std::map<const Type *, std::string> TypeNames;
144     raw_ostream &OS;
145   public:
146     TypePrinting(const Module *M, raw_ostream &os);
147     
148     void print(const Type *Ty);
149     void printAtLeastOneLevel(const Type *Ty);
150   };
151 } // end anonymous namespace.
152
153 TypePrinting::TypePrinting(const Module *M, raw_ostream &os) : OS(os) {
154   if (M == 0) return;
155   
156   // If the module has a symbol table, take all global types and stuff their
157   // names into the TypeNames map.
158   const TypeSymbolTable &ST = M->getTypeSymbolTable();
159   for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
160        TI != E; ++TI) {
161     const Type *Ty = cast<Type>(TI->second);
162     
163     // As a heuristic, don't insert pointer to primitive types, because
164     // they are used too often to have a single useful name.
165     if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
166       const Type *PETy = PTy->getElementType();
167       if ((PETy->isPrimitiveType() || PETy->isInteger()) &&
168           !isa<OpaqueType>(PETy))
169         continue;
170     }
171     
172     std::string NameStr;
173     raw_string_ostream NameOS(NameStr);
174     PrintLLVMName(NameOS, TI->first.c_str(), TI->first.length(), LocalPrefix);
175     TypeNames.insert(std::make_pair(Ty, NameOS.str()));
176   }
177 }
178
179 static void calcTypeName(const Type *Ty,
180                          std::vector<const Type *> &TypeStack,
181                          std::map<const Type *, std::string> &TypeNames,
182                          std::string &Result) {
183   if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
184     Result += Ty->getDescription();  // Base case
185     return;
186   }
187   
188   // Check to see if the type is named.
189   std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
190   if (I != TypeNames.end()) {
191     Result += I->second;
192     return;
193   }
194   
195   if (isa<OpaqueType>(Ty)) {
196     Result += "opaque";
197     return;
198   }
199   
200   // Check to see if the Type is already on the stack...
201   unsigned Slot = 0, CurSize = TypeStack.size();
202   while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
203   
204   // This is another base case for the recursion.  In this case, we know
205   // that we have looped back to a type that we have previously visited.
206   // Generate the appropriate upreference to handle this.
207   if (Slot < CurSize) {
208     Result += "\\" + utostr(CurSize-Slot);     // Here's the upreference
209     return;
210   }
211   
212   TypeStack.push_back(Ty);    // Recursive case: Add us to the stack..
213   
214   switch (Ty->getTypeID()) {
215     case Type::IntegerTyID: {
216       unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
217       Result += "i" + utostr(BitWidth);
218       break;
219     }
220     case Type::FunctionTyID: {
221       const FunctionType *FTy = cast<FunctionType>(Ty);
222       calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
223       Result += " (";
224       for (FunctionType::param_iterator I = FTy->param_begin(),
225            E = FTy->param_end(); I != E; ++I) {
226         if (I != FTy->param_begin())
227           Result += ", ";
228         calcTypeName(*I, TypeStack, TypeNames, Result);
229       }
230       if (FTy->isVarArg()) {
231         if (FTy->getNumParams()) Result += ", ";
232         Result += "...";
233       }
234       Result += ")";
235       break;
236     }
237     case Type::StructTyID: {
238       const StructType *STy = cast<StructType>(Ty);
239       if (STy->isPacked())
240         Result += '<';
241       Result += "{ ";
242       for (StructType::element_iterator I = STy->element_begin(),
243            E = STy->element_end(); I != E; ++I) {
244         calcTypeName(*I, TypeStack, TypeNames, Result);
245         if (next(I) != STy->element_end())
246           Result += ',';
247         Result += ' ';
248       }
249       Result += '}';
250       if (STy->isPacked())
251         Result += '>';
252       break;
253     }
254     case Type::PointerTyID: {
255       const PointerType *PTy = cast<PointerType>(Ty);
256       calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
257       if (unsigned AddressSpace = PTy->getAddressSpace())
258         Result += " addrspace(" + utostr(AddressSpace) + ")";
259       Result += "*";
260       break;
261     }
262     case Type::ArrayTyID: {
263       const ArrayType *ATy = cast<ArrayType>(Ty);
264       Result += "[" + utostr(ATy->getNumElements()) + " x ";
265       calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
266       Result += "]";
267       break;
268     }
269     case Type::VectorTyID: {
270       const VectorType *PTy = cast<VectorType>(Ty);
271       Result += "<" + utostr(PTy->getNumElements()) + " x ";
272       calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
273       Result += ">";
274       break;
275     }
276     case Type::OpaqueTyID:
277       Result += "opaque";
278       break;
279     default:
280       Result += "<unrecognized-type>";
281       break;
282   }
283   
284   TypeStack.pop_back();       // Remove self from stack...
285 }
286
287 /// printTypeInt - The internal guts of printing out a type that has a
288 /// potentially named portion.
289 ///
290 void TypePrinting::print(const Type *Ty) {
291   // Primitive types always print out their description, regardless of whether
292   // they have been named or not.
293   if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
294     OS << Ty->getDescription();
295     return;
296   }
297   
298   // Check to see if the type is named.
299   std::map<const Type*, std::string>::iterator I = TypeNames.find(Ty);
300   if (I != TypeNames.end()) {
301     OS << I->second;
302     return;
303   }
304   
305   // Otherwise we have a type that has not been named but is a derived type.
306   // Carefully recurse the type hierarchy to print out any contained symbolic
307   // names.
308   std::vector<const Type *> TypeStack;
309   std::string TypeName;
310   calcTypeName(Ty, TypeStack, TypeNames, TypeName);
311   TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
312   OS << TypeName;
313 }
314
315 /// printAtLeastOneLevel - Print out one level of the possibly complex type
316 /// without considering any symbolic types that we may have equal to it.
317 void TypePrinting::printAtLeastOneLevel(const Type *Ty) {
318   // FIXME: Just call calcTypeName!
319   if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
320     print(FTy->getReturnType());
321     OS << " (";
322     for (FunctionType::param_iterator I = FTy->param_begin(),
323          E = FTy->param_end(); I != E; ++I) {
324       if (I != FTy->param_begin())
325         OS << ", ";
326       print(*I);
327     }
328     if (FTy->isVarArg()) {
329       if (FTy->getNumParams()) OS << ", ";
330       OS << "...";
331     }
332     OS << ')';
333     return;
334   }
335   
336   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
337     if (STy->isPacked())
338       OS << '<';
339     OS << "{ ";
340     for (StructType::element_iterator I = STy->element_begin(),
341          E = STy->element_end(); I != E; ++I) {
342       if (I != STy->element_begin())
343         OS << ", ";
344       print(*I);
345     }
346     OS << " }";
347     if (STy->isPacked())
348       OS << '>';
349     return;
350   }
351   
352   if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
353     print(PTy->getElementType());
354     if (unsigned AddressSpace = PTy->getAddressSpace())
355       OS << " addrspace(" << AddressSpace << ")";
356     OS << '*';
357     return;
358   } 
359   
360   if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
361     OS << '[' << ATy->getNumElements() << " x ";
362     print(ATy->getElementType());
363     OS << ']';
364     return;
365   }
366   
367   if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
368     OS << '<' << PTy->getNumElements() << " x ";
369     print(PTy->getElementType());
370     OS << '>';
371     return;
372   }
373   
374   if (isa<OpaqueType>(Ty)) {
375     OS << "opaque";
376     return;
377   }
378   
379   if (!Ty->isPrimitiveType() && !isa<IntegerType>(Ty))
380     OS << "<unknown derived type>";
381   print(Ty);
382 }
383
384
385
386
387 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
388 /// type, iff there is an entry in the modules symbol table for the specified
389 /// type or one of it's component types. This is slower than a simple x << Type
390 ///
391 void llvm::WriteTypeSymbolic(raw_ostream &Out, const Type *Ty, const Module *M){
392   // FIXME: Remove this space.
393   Out << ' ';
394   
395   // If they want us to print out a type, but there is no context, we can't
396   // print it symbolically.
397   if (!M) {
398     Out << Ty->getDescription();
399   } else {
400     TypePrinting(M, Out).print(Ty);
401   }
402 }
403
404 // std::ostream adaptor.
405 void llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
406                              const Module *M) {
407   raw_os_ostream RO(Out);
408   WriteTypeSymbolic(RO, Ty, M);
409 }
410
411
412 //===----------------------------------------------------------------------===//
413 // SlotTracker Class: Enumerate slot numbers for unnamed values
414 //===----------------------------------------------------------------------===//
415
416 namespace {
417
418 /// This class provides computation of slot numbers for LLVM Assembly writing.
419 ///
420 class SlotTracker {
421 public:
422   /// ValueMap - A mapping of Values to slot numbers
423   typedef DenseMap<const Value*, unsigned> ValueMap;
424   
425 private:  
426   /// TheModule - The module for which we are holding slot numbers
427   const Module* TheModule;
428   
429   /// TheFunction - The function for which we are holding slot numbers
430   const Function* TheFunction;
431   bool FunctionProcessed;
432   
433   /// mMap - The TypePlanes map for the module level data
434   ValueMap mMap;
435   unsigned mNext;
436   
437   /// fMap - The TypePlanes map for the function level data
438   ValueMap fMap;
439   unsigned fNext;
440   
441 public:
442   /// Construct from a module
443   explicit SlotTracker(const Module *M);
444   /// Construct from a function, starting out in incorp state.
445   explicit SlotTracker(const Function *F);
446
447   /// Return the slot number of the specified value in it's type
448   /// plane.  If something is not in the SlotTracker, return -1.
449   int getLocalSlot(const Value *V);
450   int getGlobalSlot(const GlobalValue *V);
451
452   /// If you'd like to deal with a function instead of just a module, use
453   /// this method to get its data into the SlotTracker.
454   void incorporateFunction(const Function *F) {
455     TheFunction = F;
456     FunctionProcessed = false;
457   }
458
459   /// After calling incorporateFunction, use this method to remove the
460   /// most recently incorporated function from the SlotTracker. This
461   /// will reset the state of the machine back to just the module contents.
462   void purgeFunction();
463
464   // Implementation Details
465 private:
466   /// This function does the actual initialization.
467   inline void initialize();
468
469   /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
470   void CreateModuleSlot(const GlobalValue *V);
471   
472   /// CreateFunctionSlot - Insert the specified Value* into the slot table.
473   void CreateFunctionSlot(const Value *V);
474
475   /// Add all of the module level global variables (and their initializers)
476   /// and function declarations, but not the contents of those functions.
477   void processModule();
478
479   /// Add all of the functions arguments, basic blocks, and instructions
480   void processFunction();
481
482   SlotTracker(const SlotTracker &);  // DO NOT IMPLEMENT
483   void operator=(const SlotTracker &);  // DO NOT IMPLEMENT
484 };
485
486 }  // end anonymous namespace
487
488
489 static SlotTracker *createSlotTracker(const Value *V) {
490   if (const Argument *FA = dyn_cast<Argument>(V))
491     return new SlotTracker(FA->getParent());
492   
493   if (const Instruction *I = dyn_cast<Instruction>(V))
494     return new SlotTracker(I->getParent()->getParent());
495   
496   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
497     return new SlotTracker(BB->getParent());
498   
499   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
500     return new SlotTracker(GV->getParent());
501   
502   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
503     return new SlotTracker(GA->getParent());    
504   
505   if (const Function *Func = dyn_cast<Function>(V))
506     return new SlotTracker(Func);
507   
508   return 0;
509 }
510
511 #if 0
512 #define ST_DEBUG(X) cerr << X
513 #else
514 #define ST_DEBUG(X)
515 #endif
516
517 // Module level constructor. Causes the contents of the Module (sans functions)
518 // to be added to the slot table.
519 SlotTracker::SlotTracker(const Module *M)
520   : TheModule(M), TheFunction(0), FunctionProcessed(false), mNext(0), fNext(0) {
521 }
522
523 // Function level constructor. Causes the contents of the Module and the one
524 // function provided to be added to the slot table.
525 SlotTracker::SlotTracker(const Function *F)
526   : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
527     mNext(0), fNext(0) {
528 }
529
530 inline void SlotTracker::initialize() {
531   if (TheModule) {
532     processModule();
533     TheModule = 0; ///< Prevent re-processing next time we're called.
534   }
535   
536   if (TheFunction && !FunctionProcessed)
537     processFunction();
538 }
539
540 // Iterate through all the global variables, functions, and global
541 // variable initializers and create slots for them.
542 void SlotTracker::processModule() {
543   ST_DEBUG("begin processModule!\n");
544   
545   // Add all of the unnamed global variables to the value table.
546   for (Module::const_global_iterator I = TheModule->global_begin(),
547        E = TheModule->global_end(); I != E; ++I)
548     if (!I->hasName()) 
549       CreateModuleSlot(I);
550   
551   // Add all the unnamed functions to the table.
552   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
553        I != E; ++I)
554     if (!I->hasName())
555       CreateModuleSlot(I);
556   
557   ST_DEBUG("end processModule!\n");
558 }
559
560
561 // Process the arguments, basic blocks, and instructions  of a function.
562 void SlotTracker::processFunction() {
563   ST_DEBUG("begin processFunction!\n");
564   fNext = 0;
565   
566   // Add all the function arguments with no names.
567   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
568       AE = TheFunction->arg_end(); AI != AE; ++AI)
569     if (!AI->hasName())
570       CreateFunctionSlot(AI);
571   
572   ST_DEBUG("Inserting Instructions:\n");
573   
574   // Add all of the basic blocks and instructions with no names.
575   for (Function::const_iterator BB = TheFunction->begin(),
576        E = TheFunction->end(); BB != E; ++BB) {
577     if (!BB->hasName())
578       CreateFunctionSlot(BB);
579     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
580       if (I->getType() != Type::VoidTy && !I->hasName())
581         CreateFunctionSlot(I);
582   }
583   
584   FunctionProcessed = true;
585   
586   ST_DEBUG("end processFunction!\n");
587 }
588
589 /// Clean up after incorporating a function. This is the only way to get out of
590 /// the function incorporation state that affects get*Slot/Create*Slot. Function
591 /// incorporation state is indicated by TheFunction != 0.
592 void SlotTracker::purgeFunction() {
593   ST_DEBUG("begin purgeFunction!\n");
594   fMap.clear(); // Simply discard the function level map
595   TheFunction = 0;
596   FunctionProcessed = false;
597   ST_DEBUG("end purgeFunction!\n");
598 }
599
600 /// getGlobalSlot - Get the slot number of a global value.
601 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
602   // Check for uninitialized state and do lazy initialization.
603   initialize();
604   
605   // Find the type plane in the module map
606   ValueMap::iterator MI = mMap.find(V);
607   return MI == mMap.end() ? -1 : (int)MI->second;
608 }
609
610
611 /// getLocalSlot - Get the slot number for a value that is local to a function.
612 int SlotTracker::getLocalSlot(const Value *V) {
613   assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
614   
615   // Check for uninitialized state and do lazy initialization.
616   initialize();
617   
618   ValueMap::iterator FI = fMap.find(V);
619   return FI == fMap.end() ? -1 : (int)FI->second;
620 }
621
622
623 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
624 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
625   assert(V && "Can't insert a null Value into SlotTracker!");
626   assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
627   assert(!V->hasName() && "Doesn't need a slot!");
628   
629   unsigned DestSlot = mNext++;
630   mMap[V] = DestSlot;
631   
632   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
633            DestSlot << " [");
634   // G = Global, F = Function, A = Alias, o = other
635   ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
636             (isa<Function>(V) ? 'F' :
637              (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
638 }
639
640
641 /// CreateSlot - Create a new slot for the specified value if it has no name.
642 void SlotTracker::CreateFunctionSlot(const Value *V) {
643   assert(V->getType() != Type::VoidTy && !V->hasName() &&
644          "Doesn't need a slot!");
645   
646   unsigned DestSlot = fNext++;
647   fMap[V] = DestSlot;
648   
649   // G = Global, F = Function, o = other
650   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
651            DestSlot << " [o]\n");
652 }  
653
654
655
656 //===----------------------------------------------------------------------===//
657 // AsmWriter Implementation
658 //===----------------------------------------------------------------------===//
659
660 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
661                                    TypePrinting &TypePrinter,
662                                    SlotTracker *Machine);
663
664
665
666 static const char *getPredicateText(unsigned predicate) {
667   const char * pred = "unknown";
668   switch (predicate) {
669     case FCmpInst::FCMP_FALSE: pred = "false"; break;
670     case FCmpInst::FCMP_OEQ:   pred = "oeq"; break;
671     case FCmpInst::FCMP_OGT:   pred = "ogt"; break;
672     case FCmpInst::FCMP_OGE:   pred = "oge"; break;
673     case FCmpInst::FCMP_OLT:   pred = "olt"; break;
674     case FCmpInst::FCMP_OLE:   pred = "ole"; break;
675     case FCmpInst::FCMP_ONE:   pred = "one"; break;
676     case FCmpInst::FCMP_ORD:   pred = "ord"; break;
677     case FCmpInst::FCMP_UNO:   pred = "uno"; break;
678     case FCmpInst::FCMP_UEQ:   pred = "ueq"; break;
679     case FCmpInst::FCMP_UGT:   pred = "ugt"; break;
680     case FCmpInst::FCMP_UGE:   pred = "uge"; break;
681     case FCmpInst::FCMP_ULT:   pred = "ult"; break;
682     case FCmpInst::FCMP_ULE:   pred = "ule"; break;
683     case FCmpInst::FCMP_UNE:   pred = "une"; break;
684     case FCmpInst::FCMP_TRUE:  pred = "true"; break;
685     case ICmpInst::ICMP_EQ:    pred = "eq"; break;
686     case ICmpInst::ICMP_NE:    pred = "ne"; break;
687     case ICmpInst::ICMP_SGT:   pred = "sgt"; break;
688     case ICmpInst::ICMP_SGE:   pred = "sge"; break;
689     case ICmpInst::ICMP_SLT:   pred = "slt"; break;
690     case ICmpInst::ICMP_SLE:   pred = "sle"; break;
691     case ICmpInst::ICMP_UGT:   pred = "ugt"; break;
692     case ICmpInst::ICMP_UGE:   pred = "uge"; break;
693     case ICmpInst::ICMP_ULT:   pred = "ult"; break;
694     case ICmpInst::ICMP_ULE:   pred = "ule"; break;
695   }
696   return pred;
697 }
698
699 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
700                              TypePrinting &TypePrinter, SlotTracker *Machine) {
701   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
702     if (CI->getType() == Type::Int1Ty) {
703       Out << (CI->getZExtValue() ? "true" : "false");
704       return;
705     }
706     Out << CI->getValue();
707     return;
708   }
709   
710   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
711     if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
712         &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
713       // We would like to output the FP constant value in exponential notation,
714       // but we cannot do this if doing so will lose precision.  Check here to
715       // make sure that we only output it in exponential format if we can parse
716       // the value back and get the same value.
717       //
718       bool ignored;
719       bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
720       double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
721                               CFP->getValueAPF().convertToFloat();
722       std::string StrVal = ftostr(CFP->getValueAPF());
723
724       // Check to make sure that the stringized number is not some string like
725       // "Inf" or NaN, that atof will accept, but the lexer will not.  Check
726       // that the string matches the "[-+]?[0-9]" regex.
727       //
728       if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
729           ((StrVal[0] == '-' || StrVal[0] == '+') &&
730            (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
731         // Reparse stringized version!
732         if (atof(StrVal.c_str()) == Val) {
733           Out << StrVal;
734           return;
735         }
736       }
737       // Otherwise we could not reparse it to exactly the same value, so we must
738       // output the string in hexadecimal format!  Note that loading and storing
739       // floating point types changes the bits of NaNs on some hosts, notably
740       // x86, so we must not use these types.
741       assert(sizeof(double) == sizeof(uint64_t) &&
742              "assuming that double is 64 bits!");
743       char Buffer[40];
744       APFloat apf = CFP->getValueAPF();
745       // Floats are represented in ASCII IR as double, convert.
746       if (!isDouble)
747         apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, 
748                           &ignored);
749       Out << "0x" << 
750               utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()), 
751                             Buffer+40);
752       return;
753     }
754     
755     // Some form of long double.  These appear as a magic letter identifying
756     // the type, then a fixed number of hex digits.
757     Out << "0x";
758     if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended)
759       Out << 'K';
760     else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
761       Out << 'L';
762     else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
763       Out << 'M';
764     else
765       assert(0 && "Unsupported floating point type");
766     // api needed to prevent premature destruction
767     APInt api = CFP->getValueAPF().bitcastToAPInt();
768     const uint64_t* p = api.getRawData();
769     uint64_t word = *p;
770     int shiftcount=60;
771     int width = api.getBitWidth();
772     for (int j=0; j<width; j+=4, shiftcount-=4) {
773       unsigned int nibble = (word>>shiftcount) & 15;
774       if (nibble < 10)
775         Out << (unsigned char)(nibble + '0');
776       else
777         Out << (unsigned char)(nibble - 10 + 'A');
778       if (shiftcount == 0 && j+4 < width) {
779         word = *(++p);
780         shiftcount = 64;
781         if (width-j-4 < 64)
782           shiftcount = width-j-4;
783       }
784     }
785     return;
786   }
787   
788   if (isa<ConstantAggregateZero>(CV)) {
789     Out << "zeroinitializer";
790     return;
791   }
792   
793   if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
794     // As a special case, print the array as a string if it is an array of
795     // i8 with ConstantInt values.
796     //
797     const Type *ETy = CA->getType()->getElementType();
798     if (CA->isString()) {
799       Out << "c\"";
800       PrintEscapedString(CA->getAsString(), Out);
801       Out << '"';
802     } else {                // Cannot output in string format...
803       Out << '[';
804       if (CA->getNumOperands()) {
805         TypePrinter.print(ETy);
806         Out << ' ';
807         WriteAsOperandInternal(Out, CA->getOperand(0),
808                                TypePrinter, Machine);
809         for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
810           Out << ", ";
811           TypePrinter.print(ETy);
812           Out << ' ';
813           WriteAsOperandInternal(Out, CA->getOperand(i), TypePrinter, Machine);
814         }
815       }
816       Out << ']';
817     }
818     return;
819   }
820   
821   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
822     if (CS->getType()->isPacked())
823       Out << '<';
824     Out << '{';
825     unsigned N = CS->getNumOperands();
826     if (N) {
827       Out << ' ';
828       TypePrinter.print(CS->getOperand(0)->getType());
829       Out << ' ';
830
831       WriteAsOperandInternal(Out, CS->getOperand(0), TypePrinter, Machine);
832
833       for (unsigned i = 1; i < N; i++) {
834         Out << ", ";
835         TypePrinter.print(CS->getOperand(i)->getType());
836         Out << ' ';
837
838         WriteAsOperandInternal(Out, CS->getOperand(i), TypePrinter, Machine);
839       }
840       Out << ' ';
841     }
842  
843     Out << '}';
844     if (CS->getType()->isPacked())
845       Out << '>';
846     return;
847   }
848   
849   if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
850     const Type *ETy = CP->getType()->getElementType();
851     assert(CP->getNumOperands() > 0 &&
852            "Number of operands for a PackedConst must be > 0");
853     Out << '<';
854     TypePrinter.print(ETy);
855     Out << ' ';
856     WriteAsOperandInternal(Out, CP->getOperand(0), TypePrinter, Machine);
857     for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
858       Out << ", ";
859       TypePrinter.print(ETy);
860       Out << ' ';
861       WriteAsOperandInternal(Out, CP->getOperand(i), TypePrinter, Machine);
862     }
863     Out << '>';
864     return;
865   }
866   
867   if (isa<ConstantPointerNull>(CV)) {
868     Out << "null";
869     return;
870   }
871   
872   if (isa<UndefValue>(CV)) {
873     Out << "undef";
874     return;
875   }
876
877   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
878     Out << CE->getOpcodeName();
879     if (CE->isCompare())
880       Out << ' ' << getPredicateText(CE->getPredicate());
881     Out << " (";
882
883     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
884       TypePrinter.print((*OI)->getType());
885       Out << ' ';
886       WriteAsOperandInternal(Out, *OI, TypePrinter, Machine);
887       if (OI+1 != CE->op_end())
888         Out << ", ";
889     }
890
891     if (CE->hasIndices()) {
892       const SmallVector<unsigned, 4> &Indices = CE->getIndices();
893       for (unsigned i = 0, e = Indices.size(); i != e; ++i)
894         Out << ", " << Indices[i];
895     }
896
897     if (CE->isCast()) {
898       Out << " to ";
899       TypePrinter.print(CE->getType());
900     }
901
902     Out << ')';
903     return;
904   }
905   
906   Out << "<placeholder or erroneous Constant>";
907 }
908
909
910 /// WriteAsOperand - Write the name of the specified value out to the specified
911 /// ostream.  This can be useful when you just want to print int %reg126, not
912 /// the whole instruction that generated it.
913 ///
914 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
915                                    TypePrinting &TypePrinter,
916                                    SlotTracker *Machine) {
917   if (V->hasName()) {
918     PrintLLVMName(Out, V);
919     return;
920   }
921   
922   const Constant *CV = dyn_cast<Constant>(V);
923   if (CV && !isa<GlobalValue>(CV)) {
924     WriteConstantInt(Out, CV, TypePrinter, Machine);
925     return;
926   }
927   
928   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
929     Out << "asm ";
930     if (IA->hasSideEffects())
931       Out << "sideeffect ";
932     Out << '"';
933     PrintEscapedString(IA->getAsmString(), Out);
934     Out << "\", \"";
935     PrintEscapedString(IA->getConstraintString(), Out);
936     Out << '"';
937     return;
938   }
939   
940   char Prefix = '%';
941   int Slot;
942   if (Machine) {
943     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
944       Slot = Machine->getGlobalSlot(GV);
945       Prefix = '@';
946     } else {
947       Slot = Machine->getLocalSlot(V);
948     }
949   } else {
950     Machine = createSlotTracker(V);
951     if (Machine) {
952       if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
953         Slot = Machine->getGlobalSlot(GV);
954         Prefix = '@';
955       } else {
956         Slot = Machine->getLocalSlot(V);
957       }
958     } else {
959       Slot = -1;
960     }
961     delete Machine;
962   }
963   
964   if (Slot != -1)
965     Out << Prefix << Slot;
966   else
967     Out << "<badref>";
968 }
969
970 /// WriteAsOperand - Write the name of the specified value out to the specified
971 /// ostream.  This can be useful when you just want to print int %reg126, not
972 /// the whole instruction that generated it.
973 ///
974 void llvm::WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
975                           const Module *Context) {
976   raw_os_ostream OS(Out);
977   WriteAsOperand(OS, V, PrintType, Context);
978 }
979
980 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, bool PrintType,
981                           const Module *Context) {
982   if (Context == 0) Context = getModuleFromVal(V);
983
984   TypePrinting TypePrinter(Context, Out);
985   if (PrintType) {
986     TypePrinter.print(V->getType());
987     Out << ' ';
988   }
989
990   WriteAsOperandInternal(Out, V, TypePrinter, 0);
991 }
992
993
994 namespace {
995
996 class AssemblyWriter {
997   raw_ostream &Out;
998   SlotTracker &Machine;
999   const Module *TheModule;
1000   TypePrinting TypePrinter;
1001   AssemblyAnnotationWriter *AnnotationWriter;
1002 public:
1003   inline AssemblyWriter(raw_ostream &o, SlotTracker &Mac, const Module *M,
1004                         AssemblyAnnotationWriter *AAW)
1005     : Out(o), Machine(Mac), TheModule(M), TypePrinter(M, Out),
1006       AnnotationWriter(AAW) {
1007   }
1008
1009   void write(const Module *M) { printModule(M);       }
1010   
1011   void write(const GlobalValue *G) {
1012     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
1013       printGlobal(GV);
1014     else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
1015       printAlias(GA);
1016     else if (const Function *F = dyn_cast<Function>(G))
1017       printFunction(F);
1018     else
1019       assert(0 && "Unknown global");
1020   }
1021   
1022   void write(const BasicBlock *BB)    { printBasicBlock(BB);  }
1023   void write(const Instruction *I)    { printInstruction(*I); }
1024 //  void write(const Type *Ty)          { printType(Ty);        }
1025
1026   void writeOperand(const Value *Op, bool PrintType);
1027   void writeParamOperand(const Value *Operand, Attributes Attrs);
1028
1029   const Module* getModule() { return TheModule; }
1030
1031 private:
1032   void printModule(const Module *M);
1033   void printTypeSymbolTable(const TypeSymbolTable &ST);
1034   void printGlobal(const GlobalVariable *GV);
1035   void printAlias(const GlobalAlias *GV);
1036   void printFunction(const Function *F);
1037   void printArgument(const Argument *FA, Attributes Attrs);
1038   void printBasicBlock(const BasicBlock *BB);
1039   void printInstruction(const Instruction &I);
1040
1041   // printType - Go to extreme measures to attempt to print out a short,
1042   // symbolic version of a type name.
1043   //
1044   void printType(const Type *Ty) {
1045     TypePrinter.print(Ty);
1046   }
1047
1048   // printInfoComment - Print a little comment after the instruction indicating
1049   // which slot it occupies.
1050   void printInfoComment(const Value &V);
1051 };
1052 }  // end of llvm namespace
1053
1054
1055 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1056   if (Operand == 0) {
1057     Out << "<null operand!>";
1058   } else {
1059     if (PrintType) {
1060       printType(Operand->getType());
1061       Out << ' ';
1062     }
1063     WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1064   }
1065 }
1066
1067 void AssemblyWriter::writeParamOperand(const Value *Operand, 
1068                                        Attributes Attrs) {
1069   if (Operand == 0) {
1070     Out << "<null operand!>";
1071   } else {
1072     // Print the type
1073     printType(Operand->getType());
1074     // Print parameter attributes list
1075     if (Attrs != Attribute::None)
1076       Out << ' ' << Attribute::getAsString(Attrs);
1077     Out << ' ';
1078     // Print the operand
1079     WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1080   }
1081 }
1082
1083 void AssemblyWriter::printModule(const Module *M) {
1084   if (!M->getModuleIdentifier().empty() &&
1085       // Don't print the ID if it will start a new line (which would
1086       // require a comment char before it).
1087       M->getModuleIdentifier().find('\n') == std::string::npos)
1088     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1089
1090   if (!M->getDataLayout().empty())
1091     Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1092   if (!M->getTargetTriple().empty())
1093     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1094
1095   if (!M->getModuleInlineAsm().empty()) {
1096     // Split the string into lines, to make it easier to read the .ll file.
1097     std::string Asm = M->getModuleInlineAsm();
1098     size_t CurPos = 0;
1099     size_t NewLine = Asm.find_first_of('\n', CurPos);
1100     while (NewLine != std::string::npos) {
1101       // We found a newline, print the portion of the asm string from the
1102       // last newline up to this newline.
1103       Out << "module asm \"";
1104       PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1105                          Out);
1106       Out << "\"\n";
1107       CurPos = NewLine+1;
1108       NewLine = Asm.find_first_of('\n', CurPos);
1109     }
1110     Out << "module asm \"";
1111     PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1112     Out << "\"\n";
1113   }
1114   
1115   // Loop over the dependent libraries and emit them.
1116   Module::lib_iterator LI = M->lib_begin();
1117   Module::lib_iterator LE = M->lib_end();
1118   if (LI != LE) {
1119     Out << "deplibs = [ ";
1120     while (LI != LE) {
1121       Out << '"' << *LI << '"';
1122       ++LI;
1123       if (LI != LE)
1124         Out << ", ";
1125     }
1126     Out << " ]\n";
1127   }
1128
1129   // Loop over the symbol table, emitting all named constants.
1130   printTypeSymbolTable(M->getTypeSymbolTable());
1131
1132   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1133        I != E; ++I)
1134     printGlobal(I);
1135   
1136   // Output all aliases.
1137   if (!M->alias_empty()) Out << "\n";
1138   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1139        I != E; ++I)
1140     printAlias(I);
1141
1142   // Output all of the functions.
1143   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1144     printFunction(I);
1145 }
1146
1147 static void PrintLinkage(GlobalValue::LinkageTypes LT, raw_ostream &Out) {
1148   switch (LT) {
1149   case GlobalValue::PrivateLinkage:      Out << "private "; break;
1150   case GlobalValue::InternalLinkage:     Out << "internal "; break;
1151   case GlobalValue::LinkOnceLinkage:     Out << "linkonce "; break;
1152   case GlobalValue::WeakLinkage:         Out << "weak "; break;
1153   case GlobalValue::CommonLinkage:       Out << "common "; break;
1154   case GlobalValue::AppendingLinkage:    Out << "appending "; break;
1155   case GlobalValue::DLLImportLinkage:    Out << "dllimport "; break;
1156   case GlobalValue::DLLExportLinkage:    Out << "dllexport "; break;
1157   case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;      
1158   case GlobalValue::ExternalLinkage: break;
1159   case GlobalValue::GhostLinkage:
1160     Out << "GhostLinkage not allowed in AsmWriter!\n";
1161     abort();
1162   }
1163 }
1164       
1165
1166 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1167                             raw_ostream &Out) {
1168   switch (Vis) {
1169   default: assert(0 && "Invalid visibility style!");
1170   case GlobalValue::DefaultVisibility: break;
1171   case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
1172   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1173   }
1174 }
1175
1176 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1177   if (GV->hasName()) {
1178     PrintLLVMName(Out, GV);
1179     Out << " = ";
1180   }
1181
1182   if (!GV->hasInitializer() && GV->hasExternalLinkage())
1183     Out << "external ";
1184   
1185   PrintLinkage(GV->getLinkage(), Out);
1186   PrintVisibility(GV->getVisibility(), Out);
1187
1188   if (GV->isThreadLocal()) Out << "thread_local ";
1189   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1190     Out << "addrspace(" << AddressSpace << ") ";
1191   Out << (GV->isConstant() ? "constant " : "global ");
1192   printType(GV->getType()->getElementType());
1193
1194   if (GV->hasInitializer()) {
1195     Out << ' ';
1196     writeOperand(GV->getInitializer(), false);
1197   }
1198     
1199   if (GV->hasSection())
1200     Out << ", section \"" << GV->getSection() << '"';
1201   if (GV->getAlignment())
1202     Out << ", align " << GV->getAlignment();
1203
1204   printInfoComment(*GV);
1205   Out << '\n';
1206 }
1207
1208 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1209   // Don't crash when dumping partially built GA
1210   if (!GA->hasName())
1211     Out << "<<nameless>> = ";
1212   else {
1213     PrintLLVMName(Out, GA);
1214     Out << " = ";
1215   }
1216   PrintVisibility(GA->getVisibility(), Out);
1217
1218   Out << "alias ";
1219
1220   PrintLinkage(GA->getLinkage(), Out);
1221   
1222   const Constant *Aliasee = GA->getAliasee();
1223     
1224   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1225     printType(GV->getType());
1226     Out << ' ';
1227     PrintLLVMName(Out, GV);
1228   } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1229     printType(F->getFunctionType());
1230     Out << "* ";
1231
1232     WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1233   } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1234     printType(GA->getType());
1235     Out << " ";
1236     PrintLLVMName(Out, GA);
1237   } else {
1238     const ConstantExpr *CE = 0;
1239     if ((CE = dyn_cast<ConstantExpr>(Aliasee)) &&
1240         (CE->getOpcode() == Instruction::BitCast)) {
1241       writeOperand(CE, false);    
1242     } else
1243       assert(0 && "Unsupported aliasee");
1244   }
1245   
1246   printInfoComment(*GA);
1247   Out << '\n';
1248 }
1249
1250 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1251   // Print the types.
1252   for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1253        TI != TE; ++TI) {
1254     Out << '\t';
1255     PrintLLVMName(Out, &TI->first[0], TI->first.size(), LocalPrefix);
1256     Out << " = type ";
1257
1258     // Make sure we print out at least one level of the type structure, so
1259     // that we do not get %FILE = type %FILE
1260     TypePrinter.printAtLeastOneLevel(TI->second); 
1261     Out << '\n';
1262   }
1263 }
1264
1265 /// printFunction - Print all aspects of a function.
1266 ///
1267 void AssemblyWriter::printFunction(const Function *F) {
1268   // Print out the return type and name.
1269   Out << '\n';
1270
1271   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1272
1273   if (F->isDeclaration())
1274     Out << "declare ";
1275   else
1276     Out << "define ";
1277   
1278   PrintLinkage(F->getLinkage(), Out);
1279   PrintVisibility(F->getVisibility(), Out);
1280
1281   // Print the calling convention.
1282   switch (F->getCallingConv()) {
1283   case CallingConv::C: break;   // default
1284   case CallingConv::Fast:         Out << "fastcc "; break;
1285   case CallingConv::Cold:         Out << "coldcc "; break;
1286   case CallingConv::X86_StdCall:  Out << "x86_stdcallcc "; break;
1287   case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break; 
1288   default: Out << "cc" << F->getCallingConv() << " "; break;
1289   }
1290
1291   const FunctionType *FT = F->getFunctionType();
1292   const AttrListPtr &Attrs = F->getAttributes();
1293   Attributes RetAttrs = Attrs.getRetAttributes();
1294   if (RetAttrs != Attribute::None)
1295     Out <<  Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1296   printType(F->getReturnType());
1297   Out << ' ';
1298   WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1299   Out << '(';
1300   Machine.incorporateFunction(F);
1301
1302   // Loop over the arguments, printing them...
1303
1304   unsigned Idx = 1;
1305   if (!F->isDeclaration()) {
1306     // If this isn't a declaration, print the argument names as well.
1307     for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1308          I != E; ++I) {
1309       // Insert commas as we go... the first arg doesn't get a comma
1310       if (I != F->arg_begin()) Out << ", ";
1311       printArgument(I, Attrs.getParamAttributes(Idx));
1312       Idx++;
1313     }
1314   } else {
1315     // Otherwise, print the types from the function type.
1316     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1317       // Insert commas as we go... the first arg doesn't get a comma
1318       if (i) Out << ", ";
1319       
1320       // Output type...
1321       printType(FT->getParamType(i));
1322       
1323       Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1324       if (ArgAttrs != Attribute::None)
1325         Out << ' ' << Attribute::getAsString(ArgAttrs);
1326     }
1327   }
1328
1329   // Finish printing arguments...
1330   if (FT->isVarArg()) {
1331     if (FT->getNumParams()) Out << ", ";
1332     Out << "...";  // Output varargs portion of signature!
1333   }
1334   Out << ')';
1335   Attributes FnAttrs = Attrs.getFnAttributes();
1336   if (FnAttrs != Attribute::None)
1337     Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1338   if (F->hasSection())
1339     Out << " section \"" << F->getSection() << '"';
1340   if (F->getAlignment())
1341     Out << " align " << F->getAlignment();
1342   if (F->hasGC())
1343     Out << " gc \"" << F->getGC() << '"';
1344   if (F->isDeclaration()) {
1345     Out << "\n";
1346   } else {
1347     Out << " {";
1348
1349     // Output all of its basic blocks... for the function
1350     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1351       printBasicBlock(I);
1352
1353     Out << "}\n";
1354   }
1355
1356   Machine.purgeFunction();
1357 }
1358
1359 /// printArgument - This member is called for every argument that is passed into
1360 /// the function.  Simply print it out
1361 ///
1362 void AssemblyWriter::printArgument(const Argument *Arg, 
1363                                    Attributes Attrs) {
1364   // Output type...
1365   printType(Arg->getType());
1366
1367   // Output parameter attributes list
1368   if (Attrs != Attribute::None)
1369     Out << ' ' << Attribute::getAsString(Attrs);
1370
1371   // Output name, if available...
1372   if (Arg->hasName()) {
1373     Out << ' ';
1374     PrintLLVMName(Out, Arg);
1375   }
1376 }
1377
1378 /// printBasicBlock - This member is called for each basic block in a method.
1379 ///
1380 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1381   if (BB->hasName()) {              // Print out the label if it exists...
1382     Out << "\n";
1383     PrintLLVMName(Out, BB->getNameStart(), BB->getNameLen(), LabelPrefix);
1384     Out << ':';
1385   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
1386     Out << "\n; <label>:";
1387     int Slot = Machine.getLocalSlot(BB);
1388     if (Slot != -1)
1389       Out << Slot;
1390     else
1391       Out << "<badref>";
1392   }
1393
1394   if (BB->getParent() == 0)
1395     Out << "\t\t; Error: Block without parent!";
1396   else if (BB != &BB->getParent()->getEntryBlock()) {  // Not the entry block?
1397     // Output predecessors for the block...
1398     Out << "\t\t;";
1399     pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1400     
1401     if (PI == PE) {
1402       Out << " No predecessors!";
1403     } else {
1404       Out << " preds = ";
1405       writeOperand(*PI, false);
1406       for (++PI; PI != PE; ++PI) {
1407         Out << ", ";
1408         writeOperand(*PI, false);
1409       }
1410     }
1411   }
1412
1413   Out << "\n";
1414
1415   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1416
1417   // Output all of the instructions in the basic block...
1418   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1419     printInstruction(*I);
1420
1421   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1422 }
1423
1424
1425 /// printInfoComment - Print a little comment after the instruction indicating
1426 /// which slot it occupies.
1427 ///
1428 void AssemblyWriter::printInfoComment(const Value &V) {
1429   if (V.getType() != Type::VoidTy) {
1430     Out << "\t\t; <";
1431     printType(V.getType());
1432     Out << '>';
1433
1434     if (!V.hasName() && !isa<Instruction>(V)) {
1435       int SlotNum;
1436       if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1437         SlotNum = Machine.getGlobalSlot(GV);
1438       else
1439         SlotNum = Machine.getLocalSlot(&V);
1440       if (SlotNum == -1)
1441         Out << ":<badref>";
1442       else
1443         Out << ':' << SlotNum; // Print out the def slot taken.
1444     }
1445     Out << " [#uses=" << V.getNumUses() << ']';  // Output # uses
1446   }
1447 }
1448
1449 // This member is called for each Instruction in a function..
1450 void AssemblyWriter::printInstruction(const Instruction &I) {
1451   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1452
1453   Out << '\t';
1454
1455   // Print out name if it exists...
1456   if (I.hasName()) {
1457     PrintLLVMName(Out, &I);
1458     Out << " = ";
1459   } else if (I.getType() != Type::VoidTy) {
1460     // Print out the def slot taken.
1461     int SlotNum = Machine.getLocalSlot(&I);
1462     if (SlotNum == -1)
1463       Out << "<badref> = ";
1464     else
1465       Out << '%' << SlotNum << " = ";
1466   }
1467
1468   // If this is a volatile load or store, print out the volatile marker.
1469   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
1470       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1471       Out << "volatile ";
1472   } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1473     // If this is a call, check if it's a tail call.
1474     Out << "tail ";
1475   }
1476
1477   // Print out the opcode...
1478   Out << I.getOpcodeName();
1479
1480   // Print out the compare instruction predicates
1481   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1482     Out << ' ' << getPredicateText(CI->getPredicate());
1483
1484   // Print out the type of the operands...
1485   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1486
1487   // Special case conditional branches to swizzle the condition out to the front
1488   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1489     BranchInst &BI(cast<BranchInst>(I));
1490     Out << ' ';
1491     writeOperand(BI.getCondition(), true);
1492     Out << ", ";
1493     writeOperand(BI.getSuccessor(0), true);
1494     Out << ", ";
1495     writeOperand(BI.getSuccessor(1), true);
1496
1497   } else if (isa<SwitchInst>(I)) {
1498     // Special case switch statement to get formatting nice and correct...
1499     Out << ' ';
1500     writeOperand(Operand        , true);
1501     Out << ", ";
1502     writeOperand(I.getOperand(1), true);
1503     Out << " [";
1504
1505     for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1506       Out << "\n\t\t";
1507       writeOperand(I.getOperand(op  ), true);
1508       Out << ", ";
1509       writeOperand(I.getOperand(op+1), true);
1510     }
1511     Out << "\n\t]";
1512   } else if (isa<PHINode>(I)) {
1513     Out << ' ';
1514     printType(I.getType());
1515     Out << ' ';
1516
1517     for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1518       if (op) Out << ", ";
1519       Out << "[ ";
1520       writeOperand(I.getOperand(op  ), false); Out << ", ";
1521       writeOperand(I.getOperand(op+1), false); Out << " ]";
1522     }
1523   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1524     Out << ' ';
1525     writeOperand(I.getOperand(0), true);
1526     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1527       Out << ", " << *i;
1528   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1529     Out << ' ';
1530     writeOperand(I.getOperand(0), true); Out << ", ";
1531     writeOperand(I.getOperand(1), true);
1532     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1533       Out << ", " << *i;
1534   } else if (isa<ReturnInst>(I) && !Operand) {
1535     Out << " void";
1536   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1537     // Print the calling convention being used.
1538     switch (CI->getCallingConv()) {
1539     case CallingConv::C: break;   // default
1540     case CallingConv::Fast:  Out << " fastcc"; break;
1541     case CallingConv::Cold:  Out << " coldcc"; break;
1542     case CallingConv::X86_StdCall:  Out << " x86_stdcallcc"; break;
1543     case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break; 
1544     default: Out << " cc" << CI->getCallingConv(); break;
1545     }
1546
1547     const PointerType    *PTy = cast<PointerType>(Operand->getType());
1548     const FunctionType   *FTy = cast<FunctionType>(PTy->getElementType());
1549     const Type         *RetTy = FTy->getReturnType();
1550     const AttrListPtr &PAL = CI->getAttributes();
1551
1552     if (PAL.getRetAttributes() != Attribute::None)
1553       Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1554
1555     // If possible, print out the short form of the call instruction.  We can
1556     // only do this if the first argument is a pointer to a nonvararg function,
1557     // and if the return type is not a pointer to a function.
1558     //
1559     Out << ' ';
1560     if (!FTy->isVarArg() &&
1561         (!isa<PointerType>(RetTy) ||
1562          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1563       printType(RetTy);
1564       Out << ' ';
1565       writeOperand(Operand, false);
1566     } else {
1567       writeOperand(Operand, true);
1568     }
1569     Out << '(';
1570     for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1571       if (op > 1)
1572         Out << ", ";
1573       writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1574     }
1575     Out << ')';
1576     if (PAL.getFnAttributes() != Attribute::None)
1577       Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1578   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1579     const PointerType    *PTy = cast<PointerType>(Operand->getType());
1580     const FunctionType   *FTy = cast<FunctionType>(PTy->getElementType());
1581     const Type         *RetTy = FTy->getReturnType();
1582     const AttrListPtr &PAL = II->getAttributes();
1583
1584     // Print the calling convention being used.
1585     switch (II->getCallingConv()) {
1586     case CallingConv::C: break;   // default
1587     case CallingConv::Fast:  Out << " fastcc"; break;
1588     case CallingConv::Cold:  Out << " coldcc"; break;
1589     case CallingConv::X86_StdCall:  Out << " x86_stdcallcc"; break;
1590     case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1591     default: Out << " cc" << II->getCallingConv(); break;
1592     }
1593
1594     if (PAL.getRetAttributes() != Attribute::None)
1595       Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1596
1597     // If possible, print out the short form of the invoke instruction. We can
1598     // only do this if the first argument is a pointer to a nonvararg function,
1599     // and if the return type is not a pointer to a function.
1600     //
1601     Out << ' ';
1602     if (!FTy->isVarArg() &&
1603         (!isa<PointerType>(RetTy) ||
1604          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1605       printType(RetTy);
1606       Out << ' ';
1607       writeOperand(Operand, false);
1608     } else {
1609       writeOperand(Operand, true);
1610     }
1611     Out << '(';
1612     for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1613       if (op > 3)
1614         Out << ", ";
1615       writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1616     }
1617
1618     Out << ')';
1619     if (PAL.getFnAttributes() != Attribute::None)
1620       Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1621
1622     Out << "\n\t\t\tto ";
1623     writeOperand(II->getNormalDest(), true);
1624     Out << " unwind ";
1625     writeOperand(II->getUnwindDest(), true);
1626
1627   } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1628     Out << ' ';
1629     printType(AI->getType()->getElementType());
1630     if (AI->isArrayAllocation()) {
1631       Out << ", ";
1632       writeOperand(AI->getArraySize(), true);
1633     }
1634     if (AI->getAlignment()) {
1635       Out << ", align " << AI->getAlignment();
1636     }
1637   } else if (isa<CastInst>(I)) {
1638     if (Operand) {
1639       Out << ' ';
1640       writeOperand(Operand, true);   // Work with broken code
1641     }
1642     Out << " to ";
1643     printType(I.getType());
1644   } else if (isa<VAArgInst>(I)) {
1645     if (Operand) {
1646       Out << ' ';
1647       writeOperand(Operand, true);   // Work with broken code
1648     }
1649     Out << ", ";
1650     printType(I.getType());
1651   } else if (Operand) {   // Print the normal way...
1652
1653     // PrintAllTypes - Instructions who have operands of all the same type
1654     // omit the type from all but the first operand.  If the instruction has
1655     // different type operands (for example br), then they are all printed.
1656     bool PrintAllTypes = false;
1657     const Type *TheType = Operand->getType();
1658
1659     // Select, Store and ShuffleVector always print all types.
1660     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1661         || isa<ReturnInst>(I)) {
1662       PrintAllTypes = true;
1663     } else {
1664       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1665         Operand = I.getOperand(i);
1666         // note that Operand shouldn't be null, but the test helps make dump()
1667         // more tolerant of malformed IR
1668         if (Operand && Operand->getType() != TheType) {
1669           PrintAllTypes = true;    // We have differing types!  Print them all!
1670           break;
1671         }
1672       }
1673     }
1674
1675     if (!PrintAllTypes) {
1676       Out << ' ';
1677       printType(TheType);
1678     }
1679
1680     Out << ' ';
1681     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1682       if (i) Out << ", ";
1683       writeOperand(I.getOperand(i), PrintAllTypes);
1684     }
1685   }
1686   
1687   // Print post operand alignment for load/store
1688   if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1689     Out << ", align " << cast<LoadInst>(I).getAlignment();
1690   } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1691     Out << ", align " << cast<StoreInst>(I).getAlignment();
1692   }
1693
1694   printInfoComment(I);
1695   Out << '\n';
1696 }
1697
1698
1699 //===----------------------------------------------------------------------===//
1700 //                       External Interface declarations
1701 //===----------------------------------------------------------------------===//
1702
1703 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1704   raw_os_ostream OS(o);
1705   print(OS, AAW);
1706 }
1707 void Module::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1708   SlotTracker SlotTable(this);
1709   AssemblyWriter W(OS, SlotTable, this, AAW);
1710   W.write(this);
1711 }
1712
1713 void Type::print(std::ostream &o) const {
1714   raw_os_ostream OS(o);
1715   print(OS);
1716 }
1717
1718 void Type::print(raw_ostream &o) const {
1719   if (this == 0)
1720     o << "<null Type>";
1721   else
1722     o << getDescription();
1723 }
1724
1725 void Value::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1726   if (this == 0) {
1727     OS << "printing a <null> value\n";
1728     return;
1729   }
1730
1731   if (const Instruction *I = dyn_cast<Instruction>(this)) {
1732     const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
1733     SlotTracker SlotTable(F);
1734     AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
1735     W.write(I);
1736   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
1737     SlotTracker SlotTable(BB->getParent());
1738     AssemblyWriter W(OS, SlotTable,
1739                      BB->getParent() ? BB->getParent()->getParent() : 0, AAW);
1740     W.write(BB);
1741   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
1742     SlotTracker SlotTable(GV->getParent());
1743     AssemblyWriter W(OS, SlotTable, GV->getParent(), 0);
1744     W.write(GV);
1745   } else if (const Constant *C = dyn_cast<Constant>(this)) {
1746     OS << C->getType()->getDescription() << ' ';
1747     TypePrinting TypePrinter(0, OS);
1748     WriteConstantInt(OS, C, TypePrinter, 0);
1749   } else if (const Argument *A = dyn_cast<Argument>(this)) {
1750     WriteAsOperand(OS, this, true,
1751                    A->getParent() ? A->getParent()->getParent() : 0);
1752   } else if (isa<InlineAsm>(this)) {
1753     WriteAsOperand(OS, this, true, 0);
1754   } else {
1755     assert(0 && "Unknown value to print out!");
1756   }
1757 }
1758
1759 void Value::print(std::ostream &O, AssemblyAnnotationWriter *AAW) const {
1760   raw_os_ostream OS(O);
1761   print(OS, AAW);
1762 }
1763
1764 // Value::dump - allow easy printing of Values from the debugger.
1765 void Value::dump() const { print(errs()); errs() << '\n'; errs().flush(); }
1766
1767 // Type::dump - allow easy printing of Types from the debugger.
1768 void Type::dump() const { print(errs()); errs() << '\n'; errs().flush(); }
1769
1770 // Type::dump - allow easy printing of Types from the debugger.
1771 // This one uses type names from the given context module
1772 void Type::dump(const Module *Context) const {
1773   WriteTypeSymbolic(errs(), this, Context);
1774   errs() << '\n';
1775   errs().flush();
1776 }
1777
1778 // Module::dump() - Allow printing of Modules from the debugger.
1779 void Module::dump() const { print(errs(), 0); errs().flush(); }
1780
1781