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