f43fda9087d0acbc658a8f5a8da3db4b50f1add5
[oota-llvm.git] / lib / VMCore / AsmWriter.cpp
1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
2 //
3 // This library implements the functionality defined in llvm/Assembly/Writer.h
4 //
5 // Note that these routines must be extremely tolerant of various errors in the
6 // LLVM code, because of of the primary uses of it is for debugging
7 // transformations.
8 //
9 //===----------------------------------------------------------------------===//
10
11 #include "llvm/Assembly/CachedWriter.h"
12 #include "llvm/Assembly/Writer.h"
13 #include "llvm/Assembly/PrintModulePass.h"
14 #include "llvm/SlotCalculator.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Instruction.h"
17 #include "llvm/Module.h"
18 #include "llvm/Constants.h"
19 #include "llvm/iMemory.h"
20 #include "llvm/iTerminators.h"
21 #include "llvm/iPHINode.h"
22 #include "llvm/iOther.h"
23 #include "llvm/SymbolTable.h"
24 #include "llvm/Support/CFG.h"
25 #include "Support/StringExtras.h"
26 #include "Support/STLExtras.h"
27 #include <algorithm>
28 using std::string;
29 using std::map;
30 using std::vector;
31 using std::ostream;
32
33 static RegisterPass<PrintModulePass>
34 X("printm", "Print module to stderr",PassInfo::Analysis|PassInfo::Optimization);
35 static RegisterPass<PrintFunctionPass>
36 Y("print","Print function to stderr",PassInfo::Analysis|PassInfo::Optimization);
37
38 static void WriteAsOperandInternal(ostream &Out, const Value *V, bool PrintName,
39                                    map<const Type *, string> &TypeTable,
40                                    SlotCalculator *Table);
41
42 static const Module *getModuleFromVal(const Value *V) {
43   if (const Argument *MA = dyn_cast<const Argument>(V))
44     return MA->getParent() ? MA->getParent()->getParent() : 0;
45   else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(V))
46     return BB->getParent() ? BB->getParent()->getParent() : 0;
47   else if (const Instruction *I = dyn_cast<const Instruction>(V)) {
48     const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
49     return M ? M->getParent() : 0;
50   } else if (const GlobalValue *GV = dyn_cast<const GlobalValue>(V))
51     return GV->getParent();
52   return 0;
53 }
54
55 static SlotCalculator *createSlotCalculator(const Value *V) {
56   assert(!isa<Type>(V) && "Can't create an SC for a type!");
57   if (const Argument *FA = dyn_cast<const Argument>(V)) {
58     return new SlotCalculator(FA->getParent(), true);
59   } else if (const Instruction *I = dyn_cast<const Instruction>(V)) {
60     return new SlotCalculator(I->getParent()->getParent(), true);
61   } else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(V)) {
62     return new SlotCalculator(BB->getParent(), true);
63   } else if (const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V)){
64     return new SlotCalculator(GV->getParent(), true);
65   } else if (const Function *Func = dyn_cast<const Function>(V)) {
66     return new SlotCalculator(Func, true);
67   }
68   return 0;
69 }
70
71
72 // If the module has a symbol table, take all global types and stuff their
73 // names into the TypeNames map.
74 //
75 static void fillTypeNameTable(const Module *M,
76                               map<const Type *, string> &TypeNames) {
77   if (M && M->hasSymbolTable()) {
78     const SymbolTable *ST = M->getSymbolTable();
79     SymbolTable::const_iterator PI = ST->find(Type::TypeTy);
80     if (PI != ST->end()) {
81       SymbolTable::type_const_iterator I = PI->second.begin();
82       for (; I != PI->second.end(); ++I) {
83         // As a heuristic, don't insert pointer to primitive types, because
84         // they are used too often to have a single useful name.
85         //
86         const Type *Ty = cast<const Type>(I->second);
87         if (!isa<PointerType>(Ty) ||
88             !cast<PointerType>(Ty)->getElementType()->isPrimitiveType())
89           TypeNames.insert(std::make_pair(Ty, "%"+I->first));
90       }
91     }
92   }
93 }
94
95
96
97 static string calcTypeName(const Type *Ty, vector<const Type *> &TypeStack,
98                            map<const Type *, string> &TypeNames) {
99   if (Ty->isPrimitiveType()) return Ty->getDescription();  // Base case
100
101   // Check to see if the type is named.
102   map<const Type *, string>::iterator I = TypeNames.find(Ty);
103   if (I != TypeNames.end()) return I->second;
104
105   // Check to see if the Type is already on the stack...
106   unsigned Slot = 0, CurSize = TypeStack.size();
107   while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
108
109   // This is another base case for the recursion.  In this case, we know 
110   // that we have looped back to a type that we have previously visited.
111   // Generate the appropriate upreference to handle this.
112   // 
113   if (Slot < CurSize)
114     return "\\" + utostr(CurSize-Slot);       // Here's the upreference
115
116   TypeStack.push_back(Ty);    // Recursive case: Add us to the stack..
117   
118   string Result;
119   switch (Ty->getPrimitiveID()) {
120   case Type::FunctionTyID: {
121     const FunctionType *FTy = cast<const FunctionType>(Ty);
122     Result = calcTypeName(FTy->getReturnType(), TypeStack, TypeNames) + " (";
123     for (FunctionType::ParamTypes::const_iterator
124            I = FTy->getParamTypes().begin(),
125            E = FTy->getParamTypes().end(); I != E; ++I) {
126       if (I != FTy->getParamTypes().begin())
127         Result += ", ";
128       Result += calcTypeName(*I, TypeStack, TypeNames);
129     }
130     if (FTy->isVarArg()) {
131       if (!FTy->getParamTypes().empty()) Result += ", ";
132       Result += "...";
133     }
134     Result += ")";
135     break;
136   }
137   case Type::StructTyID: {
138     const StructType *STy = cast<const StructType>(Ty);
139     Result = "{ ";
140     for (StructType::ElementTypes::const_iterator
141            I = STy->getElementTypes().begin(),
142            E = STy->getElementTypes().end(); I != E; ++I) {
143       if (I != STy->getElementTypes().begin())
144         Result += ", ";
145       Result += calcTypeName(*I, TypeStack, TypeNames);
146     }
147     Result += " }";
148     break;
149   }
150   case Type::PointerTyID:
151     Result = calcTypeName(cast<const PointerType>(Ty)->getElementType(), 
152                           TypeStack, TypeNames) + "*";
153     break;
154   case Type::ArrayTyID: {
155     const ArrayType *ATy = cast<const ArrayType>(Ty);
156     Result = "[" + utostr(ATy->getNumElements()) + " x ";
157     Result += calcTypeName(ATy->getElementType(), TypeStack, TypeNames) + "]";
158     break;
159   }
160   default:
161     Result = "<unrecognized-type>";
162   }
163
164   TypeStack.pop_back();       // Remove self from stack...
165   return Result;
166 }
167
168
169 // printTypeInt - The internal guts of printing out a type that has a
170 // potentially named portion.
171 //
172 static ostream &printTypeInt(ostream &Out, const Type *Ty,
173                              map<const Type *, string> &TypeNames) {
174   // Primitive types always print out their description, regardless of whether
175   // they have been named or not.
176   //
177   if (Ty->isPrimitiveType()) return Out << Ty->getDescription();
178
179   // Check to see if the type is named.
180   map<const Type *, string>::iterator I = TypeNames.find(Ty);
181   if (I != TypeNames.end()) return Out << I->second;
182
183   // Otherwise we have a type that has not been named but is a derived type.
184   // Carefully recurse the type hierarchy to print out any contained symbolic
185   // names.
186   //
187   vector<const Type *> TypeStack;
188   string TypeName = calcTypeName(Ty, TypeStack, TypeNames);
189   TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
190   return Out << TypeName;
191 }
192
193
194 // WriteTypeSymbolic - This attempts to write the specified type as a symbolic
195 // type, iff there is an entry in the modules symbol table for the specified
196 // type or one of it's component types.  This is slower than a simple x << Type;
197 //
198 ostream &WriteTypeSymbolic(ostream &Out, const Type *Ty, const Module *M) {
199   Out << " "; 
200
201   // If they want us to print out a type, attempt to make it symbolic if there
202   // is a symbol table in the module...
203   if (M && M->hasSymbolTable()) {
204     map<const Type *, string> TypeNames;
205     fillTypeNameTable(M, TypeNames);
206     
207     return printTypeInt(Out, Ty, TypeNames);
208   } else {
209     return Out << Ty->getDescription();
210   }
211 }
212
213 static void WriteConstantInt(ostream &Out, const Constant *CV, bool PrintName,
214                              map<const Type *, string> &TypeTable,
215                              SlotCalculator *Table) {
216   if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
217     Out << (CB == ConstantBool::True ? "true" : "false");
218   } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
219     Out << CI->getValue();
220   } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
221     Out << CI->getValue();
222   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
223     // We would like to output the FP constant value in exponential notation,
224     // but we cannot do this if doing so will lose precision.  Check here to
225     // make sure that we only output it in exponential format if we can parse
226     // the value back and get the same value.
227     //
228     std::string StrVal = ftostr(CFP->getValue());
229
230     // Check to make sure that the stringized number is not some string like
231     // "Inf" or NaN, that atof will accept, but the lexer will not.  Check that
232     // the string matches the "[-+]?[0-9]" regex.
233     //
234     if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
235         ((StrVal[0] == '-' || StrVal[0] == '+') &&
236          (StrVal[0] >= '0' && StrVal[0] <= '9')))
237       // Reparse stringized version!
238       if (atof(StrVal.c_str()) == CFP->getValue()) {
239         Out << StrVal; return;
240       }
241     
242     // Otherwise we could not reparse it to exactly the same value, so we must
243     // output the string in hexadecimal format!
244     //
245     // Behave nicely in the face of C TBAA rules... see:
246     // http://www.nullstone.com/htmls/category/aliastyp.htm
247     //
248     double Val = CFP->getValue();
249     char *Ptr = (char*)&Val;
250     assert(sizeof(double) == sizeof(uint64_t) && sizeof(double) == 8 &&
251            "assuming that double is 64 bits!");
252     Out << "0x" << utohexstr(*(uint64_t*)Ptr);
253
254   } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
255     // As a special case, print the array as a string if it is an array of
256     // ubytes or an array of sbytes with positive values.
257     // 
258     const Type *ETy = CA->getType()->getElementType();
259     bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
260
261     if (ETy == Type::SByteTy)
262       for (unsigned i = 0; i < CA->getNumOperands(); ++i)
263         if (cast<ConstantSInt>(CA->getOperand(i))->getValue() < 0) {
264           isString = false;
265           break;
266         }
267
268     if (isString) {
269       Out << "c\"";
270       for (unsigned i = 0; i < CA->getNumOperands(); ++i) {
271         unsigned char C = (ETy == Type::SByteTy) ?
272           (unsigned char)cast<ConstantSInt>(CA->getOperand(i))->getValue() :
273           (unsigned char)cast<ConstantUInt>(CA->getOperand(i))->getValue();
274         
275         if (isprint(C) && C != '"' && C != '\\') {
276           Out << C;
277         } else {
278           Out << '\\'
279               << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
280               << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
281         }
282       }
283       Out << "\"";
284
285     } else {                // Cannot output in string format...
286       Out << "[";
287       if (CA->getNumOperands()) {
288         Out << " ";
289         printTypeInt(Out, ETy, TypeTable);
290         WriteAsOperandInternal(Out, CA->getOperand(0),
291                                PrintName, TypeTable, Table);
292         for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
293           Out << ", ";
294           printTypeInt(Out, ETy, TypeTable);
295           WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
296                                  TypeTable, Table);
297         }
298       }
299       Out << " ]";
300     }
301   } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
302     Out << "{";
303     if (CS->getNumOperands()) {
304       Out << " ";
305       printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
306
307       WriteAsOperandInternal(Out, CS->getOperand(0),
308                              PrintName, TypeTable, Table);
309
310       for (unsigned i = 1; i < CS->getNumOperands(); i++) {
311         Out << ", ";
312         printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
313
314         WriteAsOperandInternal(Out, CS->getOperand(i),
315                                PrintName, TypeTable, Table);
316       }
317     }
318
319     Out << " }";
320   } else if (isa<ConstantPointerNull>(CV)) {
321     Out << "null";
322
323   } else if (const ConstantPointerRef *PR = dyn_cast<ConstantPointerRef>(CV)) {
324     const GlobalValue *V = PR->getValue();
325     if (V->hasName()) {
326       Out << "%" << V->getName();
327     } else if (Table) {
328       int Slot = Table->getValSlot(V);
329       if (Slot >= 0)
330         Out << "%" << Slot;
331       else
332         Out << "<pointer reference badref>";
333     } else {
334       Out << "<pointer reference without context info>";
335     }
336
337   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
338     Out << CE->getOpcodeName();
339
340     bool isGEP = CE->getOpcode() == Instruction::GetElementPtr;
341     Out << " (";
342     
343     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
344       printTypeInt(Out, (*OI)->getType(), TypeTable);
345       WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Table);
346       if (OI+1 != CE->op_end())
347         Out << ", ";
348     }
349     
350     if (CE->getOpcode() == Instruction::Cast) {
351       Out << " to ";
352       printTypeInt(Out, CE->getType(), TypeTable);
353     }
354     Out << ")";
355
356   } else {
357     Out << "<placeholder or erroneous Constant>";
358   }
359 }
360
361
362 // WriteAsOperand - Write the name of the specified value out to the specified
363 // ostream.  This can be useful when you just want to print int %reg126, not the
364 // whole instruction that generated it.
365 //
366 static void WriteAsOperandInternal(ostream &Out, const Value *V, bool PrintName,
367                                    map<const Type *, string> &TypeTable,
368                                    SlotCalculator *Table) {
369   Out << " ";
370   if (PrintName && V->hasName()) {
371     Out << "%" << V->getName();
372   } else {
373     if (const Constant *CV = dyn_cast<const Constant>(V)) {
374       WriteConstantInt(Out, CV, PrintName, TypeTable, Table);
375     } else {
376       int Slot;
377       if (Table) {
378         Slot = Table->getValSlot(V);
379       } else {
380         if (const Type *Ty = dyn_cast<const Type>(V)) {
381           Out << Ty->getDescription();
382           return;
383         }
384
385         Table = createSlotCalculator(V);
386         if (Table == 0) { Out << "BAD VALUE TYPE!"; return; }
387
388         Slot = Table->getValSlot(V);
389         delete Table;
390       }
391       if (Slot >= 0)  Out << "%" << Slot;
392       else if (PrintName)
393         Out << "<badref>";     // Not embeded into a location?
394     }
395   }
396 }
397
398
399
400 // WriteAsOperand - Write the name of the specified value out to the specified
401 // ostream.  This can be useful when you just want to print int %reg126, not the
402 // whole instruction that generated it.
403 //
404 ostream &WriteAsOperand(ostream &Out, const Value *V, bool PrintType, 
405                         bool PrintName, const Module *Context) {
406   map<const Type *, string> TypeNames;
407   if (Context == 0) Context = getModuleFromVal(V);
408
409   if (Context && Context->hasSymbolTable())
410     fillTypeNameTable(Context, TypeNames);
411
412   if (PrintType)
413     printTypeInt(Out, V->getType(), TypeNames);
414   
415   WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
416   return Out;
417 }
418
419
420
421 class AssemblyWriter {
422   ostream &Out;
423   SlotCalculator &Table;
424   const Module *TheModule;
425   map<const Type *, string> TypeNames;
426 public:
427   inline AssemblyWriter(ostream &o, SlotCalculator &Tab, const Module *M)
428     : Out(o), Table(Tab), TheModule(M) {
429
430     // If the module has a symbol table, take all global types and stuff their
431     // names into the TypeNames map.
432     //
433     fillTypeNameTable(M, TypeNames);
434   }
435
436   inline void write(const Module *M)         { printModule(M);      }
437   inline void write(const GlobalVariable *G) { printGlobal(G);      }
438   inline void write(const Function *F)       { printFunction(F);    }
439   inline void write(const BasicBlock *BB)    { printBasicBlock(BB); }
440   inline void write(const Instruction *I)    { printInstruction(*I); }
441   inline void write(const Constant *CPV)     { printConstant(CPV);  }
442   inline void write(const Type *Ty)          { printType(Ty);       }
443
444   void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
445
446 private :
447   void printModule(const Module *M);
448   void printSymbolTable(const SymbolTable &ST);
449   void printConstant(const Constant *CPV);
450   void printGlobal(const GlobalVariable *GV);
451   void printFunction(const Function *F);
452   void printArgument(const Argument *FA);
453   void printBasicBlock(const BasicBlock *BB);
454   void printInstruction(const Instruction &I);
455
456   // printType - Go to extreme measures to attempt to print out a short,
457   // symbolic version of a type name.
458   //
459   ostream &printType(const Type *Ty) {
460     return printTypeInt(Out, Ty, TypeNames);
461   }
462
463   // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
464   // without considering any symbolic types that we may have equal to it.
465   //
466   ostream &printTypeAtLeastOneLevel(const Type *Ty);
467
468   // printInfoComment - Print a little comment after the instruction indicating
469   // which slot it occupies.
470   void printInfoComment(const Value &V);
471 };
472
473
474 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
475 // without considering any symbolic types that we may have equal to it.
476 //
477 ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
478   if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
479     printType(FTy->getReturnType()) << " (";
480     for (FunctionType::ParamTypes::const_iterator
481            I = FTy->getParamTypes().begin(),
482            E = FTy->getParamTypes().end(); I != E; ++I) {
483       if (I != FTy->getParamTypes().begin())
484         Out << ", ";
485       printType(*I);
486     }
487     if (FTy->isVarArg()) {
488       if (!FTy->getParamTypes().empty()) Out << ", ";
489       Out << "...";
490     }
491     Out << ")";
492   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
493     Out << "{ ";
494     for (StructType::ElementTypes::const_iterator
495            I = STy->getElementTypes().begin(),
496            E = STy->getElementTypes().end(); I != E; ++I) {
497       if (I != STy->getElementTypes().begin())
498         Out << ", ";
499       printType(*I);
500     }
501     Out << " }";
502   } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
503     printType(PTy->getElementType()) << "*";
504   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
505     Out << "[" << ATy->getNumElements() << " x ";
506     printType(ATy->getElementType()) << "]";
507   } else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
508     Out << OTy->getDescription();
509   } else {
510     if (!Ty->isPrimitiveType())
511       Out << "<unknown derived type>";
512     printType(Ty);
513   }
514   return Out;
515 }
516
517
518 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType, 
519                                   bool PrintName) {
520   if (PrintType) { Out << " "; printType(Operand->getType()); }
521   WriteAsOperandInternal(Out, Operand, PrintName, TypeNames, &Table);
522 }
523
524
525 void AssemblyWriter::printModule(const Module *M) {
526   // Loop over the symbol table, emitting all named constants...
527   if (M->hasSymbolTable())
528     printSymbolTable(*M->getSymbolTable());
529   
530   for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
531     printGlobal(I);
532
533   Out << "\nimplementation   ; Functions:\n";
534   
535   // Output all of the functions...
536   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
537     printFunction(I);
538 }
539
540 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
541   if (GV->hasName()) Out << "%" << GV->getName() << " = ";
542
543   if (GV->hasInternalLinkage()) Out << "internal ";
544   if (!GV->hasInitializer()) Out << "external ";
545
546   Out << (GV->isConstant() ? "constant " : "global ");
547   printType(GV->getType()->getElementType());
548
549   if (GV->hasInitializer())
550     writeOperand(GV->getInitializer(), false, false);
551
552   printInfoComment(*GV);
553   Out << "\n";
554 }
555
556
557 // printSymbolTable - Run through symbol table looking for named constants
558 // if a named constant is found, emit it's declaration...
559 //
560 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
561   for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
562     SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
563     SymbolTable::type_const_iterator End = ST.type_end(TI->first);
564     
565     for (; I != End; ++I) {
566       const Value *V = I->second;
567       if (const Constant *CPV = dyn_cast<const Constant>(V)) {
568         printConstant(CPV);
569       } else if (const Type *Ty = dyn_cast<const Type>(V)) {
570         Out << "\t%" << I->first << " = type ";
571
572         // Make sure we print out at least one level of the type structure, so
573         // that we do not get %FILE = type %FILE
574         //
575         printTypeAtLeastOneLevel(Ty) << "\n";
576       }
577     }
578   }
579 }
580
581
582 // printConstant - Print out a constant pool entry...
583 //
584 void AssemblyWriter::printConstant(const Constant *CPV) {
585   // Don't print out unnamed constants, they will be inlined
586   if (!CPV->hasName()) return;
587
588   // Print out name...
589   Out << "\t%" << CPV->getName() << " =";
590
591   // Write the value out now...
592   writeOperand(CPV, true, false);
593
594   printInfoComment(*CPV);
595   Out << "\n";
596 }
597
598 // printFunction - Print all aspects of a function.
599 //
600 void AssemblyWriter::printFunction(const Function *F) {
601   // Print out the return type and name...
602   Out << "\n" << (F->isExternal() ? "declare " : "")
603       << (F->hasInternalLinkage() ? "internal " : "");
604   printType(F->getReturnType()) << " %" << F->getName() << "(";
605   Table.incorporateFunction(F);
606
607   // Loop over the arguments, printing them...
608   const FunctionType *FT = F->getFunctionType();
609
610   if (!F->isExternal()) {
611     for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
612       printArgument(I);
613   } else {
614     // Loop over the arguments, printing them...
615     for (FunctionType::ParamTypes::const_iterator I = FT->getParamTypes().begin(),
616            E = FT->getParamTypes().end(); I != E; ++I) {
617       if (I != FT->getParamTypes().begin()) Out << ", ";
618       printType(*I);
619     }
620   }
621
622   // Finish printing arguments...
623   if (FT->isVarArg()) {
624     if (FT->getParamTypes().size()) Out << ", ";
625     Out << "...";  // Output varargs portion of signature!
626   }
627   Out << ")";
628
629   if (F->isExternal()) {
630     Out << "\n";
631   } else {
632     Out << " {";
633   
634     // Output all of its basic blocks... for the function
635     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
636       printBasicBlock(I);
637
638     Out << "}\n";
639   }
640
641   Table.purgeFunction();
642 }
643
644 // printArgument - This member is called for every argument that 
645 // is passed into the function.  Simply print it out
646 //
647 void AssemblyWriter::printArgument(const Argument *Arg) {
648   // Insert commas as we go... the first arg doesn't get a comma
649   if (Arg != &Arg->getParent()->afront()) Out << ", ";
650
651   // Output type...
652   printType(Arg->getType());
653   
654   // Output name, if available...
655   if (Arg->hasName())
656     Out << " %" << Arg->getName();
657   else if (Table.getValSlot(Arg) < 0)
658     Out << "<badref>";
659 }
660
661 // printBasicBlock - This member is called for each basic block in a methd.
662 //
663 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
664   if (BB->hasName()) {              // Print out the label if it exists...
665     Out << "\n" << BB->getName() << ":";
666   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
667     int Slot = Table.getValSlot(BB);
668     Out << "\n; <label>:";
669     if (Slot >= 0) 
670       Out << Slot;         // Extra newline seperates out label's
671     else 
672       Out << "<badref>"; 
673   }
674   
675   // Output predecessors for the block...
676   Out << "\t\t;";
677   pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
678
679   if (PI == PE) {
680     Out << " No predecessors!";
681   } else {
682     Out << " preds =";
683     writeOperand(*PI, false, true);
684     for (++PI; PI != PE; ++PI) {
685       Out << ",";
686       writeOperand(*PI, false, true);
687     }
688   }
689   
690   Out << "\n";
691
692   // Output all of the instructions in the basic block...
693   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
694     printInstruction(*I);
695 }
696
697
698 // printInfoComment - Print a little comment after the instruction indicating
699 // which slot it occupies.
700 //
701 void AssemblyWriter::printInfoComment(const Value &V) {
702   if (V.getType() != Type::VoidTy) {
703     Out << "\t\t; <";
704     printType(V.getType()) << ">";
705
706     if (!V.hasName()) {
707       int Slot = Table.getValSlot(&V); // Print out the def slot taken...
708       if (Slot >= 0) Out << ":" << Slot;
709       else Out << ":<badref>";
710     }
711     Out << " [#uses=" << V.use_size() << "]";  // Output # uses
712   }
713 }
714
715 // printInstruction - This member is called for each Instruction in a methd.
716 //
717 void AssemblyWriter::printInstruction(const Instruction &I) {
718   Out << "\t";
719
720   // Print out name if it exists...
721   if (I.hasName())
722     Out << "%" << I.getName() << " = ";
723
724   // Print out the opcode...
725   Out << I.getOpcodeName();
726
727   // Print out the type of the operands...
728   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
729
730   // Special case conditional branches to swizzle the condition out to the front
731   if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
732     writeOperand(I.getOperand(2), true);
733     Out << ",";
734     writeOperand(Operand, true);
735     Out << ",";
736     writeOperand(I.getOperand(1), true);
737
738   } else if (isa<SwitchInst>(I)) {
739     // Special case switch statement to get formatting nice and correct...
740     writeOperand(Operand        , true); Out << ",";
741     writeOperand(I.getOperand(1), true); Out << " [";
742
743     for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
744       Out << "\n\t\t";
745       writeOperand(I.getOperand(op  ), true); Out << ",";
746       writeOperand(I.getOperand(op+1), true);
747     }
748     Out << "\n\t]";
749   } else if (isa<PHINode>(I)) {
750     Out << " ";
751     printType(I.getType());
752     Out << " ";
753
754     for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
755       if (op) Out << ", ";
756       Out << "[";  
757       writeOperand(I.getOperand(op  ), false); Out << ",";
758       writeOperand(I.getOperand(op+1), false); Out << " ]";
759     }
760   } else if (isa<ReturnInst>(I) && !Operand) {
761     Out << " void";
762   } else if (isa<CallInst>(I)) {
763     const PointerType *PTy = dyn_cast<PointerType>(Operand->getType());
764     const FunctionType*MTy = PTy ? dyn_cast<FunctionType>(PTy->getElementType()):0;
765     const Type      *RetTy = MTy ? MTy->getReturnType() : 0;
766
767     // If possible, print out the short form of the call instruction, but we can
768     // only do this if the first argument is a pointer to a nonvararg function,
769     // and if the value returned is not a pointer to a function.
770     //
771     if (RetTy && MTy && !MTy->isVarArg() &&
772         (!isa<PointerType>(RetTy) || 
773          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
774       Out << " "; printType(RetTy);
775       writeOperand(Operand, false);
776     } else {
777       writeOperand(Operand, true);
778     }
779     Out << "(";
780     if (I.getNumOperands() > 1) writeOperand(I.getOperand(1), true);
781     for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
782       Out << ",";
783       writeOperand(I.getOperand(op), true);
784     }
785
786     Out << " )";
787   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
788     // TODO: Should try to print out short form of the Invoke instruction
789     writeOperand(Operand, true);
790     Out << "(";
791     if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
792     for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
793       Out << ",";
794       writeOperand(I.getOperand(op), true);
795     }
796
797     Out << " )\n\t\t\tto";
798     writeOperand(II->getNormalDest(), true);
799     Out << " except";
800     writeOperand(II->getExceptionalDest(), true);
801
802   } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
803     Out << " ";
804     printType(AI->getType()->getElementType());
805     if (AI->isArrayAllocation()) {
806       Out << ",";
807       writeOperand(AI->getArraySize(), true);
808     }
809   } else if (isa<CastInst>(I)) {
810     if (Operand) writeOperand(Operand, true);
811     Out << " to ";
812     printType(I.getType());
813   } else if (Operand) {   // Print the normal way...
814
815     // PrintAllTypes - Instructions who have operands of all the same type 
816     // omit the type from all but the first operand.  If the instruction has
817     // different type operands (for example br), then they are all printed.
818     bool PrintAllTypes = false;
819     const Type *TheType = Operand->getType();
820
821     for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
822       Operand = I.getOperand(i);
823       if (Operand->getType() != TheType) {
824         PrintAllTypes = true;       // We have differing types!  Print them all!
825         break;
826       }
827     }
828
829     // Shift Left & Right print both types even for Ubyte LHS
830     if (isa<ShiftInst>(I)) PrintAllTypes = true;
831
832     if (!PrintAllTypes) {
833       Out << " ";
834       printType(I.getOperand(0)->getType());
835     }
836
837     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
838       if (i) Out << ",";
839       writeOperand(I.getOperand(i), PrintAllTypes);
840     }
841   }
842
843   printInfoComment(I);
844   Out << "\n";
845 }
846
847
848 //===----------------------------------------------------------------------===//
849 //                       External Interface declarations
850 //===----------------------------------------------------------------------===//
851
852
853 void Module::print(std::ostream &o) const {
854   SlotCalculator SlotTable(this, true);
855   AssemblyWriter W(o, SlotTable, this);
856   W.write(this);
857 }
858
859 void GlobalVariable::print(std::ostream &o) const {
860   SlotCalculator SlotTable(getParent(), true);
861   AssemblyWriter W(o, SlotTable, getParent());
862   W.write(this);
863 }
864
865 void Function::print(std::ostream &o) const {
866   SlotCalculator SlotTable(getParent(), true);
867   AssemblyWriter W(o, SlotTable, getParent());
868
869   W.write(this);
870 }
871
872 void BasicBlock::print(std::ostream &o) const {
873   SlotCalculator SlotTable(getParent(), true);
874   AssemblyWriter W(o, SlotTable, 
875                    getParent() ? getParent()->getParent() : 0);
876   W.write(this);
877 }
878
879 void Instruction::print(std::ostream &o) const {
880   const Function *F = getParent() ? getParent()->getParent() : 0;
881   SlotCalculator SlotTable(F, true);
882   AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0);
883
884   W.write(this);
885 }
886
887 void Constant::print(std::ostream &o) const {
888   if (this == 0) { o << "<null> constant value\n"; return; }
889
890   // Handle CPR's special, because they have context information...
891   if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
892     CPR->getValue()->print(o);  // Print as a global value, with context info.
893     return;
894   }
895
896   o << " " << getType()->getDescription() << " ";
897
898   map<const Type *, string> TypeTable;
899   WriteConstantInt(o, this, false, TypeTable, 0);
900 }
901
902 void Type::print(std::ostream &o) const { 
903   if (this == 0)
904     o << "<null Type>";
905   else
906     o << getDescription();
907 }
908
909 void Argument::print(std::ostream &o) const {
910   o << getType() << " " << getName();
911 }
912
913 void Value::dump() const { print(std::cerr); }
914
915 //===----------------------------------------------------------------------===//
916 //  CachedWriter Class Implementation
917 //===----------------------------------------------------------------------===//
918
919 void CachedWriter::setModule(const Module *M) {
920   delete SC; delete AW;
921   if (M) {
922     SC = new SlotCalculator(M, true);
923     AW = new AssemblyWriter(Out, *SC, M);
924   } else {
925     SC = 0; AW = 0;
926   }
927 }
928
929 CachedWriter::~CachedWriter() {
930   delete AW;
931   delete SC;
932 }
933
934 CachedWriter &CachedWriter::operator<<(const Value *V) {
935   assert(AW && SC && "CachedWriter does not have a current module!");
936   switch (V->getValueType()) {
937   case Value::ConstantVal:
938   case Value::ArgumentVal:       AW->writeOperand(V, true, true); break;
939   case Value::TypeVal:           AW->write(cast<const Type>(V)); break;
940   case Value::InstructionVal:    AW->write(cast<Instruction>(V)); break;
941   case Value::BasicBlockVal:     AW->write(cast<BasicBlock>(V)); break;
942   case Value::FunctionVal:       AW->write(cast<Function>(V)); break;
943   case Value::GlobalVariableVal: AW->write(cast<GlobalVariable>(V)); break;
944   default: Out << "<unknown value type: " << V->getValueType() << ">"; break;
945   }
946   return *this;
947 }