Minor bugfix for previous checkin
[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 // TODO: print out the type name instead of the full type if a particular type
10 // is in the symbol table...
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Assembly/CachedWriter.h"
15 #include "llvm/Assembly/Writer.h"
16 #include "llvm/SlotCalculator.h"
17 #include "llvm/Module.h"
18 #include "llvm/Function.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/BasicBlock.h"
21 #include "llvm/ConstantVals.h"
22 #include "llvm/iMemory.h"
23 #include "llvm/iTerminators.h"
24 #include "llvm/iPHINode.h"
25 #include "llvm/iOther.h"
26 #include "llvm/SymbolTable.h"
27 #include "llvm/Argument.h"
28 #include "Support/StringExtras.h"
29 #include "Support/STLExtras.h"
30 #include <algorithm>
31 #include <map>
32 using std::string;
33 using std::map;
34 using std::vector;
35 using std::ostream;
36
37 static const Module *getModuleFromVal(const Value *V) {
38   if (const Argument *MA = dyn_cast<const Argument>(V))
39     return MA->getParent() ? MA->getParent()->getParent() : 0;
40   else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(V))
41     return BB->getParent() ? BB->getParent()->getParent() : 0;
42   else if (const Instruction *I = dyn_cast<const Instruction>(V)) {
43     const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
44     return M ? M->getParent() : 0;
45   } else if (const GlobalValue *GV = dyn_cast<const GlobalValue>(V))
46     return GV->getParent();
47   else if (const Module *Mod  = dyn_cast<const Module>(V))
48     return Mod;
49   return 0;
50 }
51
52 static SlotCalculator *createSlotCalculator(const Value *V) {
53   assert(!isa<Type>(V) && "Can't create an SC for a type!");
54   if (const Argument *FA = dyn_cast<const Argument>(V)) {
55     return new SlotCalculator(FA->getParent(), true);
56   } else if (const Instruction *I = dyn_cast<const Instruction>(V)) {
57     return new SlotCalculator(I->getParent()->getParent(), true);
58   } else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(V)) {
59     return new SlotCalculator(BB->getParent(), true);
60   } else if (const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V)){
61     return new SlotCalculator(GV->getParent(), true);
62   } else if (const Function *Func = dyn_cast<const Function>(V)) {
63     return new SlotCalculator(Func, true);
64   } else if (const Module *Mod  = dyn_cast<const Module>(V)) {
65     return new SlotCalculator(Mod, true);
66   }
67   return 0;
68 }
69
70 // WriteAsOperand - Write the name of the specified value out to the specified
71 // ostream.  This can be useful when you just want to print int %reg126, not the
72 // whole instruction that generated it.
73 //
74 static void WriteAsOperandInternal(ostream &Out, const Value *V, bool PrintName,
75                                    SlotCalculator *Table) {
76   if (PrintName && V->hasName()) {
77     Out << " %" << V->getName();
78   } else {
79     if (const Constant *CPV = dyn_cast<const Constant>(V)) {
80       Out << " " << CPV->getStrValue();
81     } else {
82       int Slot;
83       if (Table) {
84         Slot = Table->getValSlot(V);
85       } else {
86         if (const Type *Ty = dyn_cast<const Type>(V)) {
87           Out << " " << Ty->getDescription();
88           return;
89         }
90
91         Table = createSlotCalculator(V);
92         if (Table == 0) { Out << "BAD VALUE TYPE!"; return; }
93
94         Slot = Table->getValSlot(V);
95         delete Table;
96       }
97       if (Slot >= 0)  Out << " %" << Slot;
98       else if (PrintName)
99         Out << "<badref>";     // Not embeded into a location?
100     }
101   }
102 }
103
104
105 // If the module has a symbol table, take all global types and stuff their
106 // names into the TypeNames map.
107 //
108 static void fillTypeNameTable(const Module *M,
109                               map<const Type *, string> &TypeNames) {
110   if (M && M->hasSymbolTable()) {
111     const SymbolTable *ST = M->getSymbolTable();
112     SymbolTable::const_iterator PI = ST->find(Type::TypeTy);
113     if (PI != ST->end()) {
114       SymbolTable::type_const_iterator I = PI->second.begin();
115       for (; I != PI->second.end(); ++I) {
116         // As a heuristic, don't insert pointer to primitive types, because
117         // they are used too often to have a single useful name.
118         //
119         const Type *Ty = cast<const Type>(I->second);
120         if (!isa<PointerType>(Ty) ||
121             !cast<PointerType>(Ty)->getElementType()->isPrimitiveType())
122           TypeNames.insert(std::make_pair(Ty, "%"+I->first));
123       }
124     }
125   }
126 }
127
128
129
130 static string calcTypeName(const Type *Ty, vector<const Type *> &TypeStack,
131                            map<const Type *, string> &TypeNames) {
132   if (Ty->isPrimitiveType()) return Ty->getDescription();  // Base case
133
134   // Check to see if the type is named.
135   map<const Type *, string>::iterator I = TypeNames.find(Ty);
136   if (I != TypeNames.end()) return I->second;
137
138   // Check to see if the Type is already on the stack...
139   unsigned Slot = 0, CurSize = TypeStack.size();
140   while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
141
142   // This is another base case for the recursion.  In this case, we know 
143   // that we have looped back to a type that we have previously visited.
144   // Generate the appropriate upreference to handle this.
145   // 
146   if (Slot < CurSize)
147     return "\\" + utostr(CurSize-Slot);       // Here's the upreference
148
149   TypeStack.push_back(Ty);    // Recursive case: Add us to the stack..
150   
151   string Result;
152   switch (Ty->getPrimitiveID()) {
153   case Type::FunctionTyID: {
154     const FunctionType *FTy = cast<const FunctionType>(Ty);
155     Result = calcTypeName(FTy->getReturnType(), TypeStack, TypeNames) + " (";
156     for (FunctionType::ParamTypes::const_iterator
157            I = FTy->getParamTypes().begin(),
158            E = FTy->getParamTypes().end(); I != E; ++I) {
159       if (I != FTy->getParamTypes().begin())
160         Result += ", ";
161       Result += calcTypeName(*I, TypeStack, TypeNames);
162     }
163     if (FTy->isVarArg()) {
164       if (!FTy->getParamTypes().empty()) Result += ", ";
165       Result += "...";
166     }
167     Result += ")";
168     break;
169   }
170   case Type::StructTyID: {
171     const StructType *STy = cast<const StructType>(Ty);
172     Result = "{ ";
173     for (StructType::ElementTypes::const_iterator
174            I = STy->getElementTypes().begin(),
175            E = STy->getElementTypes().end(); I != E; ++I) {
176       if (I != STy->getElementTypes().begin())
177         Result += ", ";
178       Result += calcTypeName(*I, TypeStack, TypeNames);
179     }
180     Result += " }";
181     break;
182   }
183   case Type::PointerTyID:
184     Result = calcTypeName(cast<const PointerType>(Ty)->getElementType(), 
185                           TypeStack, TypeNames) + "*";
186     break;
187   case Type::ArrayTyID: {
188     const ArrayType *ATy = cast<const ArrayType>(Ty);
189     Result = "[" + utostr(ATy->getNumElements()) + " x ";
190     Result += calcTypeName(ATy->getElementType(), TypeStack, TypeNames) + "]";
191     break;
192   }
193   default:
194     assert(0 && "Unhandled case in getTypeProps!");
195     Result = "<error>";
196   }
197
198   TypeStack.pop_back();       // Remove self from stack...
199   return Result;
200 }
201
202
203 // printTypeInt - The internal guts of printing out a type that has a
204 // potentially named portion.
205 //
206 static ostream &printTypeInt(ostream &Out, const Type *Ty,
207                              map<const Type *, string> &TypeNames) {
208   // Primitive types always print out their description, regardless of whether
209   // they have been named or not.
210   //
211   if (Ty->isPrimitiveType()) return Out << Ty->getDescription();
212
213   // Check to see if the type is named.
214   map<const Type *, string>::iterator I = TypeNames.find(Ty);
215   if (I != TypeNames.end()) return Out << I->second;
216
217   // Otherwise we have a type that has not been named but is a derived type.
218   // Carefully recurse the type hierarchy to print out any contained symbolic
219   // names.
220   //
221   vector<const Type *> TypeStack;
222   string TypeName = calcTypeName(Ty, TypeStack, TypeNames);
223   TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
224   return Out << TypeName;
225 }
226
227
228 // WriteTypeSymbolic - This attempts to write the specified type as a symbolic
229 // type, iff there is an entry in the modules symbol table for the specified
230 // type or one of it's component types.  This is slower than a simple x << Type;
231 //
232 ostream &WriteTypeSymbolic(ostream &Out, const Type *Ty, const Module *M) {
233   Out << " "; 
234
235   // If they want us to print out a type, attempt to make it symbolic if there
236   // is a symbol table in the module...
237   if (M && M->hasSymbolTable()) {
238     map<const Type *, string> TypeNames;
239     fillTypeNameTable(M, TypeNames);
240     
241     return printTypeInt(Out, Ty, TypeNames);
242   } else {
243     return Out << Ty->getDescription();
244   }
245 }
246
247
248 // WriteAsOperand - Write the name of the specified value out to the specified
249 // ostream.  This can be useful when you just want to print int %reg126, not the
250 // whole instruction that generated it.
251 //
252 ostream &WriteAsOperand(ostream &Out, const Value *V, bool PrintType, 
253                         bool PrintName, SlotCalculator *Table) {
254   if (PrintType)
255     WriteTypeSymbolic(Out, V->getType(), getModuleFromVal(V));
256
257   WriteAsOperandInternal(Out, V, PrintName, Table);
258   return Out;
259 }
260
261
262
263 class AssemblyWriter {
264   ostream &Out;
265   SlotCalculator &Table;
266   const Module *TheModule;
267   map<const Type *, string> TypeNames;
268 public:
269   inline AssemblyWriter(ostream &o, SlotCalculator &Tab, const Module *M)
270     : Out(o), Table(Tab), TheModule(M) {
271
272     // If the module has a symbol table, take all global types and stuff their
273     // names into the TypeNames map.
274     //
275     fillTypeNameTable(M, TypeNames);
276   }
277
278   inline void write(const Module *M)         { printModule(M);      }
279   inline void write(const GlobalVariable *G) { printGlobal(G);      }
280   inline void write(const Function *F)       { printFunction(F);    }
281   inline void write(const BasicBlock *BB)    { printBasicBlock(BB); }
282   inline void write(const Instruction *I)    { printInstruction(I); }
283   inline void write(const Constant *CPV)     { printConstant(CPV);  }
284   inline void write(const Type *Ty)          { printType(Ty);       }
285
286 private :
287   void printModule(const Module *M);
288   void printSymbolTable(const SymbolTable &ST);
289   void printConstant(const Constant *CPV);
290   void printGlobal(const GlobalVariable *GV);
291   void printFunction(const Function *F);
292   void printArgument(const Argument *FA);
293   void printBasicBlock(const BasicBlock *BB);
294   void printInstruction(const Instruction *I);
295
296   // printType - Go to extreme measures to attempt to print out a short,
297   // symbolic version of a type name.
298   //
299   ostream &printType(const Type *Ty) {
300     return printTypeInt(Out, Ty, TypeNames);
301   }
302
303   // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
304   // without considering any symbolic types that we may have equal to it.
305   //
306   ostream &printTypeAtLeastOneLevel(const Type *Ty);
307
308   void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
309
310   // printInfoComment - Print a little comment after the instruction indicating
311   // which slot it occupies.
312   void printInfoComment(const Value *V);
313 };
314
315
316 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
317 // without considering any symbolic types that we may have equal to it.
318 //
319 ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
320   if (FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
321     printType(FTy->getReturnType()) << " (";
322     for (FunctionType::ParamTypes::const_iterator
323            I = FTy->getParamTypes().begin(),
324            E = FTy->getParamTypes().end(); I != E; ++I) {
325       if (I != FTy->getParamTypes().begin())
326         Out << ", ";
327       Out << printType(*I);
328     }
329     if (FTy->isVarArg()) {
330       if (!FTy->getParamTypes().empty()) Out << ", ";
331       Out << "...";
332     }
333     Out << ")";
334   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
335     Out << "{ ";
336     for (StructType::ElementTypes::const_iterator
337            I = STy->getElementTypes().begin(),
338            E = STy->getElementTypes().end(); I != E; ++I) {
339       if (I != STy->getElementTypes().begin())
340         Out << ", ";
341       printType(*I);
342     }
343     Out << " }";
344   } else if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
345     printType(PTy->getElementType()) << "*";
346   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
347     Out << "[" << ATy->getNumElements() << " x ";
348     printType(ATy->getElementType()) << "]";
349   } else {
350     assert(Ty->isPrimitiveType() && "Unknown derived type!");
351     printType(Ty);
352   }
353   return Out;
354 }
355
356
357 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType, 
358                                   bool PrintName) {
359   if (PrintType) { Out << " "; printType(Operand->getType()); }
360   WriteAsOperandInternal(Out, Operand, PrintName, &Table);
361 }
362
363
364 void AssemblyWriter::printModule(const Module *M) {
365   // Loop over the symbol table, emitting all named constants...
366   if (M->hasSymbolTable())
367     printSymbolTable(*M->getSymbolTable());
368   
369   for_each(M->gbegin(), M->gend(), 
370            bind_obj(this, &AssemblyWriter::printGlobal));
371
372   Out << "implementation\n";
373   
374   // Output all of the functions...
375   for_each(M->begin(), M->end(), bind_obj(this,&AssemblyWriter::printFunction));
376 }
377
378 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
379   if (GV->hasName()) Out << "%" << GV->getName() << " = ";
380
381   if (GV->hasInternalLinkage()) Out << "internal ";
382   if (!GV->hasInitializer()) Out << "uninitialized ";
383
384   Out << (GV->isConstant() ? "constant " : "global ");
385   printType(GV->getType()->getElementType());
386
387   if (GV->hasInitializer())
388     writeOperand(GV->getInitializer(), false, false);
389
390   printInfoComment(GV);
391   Out << "\n";
392 }
393
394
395 // printSymbolTable - Run through symbol table looking for named constants
396 // if a named constant is found, emit it's declaration...
397 //
398 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
399   for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
400     SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
401     SymbolTable::type_const_iterator End = ST.type_end(TI->first);
402     
403     for (; I != End; ++I) {
404       const Value *V = I->second;
405       if (const Constant *CPV = dyn_cast<const Constant>(V)) {
406         printConstant(CPV);
407       } else if (const Type *Ty = dyn_cast<const Type>(V)) {
408         Out << "\t%" << I->first << " = type ";
409
410         // Make sure we print out at least one level of the type structure, so
411         // that we do not get %FILE = type %FILE
412         //
413         printTypeAtLeastOneLevel(Ty) << "\n";
414       }
415     }
416   }
417 }
418
419
420 // printConstant - Print out a constant pool entry...
421 //
422 void AssemblyWriter::printConstant(const Constant *CPV) {
423   // Don't print out unnamed constants, they will be inlined
424   if (!CPV->hasName()) return;
425
426   // Print out name...
427   Out << "\t%" << CPV->getName() << " = ";
428
429   // Print out the constant type...
430   printType(CPV->getType());
431
432   // Write the value out now...
433   writeOperand(CPV, false, false);
434
435   if (!CPV->hasName() && CPV->getType() != Type::VoidTy) {
436     int Slot = Table.getValSlot(CPV); // Print out the def slot taken...
437     Out << "\t\t; <";
438     printType(CPV->getType()) << ">:";
439     if (Slot >= 0) Out << Slot;
440     else Out << "<badref>";
441   } 
442
443   Out << "\n";
444 }
445
446 // printFunction - Print all aspects of a function.
447 //
448 void AssemblyWriter::printFunction(const Function *M) {
449   // Print out the return type and name...
450   Out << "\n" << (M->isExternal() ? "declare " : "")
451       << (M->hasInternalLinkage() ? "internal " : "");
452   printType(M->getReturnType()) << " \"" << M->getName() << "\"(";
453   Table.incorporateFunction(M);
454
455   // Loop over the arguments, printing them...
456   const FunctionType *MT = M->getFunctionType();
457
458   if (!M->isExternal()) {
459     for_each(M->getArgumentList().begin(), M->getArgumentList().end(),
460              bind_obj(this, &AssemblyWriter::printArgument));
461   } else {
462     // Loop over the arguments, printing them...
463     const FunctionType *MT = M->getFunctionType();
464     for (FunctionType::ParamTypes::const_iterator I = MT->getParamTypes().begin(),
465            E = MT->getParamTypes().end(); I != E; ++I) {
466       if (I != MT->getParamTypes().begin()) Out << ", ";
467       printType(*I);
468     }
469   }
470
471   // Finish printing arguments...
472   if (MT->isVarArg()) {
473     if (MT->getParamTypes().size()) Out << ", ";
474     Out << "...";  // Output varargs portion of signature!
475   }
476   Out << ")\n";
477
478   if (!M->isExternal()) {
479     // Loop over the symbol table, emitting all named constants...
480     if (M->hasSymbolTable())
481       printSymbolTable(*M->getSymbolTable());
482
483     Out << "begin";
484   
485     // Output all of its basic blocks... for the function
486     for_each(M->begin(), M->end(),
487              bind_obj(this, &AssemblyWriter::printBasicBlock));
488
489     Out << "end\n";
490   }
491
492   Table.purgeFunction();
493 }
494
495 // printArgument - This member is called for every argument that 
496 // is passed into the function.  Simply print it out
497 //
498 void AssemblyWriter::printArgument(const Argument *Arg) {
499   // Insert commas as we go... the first arg doesn't get a comma
500   if (Arg != Arg->getParent()->getArgumentList().front()) Out << ", ";
501
502   // Output type...
503   printType(Arg->getType());
504   
505   // Output name, if available...
506   if (Arg->hasName())
507     Out << " %" << Arg->getName();
508   else if (Table.getValSlot(Arg) < 0)
509     Out << "<badref>";
510 }
511
512 // printBasicBlock - This member is called for each basic block in a methd.
513 //
514 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
515   if (BB->hasName()) {              // Print out the label if it exists...
516     Out << "\n" << BB->getName() << ":";
517   } else {
518     int Slot = Table.getValSlot(BB);
519     Out << "\n; <label>:";
520     if (Slot >= 0) 
521       Out << Slot;         // Extra newline seperates out label's
522     else 
523       Out << "<badref>"; 
524   }
525   Out << "\t\t\t\t\t;[#uses=" << BB->use_size() << "]\n";  // Output # uses
526
527   // Output all of the instructions in the basic block...
528   for_each(BB->begin(), BB->end(),
529            bind_obj(this, &AssemblyWriter::printInstruction));
530 }
531
532
533 // printInfoComment - Print a little comment after the instruction indicating
534 // which slot it occupies.
535 //
536 void AssemblyWriter::printInfoComment(const Value *V) {
537   if (V->getType() != Type::VoidTy) {
538     Out << "\t\t; <";
539     printType(V->getType()) << ">";
540
541     if (!V->hasName()) {
542       int Slot = Table.getValSlot(V); // Print out the def slot taken...
543       if (Slot >= 0) Out << ":" << Slot;
544       else Out << ":<badref>";
545     }
546     Out << " [#uses=" << V->use_size() << "]";  // Output # uses
547   }
548 }
549
550 // printInstruction - This member is called for each Instruction in a methd.
551 //
552 void AssemblyWriter::printInstruction(const Instruction *I) {
553   Out << "\t";
554
555   // Print out name if it exists...
556   if (I && I->hasName())
557     Out << "%" << I->getName() << " = ";
558
559   // Print out the opcode...
560   Out << I->getOpcodeName();
561
562   // Print out the type of the operands...
563   const Value *Operand = I->getNumOperands() ? I->getOperand(0) : 0;
564
565   // Special case conditional branches to swizzle the condition out to the front
566   if (isa<BranchInst>(I) && I->getNumOperands() > 1) {
567     writeOperand(I->getOperand(2), true);
568     Out << ",";
569     writeOperand(Operand, true);
570     Out << ",";
571     writeOperand(I->getOperand(1), true);
572
573   } else if (isa<SwitchInst>(I)) {
574     // Special case switch statement to get formatting nice and correct...
575     writeOperand(Operand         , true); Out << ",";
576     writeOperand(I->getOperand(1), true); Out << " [";
577
578     for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; op += 2) {
579       Out << "\n\t\t";
580       writeOperand(I->getOperand(op  ), true); Out << ",";
581       writeOperand(I->getOperand(op+1), true);
582     }
583     Out << "\n\t]";
584   } else if (isa<PHINode>(I)) {
585     Out << " ";
586     printType(I->getType());
587     Out << " ";
588
589     for (unsigned op = 0, Eop = I->getNumOperands(); op < Eop; op += 2) {
590       if (op) Out << ", ";
591       Out << "[";  
592       writeOperand(I->getOperand(op  ), false); Out << ",";
593       writeOperand(I->getOperand(op+1), false); Out << " ]";
594     }
595   } else if (isa<ReturnInst>(I) && !Operand) {
596     Out << " void";
597   } else if (isa<CallInst>(I)) {
598     const PointerType *PTy = dyn_cast<PointerType>(Operand->getType());
599     const FunctionType*MTy = PTy ? dyn_cast<FunctionType>(PTy->getElementType()):0;
600     const Type      *RetTy = MTy ? MTy->getReturnType() : 0;
601
602     // If possible, print out the short form of the call instruction, but we can
603     // only do this if the first argument is a pointer to a nonvararg function,
604     // and if the value returned is not a pointer to a function.
605     //
606     if (RetTy && MTy && !MTy->isVarArg() &&
607         (!isa<PointerType>(RetTy) || 
608          !isa<FunctionType>(cast<PointerType>(RetTy)))) {
609       Out << " "; printType(RetTy);
610       writeOperand(Operand, false);
611     } else {
612       writeOperand(Operand, true);
613     }
614     Out << "(";
615     if (I->getNumOperands() > 1) writeOperand(I->getOperand(1), true);
616     for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; ++op) {
617       Out << ",";
618       writeOperand(I->getOperand(op), true);
619     }
620
621     Out << " )";
622   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(I)) {
623     // TODO: Should try to print out short form of the Invoke instruction
624     writeOperand(Operand, true);
625     Out << "(";
626     if (I->getNumOperands() > 3) writeOperand(I->getOperand(3), true);
627     for (unsigned op = 4, Eop = I->getNumOperands(); op < Eop; ++op) {
628       Out << ",";
629       writeOperand(I->getOperand(op), true);
630     }
631
632     Out << " )\n\t\t\tto";
633     writeOperand(II->getNormalDest(), true);
634     Out << " except";
635     writeOperand(II->getExceptionalDest(), true);
636
637   } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(I)) {
638     Out << " ";
639     printType(AI->getType()->getElementType());
640     if (AI->isArrayAllocation()) {
641       Out << ",";
642       writeOperand(AI->getArraySize(), true);
643     }
644   } else if (isa<CastInst>(I)) {
645     writeOperand(Operand, true);
646     Out << " to ";
647     printType(I->getType());
648   } else if (Operand) {   // Print the normal way...
649
650     // PrintAllTypes - Instructions who have operands of all the same type 
651     // omit the type from all but the first operand.  If the instruction has
652     // different type operands (for example br), then they are all printed.
653     bool PrintAllTypes = false;
654     const Type *TheType = Operand->getType();
655
656     for (unsigned i = 1, E = I->getNumOperands(); i != E; ++i) {
657       Operand = I->getOperand(i);
658       if (Operand->getType() != TheType) {
659         PrintAllTypes = true;       // We have differing types!  Print them all!
660         break;
661       }
662     }
663
664     // Shift Left & Right print both types even for Ubyte LHS
665     if (isa<ShiftInst>(I)) PrintAllTypes = true;
666
667     if (!PrintAllTypes) {
668       Out << " ";
669       printType(I->getOperand(0)->getType());
670     }
671
672     for (unsigned i = 0, E = I->getNumOperands(); i != E; ++i) {
673       if (i) Out << ",";
674       writeOperand(I->getOperand(i), PrintAllTypes);
675     }
676   }
677
678   printInfoComment(I);
679   Out << "\n";
680 }
681
682
683 //===----------------------------------------------------------------------===//
684 //                       External Interface declarations
685 //===----------------------------------------------------------------------===//
686
687
688 void Module::print(std::ostream &o) const {
689   SlotCalculator SlotTable(this, true);
690   AssemblyWriter W(o, SlotTable, this);
691   W.write(this);
692 }
693
694 void GlobalVariable::print(std::ostream &o) const {
695   SlotCalculator SlotTable(getParent(), true);
696   AssemblyWriter W(o, SlotTable, getParent());
697   W.write(this);
698 }
699
700 void Function::print(std::ostream &o) const {
701   SlotCalculator SlotTable(getParent(), true);
702   AssemblyWriter W(o, SlotTable, getParent());
703
704   W.write(this);
705 }
706
707 void BasicBlock::print(std::ostream &o) const {
708   SlotCalculator SlotTable(getParent(), true);
709   AssemblyWriter W(o, SlotTable, 
710                    getParent() ? getParent()->getParent() : 0);
711   W.write(this);
712 }
713
714 void Instruction::print(std::ostream &o) const {
715   const Function *F = getParent() ? getParent()->getParent() : 0;
716   SlotCalculator SlotTable(F, true);
717   AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0);
718
719   W.write(this);
720 }
721
722 void Constant::print(std::ostream &o) const {
723   if (this == 0) { o << "<null> constant value\n"; return; }
724   o << " " << getType()->getDescription() << " " << getStrValue();
725 }
726
727 void Type::print(std::ostream &o) const { 
728   if (this == 0)
729     o << "<null Type>";
730   else
731     o << getDescription();
732 }
733
734 void Argument::print(std::ostream &o) const {
735   o << getType() << " " << getName();
736 }
737
738 void Value::dump() const { print(std::cerr); }
739
740 //===----------------------------------------------------------------------===//
741 //  CachedWriter Class Implementation
742 //===----------------------------------------------------------------------===//
743
744 void CachedWriter::setModule(const Module *M) {
745   delete SC; delete AW;
746   if (M) {
747     SC = new SlotCalculator(M, true);
748     AW = new AssemblyWriter(Out, *SC, M);
749   } else {
750     SC = 0; AW = 0;
751   }
752 }
753
754 CachedWriter::~CachedWriter() {
755   delete AW;
756   delete SC;
757 }
758
759 CachedWriter &CachedWriter::operator<<(const Value *V) {
760   assert(AW && SC && "CachedWriter does not have a current module!");
761   switch (V->getValueType()) {
762   case Value::ConstantVal:
763     Out << " "; AW->write(V->getType());
764     Out << " " << cast<Constant>(V)->getStrValue(); break;
765   case Value::ArgumentVal: 
766     AW->write(V->getType()); Out << " " << V->getName(); break;
767   case Value::TypeVal:           AW->write(cast<const Type>(V)); break;
768   case Value::InstructionVal:    AW->write(cast<Instruction>(V)); break;
769   case Value::BasicBlockVal:     AW->write(cast<BasicBlock>(V)); break;
770   case Value::FunctionVal:       AW->write(cast<Function>(V)); break;
771   case Value::GlobalVariableVal: AW->write(cast<GlobalVariable>(V)); break;
772   case Value::ModuleVal:         AW->write(cast<Module>(V)); break;
773   default: Out << "<unknown value type: " << V->getValueType() << ">"; break;
774   }
775   return *this;
776 }