Add support for printing constpointerrefs more nicely
[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 "Support/StringExtras.h"
25 #include "Support/STLExtras.h"
26 #include <algorithm>
27 using std::string;
28 using std::map;
29 using std::vector;
30 using std::ostream;
31
32 static RegisterPass<PrintModulePass>
33 X("printm", "Print module to stderr",PassInfo::Analysis|PassInfo::Optimization);
34 static RegisterPass<PrintFunctionPass>
35 Y("print","Print function to stderr",PassInfo::Analysis|PassInfo::Optimization);
36
37 static void WriteAsOperandInternal(ostream &Out, const Value *V, bool PrintName,
38                                    map<const Type *, string> &TypeTable,
39                                    SlotCalculator *Table);
40
41 static const Module *getModuleFromVal(const Value *V) {
42   if (const Argument *MA = dyn_cast<const Argument>(V))
43     return MA->getParent() ? MA->getParent()->getParent() : 0;
44   else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(V))
45     return BB->getParent() ? BB->getParent()->getParent() : 0;
46   else if (const Instruction *I = dyn_cast<const Instruction>(V)) {
47     const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
48     return M ? M->getParent() : 0;
49   } else if (const GlobalValue *GV = dyn_cast<const GlobalValue>(V))
50     return GV->getParent();
51   return 0;
52 }
53
54 static SlotCalculator *createSlotCalculator(const Value *V) {
55   assert(!isa<Type>(V) && "Can't create an SC for a type!");
56   if (const Argument *FA = dyn_cast<const Argument>(V)) {
57     return new SlotCalculator(FA->getParent(), true);
58   } else if (const Instruction *I = dyn_cast<const Instruction>(V)) {
59     return new SlotCalculator(I->getParent()->getParent(), true);
60   } else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(V)) {
61     return new SlotCalculator(BB->getParent(), true);
62   } else if (const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V)){
63     return new SlotCalculator(GV->getParent(), true);
64   } else if (const Function *Func = dyn_cast<const Function>(V)) {
65     return new SlotCalculator(Func, true);
66   }
67   return 0;
68 }
69
70
71 // If the module has a symbol table, take all global types and stuff their
72 // names into the TypeNames map.
73 //
74 static void fillTypeNameTable(const Module *M,
75                               map<const Type *, string> &TypeNames) {
76   if (M && M->hasSymbolTable()) {
77     const SymbolTable *ST = M->getSymbolTable();
78     SymbolTable::const_iterator PI = ST->find(Type::TypeTy);
79     if (PI != ST->end()) {
80       SymbolTable::type_const_iterator I = PI->second.begin();
81       for (; I != PI->second.end(); ++I) {
82         // As a heuristic, don't insert pointer to primitive types, because
83         // they are used too often to have a single useful name.
84         //
85         const Type *Ty = cast<const Type>(I->second);
86         if (!isa<PointerType>(Ty) ||
87             !cast<PointerType>(Ty)->getElementType()->isPrimitiveType())
88           TypeNames.insert(std::make_pair(Ty, "%"+I->first));
89       }
90     }
91   }
92 }
93
94
95
96 static string calcTypeName(const Type *Ty, vector<const Type *> &TypeStack,
97                            map<const Type *, string> &TypeNames) {
98   if (Ty->isPrimitiveType()) return Ty->getDescription();  // Base case
99
100   // Check to see if the type is named.
101   map<const Type *, string>::iterator I = TypeNames.find(Ty);
102   if (I != TypeNames.end()) return I->second;
103
104   // Check to see if the Type is already on the stack...
105   unsigned Slot = 0, CurSize = TypeStack.size();
106   while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
107
108   // This is another base case for the recursion.  In this case, we know 
109   // that we have looped back to a type that we have previously visited.
110   // Generate the appropriate upreference to handle this.
111   // 
112   if (Slot < CurSize)
113     return "\\" + utostr(CurSize-Slot);       // Here's the upreference
114
115   TypeStack.push_back(Ty);    // Recursive case: Add us to the stack..
116   
117   string Result;
118   switch (Ty->getPrimitiveID()) {
119   case Type::FunctionTyID: {
120     const FunctionType *FTy = cast<const FunctionType>(Ty);
121     Result = calcTypeName(FTy->getReturnType(), TypeStack, TypeNames) + " (";
122     for (FunctionType::ParamTypes::const_iterator
123            I = FTy->getParamTypes().begin(),
124            E = FTy->getParamTypes().end(); I != E; ++I) {
125       if (I != FTy->getParamTypes().begin())
126         Result += ", ";
127       Result += calcTypeName(*I, TypeStack, TypeNames);
128     }
129     if (FTy->isVarArg()) {
130       if (!FTy->getParamTypes().empty()) Result += ", ";
131       Result += "...";
132     }
133     Result += ")";
134     break;
135   }
136   case Type::StructTyID: {
137     const StructType *STy = cast<const StructType>(Ty);
138     Result = "{ ";
139     for (StructType::ElementTypes::const_iterator
140            I = STy->getElementTypes().begin(),
141            E = STy->getElementTypes().end(); I != E; ++I) {
142       if (I != STy->getElementTypes().begin())
143         Result += ", ";
144       Result += calcTypeName(*I, TypeStack, TypeNames);
145     }
146     Result += " }";
147     break;
148   }
149   case Type::PointerTyID:
150     Result = calcTypeName(cast<const PointerType>(Ty)->getElementType(), 
151                           TypeStack, TypeNames) + "*";
152     break;
153   case Type::ArrayTyID: {
154     const ArrayType *ATy = cast<const ArrayType>(Ty);
155     Result = "[" + utostr(ATy->getNumElements()) + " x ";
156     Result += calcTypeName(ATy->getElementType(), TypeStack, TypeNames) + "]";
157     break;
158   }
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 ostream &printTypeInt(ostream &Out, const Type *Ty,
172                              map<const Type *, 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   map<const Type *, 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   vector<const Type *> TypeStack;
187   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 ostream &WriteTypeSymbolic(ostream &Out, const Type *Ty, const Module *M) {
198   Out << " "; 
199
200   // If they want us to print out a type, attempt to make it symbolic if there
201   // is a symbol table in the module...
202   if (M && M->hasSymbolTable()) {
203     map<const Type *, string> TypeNames;
204     fillTypeNameTable(M, TypeNames);
205     
206     return printTypeInt(Out, Ty, TypeNames);
207   } else {
208     return Out << Ty->getDescription();
209   }
210 }
211
212 static void WriteConstantInt(ostream &Out, const Constant *CV, bool PrintName,
213                              map<const Type *, string> &TypeTable,
214                              SlotCalculator *Table) {
215   if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
216     Out << (CB == ConstantBool::True ? "true" : "false");
217   } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
218     Out << CI->getValue();
219   } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
220     Out << CI->getValue();
221   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
222     // We would like to output the FP constant value in exponential notation,
223     // but we cannot do this if doing so will lose precision.  Check here to
224     // make sure that we only output it in exponential format if we can parse
225     // the value back and get the same value.
226     //
227     std::string StrVal = ftostr(CFP->getValue());
228
229     // Check to make sure that the stringized number is not some string like
230     // "Inf" or NaN, that atof will accept, but the lexer will not.  Check that
231     // the string matches the "[-+]?[0-9]" regex.
232     //
233     if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
234         ((StrVal[0] == '-' || StrVal[0] == '+') &&
235          (StrVal[0] >= '0' && StrVal[0] <= '9')))
236       // Reparse stringized version!
237       if (atof(StrVal.c_str()) == CFP->getValue()) {
238         Out << StrVal; return;
239       }
240     
241     // Otherwise we could not reparse it to exactly the same value, so we must
242     // output the string in hexadecimal format!
243     //
244     // Behave nicely in the face of C TBAA rules... see:
245     // http://www.nullstone.com/htmls/category/aliastyp.htm
246     //
247     double Val = CFP->getValue();
248     char *Ptr = (char*)&Val;
249     assert(sizeof(double) == sizeof(uint64_t) && sizeof(double) == 8 &&
250            "assuming that double is 64 bits!");
251     Out << "0x" << utohexstr(*(uint64_t*)Ptr);
252
253   } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
254     // As a special case, print the array as a string if it is an array of
255     // ubytes or an array of sbytes with positive values.
256     // 
257     const Type *ETy = CA->getType()->getElementType();
258     bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
259
260     if (ETy == Type::SByteTy)
261       for (unsigned i = 0; i < CA->getNumOperands(); ++i)
262         if (cast<ConstantSInt>(CA->getOperand(i))->getValue() < 0) {
263           isString = false;
264           break;
265         }
266
267     if (isString) {
268       Out << "c\"";
269       for (unsigned i = 0; i < CA->getNumOperands(); ++i) {
270         unsigned char C = (ETy == Type::SByteTy) ?
271           (unsigned char)cast<ConstantSInt>(CA->getOperand(i))->getValue() :
272           (unsigned char)cast<ConstantUInt>(CA->getOperand(i))->getValue();
273         
274         if (isprint(C) && C != '"' && C != '\\') {
275           Out << C;
276         } else {
277           Out << '\\'
278               << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
279               << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
280         }
281       }
282       Out << "\"";
283
284     } else {                // Cannot output in string format...
285       Out << "[";
286       if (CA->getNumOperands()) {
287         Out << " ";
288         printTypeInt(Out, ETy, TypeTable);
289         WriteAsOperandInternal(Out, CA->getOperand(0),
290                                PrintName, TypeTable, Table);
291         for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
292           Out << ", ";
293           printTypeInt(Out, ETy, TypeTable);
294           WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
295                                  TypeTable, Table);
296         }
297       }
298       Out << " ]";
299     }
300   } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
301     Out << "{";
302     if (CS->getNumOperands()) {
303       Out << " ";
304       printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
305
306       WriteAsOperandInternal(Out, CS->getOperand(0),
307                              PrintName, TypeTable, Table);
308
309       for (unsigned i = 1; i < CS->getNumOperands(); i++) {
310         Out << ", ";
311         printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
312
313         WriteAsOperandInternal(Out, CS->getOperand(i),
314                                PrintName, TypeTable, Table);
315       }
316     }
317
318     Out << " }";
319   } else if (isa<ConstantPointerNull>(CV)) {
320     Out << "null";
321
322   } else if (const ConstantPointerRef *PR = dyn_cast<ConstantPointerRef>(CV)) {
323     const GlobalValue *V = PR->getValue();
324     if (V->hasName()) {
325       Out << "%" << V->getName();
326     } else if (Table) {
327       int Slot = Table->getValSlot(V);
328       if (Slot >= 0)
329         Out << "%" << Slot;
330       else
331         Out << "<pointer reference badref>";
332     } else {
333       Out << "<pointer reference without context info>";
334     }
335
336   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
337     Out << CE->getOpcodeName();
338
339     bool isGEP = CE->getOpcode() == Instruction::GetElementPtr;
340     Out << " (";
341     
342     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
343       printTypeInt(Out, (*OI)->getType(), TypeTable);
344       WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Table);
345       if (OI+1 != CE->op_end())
346         Out << ", ";
347     }
348     
349     if (CE->getOpcode() == Instruction::Cast) {
350       Out << " to ";
351       printTypeInt(Out, CE->getType(), TypeTable);
352     }
353     Out << ")";
354
355   } else {
356     Out << "<placeholder or erroneous Constant>";
357   }
358 }
359
360
361 // WriteAsOperand - Write the name of the specified value out to the specified
362 // ostream.  This can be useful when you just want to print int %reg126, not the
363 // whole instruction that generated it.
364 //
365 static void WriteAsOperandInternal(ostream &Out, const Value *V, bool PrintName,
366                                    map<const Type *, 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 ostream &WriteAsOperand(ostream &Out, const Value *V, bool PrintType, 
404                         bool PrintName, const Module *Context) {
405   map<const Type *, string> TypeNames;
406   if (Context == 0) Context = getModuleFromVal(V);
407
408   if (Context && Context->hasSymbolTable())
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   ostream &Out;
422   SlotCalculator &Table;
423   const Module *TheModule;
424   map<const Type *, string> TypeNames;
425 public:
426   inline AssemblyWriter(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   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   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 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   // Loop over the symbol table, emitting all named constants...
526   if (M->hasSymbolTable())
527     printSymbolTable(*M->getSymbolTable());
528   
529   for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
530     printGlobal(I);
531
532   Out << "\nimplementation   ; Functions:\n";
533   
534   // Output all of the functions...
535   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
536     printFunction(I);
537 }
538
539 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
540   if (GV->hasName()) Out << "%" << GV->getName() << " = ";
541
542   if (GV->hasInternalLinkage()) Out << "internal ";
543   if (!GV->hasInitializer()) Out << "uninitialized ";
544
545   Out << (GV->isConstant() ? "constant " : "global ");
546   printType(GV->getType()->getElementType());
547
548   if (GV->hasInitializer())
549     writeOperand(GV->getInitializer(), false, false);
550
551   printInfoComment(*GV);
552   Out << "\n";
553 }
554
555
556 // printSymbolTable - Run through symbol table looking for named constants
557 // if a named constant is found, emit it's declaration...
558 //
559 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
560   for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
561     SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
562     SymbolTable::type_const_iterator End = ST.type_end(TI->first);
563     
564     for (; I != End; ++I) {
565       const Value *V = I->second;
566       if (const Constant *CPV = dyn_cast<const Constant>(V)) {
567         printConstant(CPV);
568       } else if (const Type *Ty = dyn_cast<const Type>(V)) {
569         Out << "\t%" << I->first << " = type ";
570
571         // Make sure we print out at least one level of the type structure, so
572         // that we do not get %FILE = type %FILE
573         //
574         printTypeAtLeastOneLevel(Ty) << "\n";
575       }
576     }
577   }
578 }
579
580
581 // printConstant - Print out a constant pool entry...
582 //
583 void AssemblyWriter::printConstant(const Constant *CPV) {
584   // Don't print out unnamed constants, they will be inlined
585   if (!CPV->hasName()) return;
586
587   // Print out name...
588   Out << "\t%" << CPV->getName() << " =";
589
590   // Write the value out now...
591   writeOperand(CPV, true, false);
592
593   printInfoComment(*CPV);
594   Out << "\n";
595 }
596
597 // printFunction - Print all aspects of a function.
598 //
599 void AssemblyWriter::printFunction(const Function *F) {
600   // Print out the return type and name...
601   Out << "\n" << (F->isExternal() ? "declare " : "")
602       << (F->hasInternalLinkage() ? "internal " : "");
603   printType(F->getReturnType()) << " %" << F->getName() << "(";
604   Table.incorporateFunction(F);
605
606   // Loop over the arguments, printing them...
607   const FunctionType *FT = F->getFunctionType();
608
609   if (!F->isExternal()) {
610     for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
611       printArgument(I);
612   } else {
613     // Loop over the arguments, printing them...
614     for (FunctionType::ParamTypes::const_iterator I = FT->getParamTypes().begin(),
615            E = FT->getParamTypes().end(); I != E; ++I) {
616       if (I != FT->getParamTypes().begin()) Out << ", ";
617       printType(*I);
618     }
619   }
620
621   // Finish printing arguments...
622   if (FT->isVarArg()) {
623     if (FT->getParamTypes().size()) Out << ", ";
624     Out << "...";  // Output varargs portion of signature!
625   }
626   Out << ")";
627
628   if (F->isExternal()) {
629     Out << "\n";
630   } else {
631     Out << " {";
632   
633     // Output all of its basic blocks... for the function
634     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
635       printBasicBlock(I);
636
637     Out << "}\n";
638   }
639
640   Table.purgeFunction();
641 }
642
643 // printArgument - This member is called for every argument that 
644 // is passed into the function.  Simply print it out
645 //
646 void AssemblyWriter::printArgument(const Argument *Arg) {
647   // Insert commas as we go... the first arg doesn't get a comma
648   if (Arg != &Arg->getParent()->afront()) Out << ", ";
649
650   // Output type...
651   printType(Arg->getType());
652   
653   // Output name, if available...
654   if (Arg->hasName())
655     Out << " %" << Arg->getName();
656   else if (Table.getValSlot(Arg) < 0)
657     Out << "<badref>";
658 }
659
660 // printBasicBlock - This member is called for each basic block in a methd.
661 //
662 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
663   if (BB->hasName()) {              // Print out the label if it exists...
664     Out << "\n" << BB->getName() << ":\t\t\t\t\t;[#uses="
665         << BB->use_size() << "]";  // Output # uses
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     Out << "\t\t\t\t\t;[#uses=" << BB->use_size() << "]";  // Output # uses
674   }
675   
676   Out << "\n";
677
678   // Output all of the instructions in the basic block...
679   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
680     printInstruction(*I);
681 }
682
683
684 // printInfoComment - Print a little comment after the instruction indicating
685 // which slot it occupies.
686 //
687 void AssemblyWriter::printInfoComment(const Value &V) {
688   if (V.getType() != Type::VoidTy) {
689     Out << "\t\t; <";
690     printType(V.getType()) << ">";
691
692     if (!V.hasName()) {
693       int Slot = Table.getValSlot(&V); // Print out the def slot taken...
694       if (Slot >= 0) Out << ":" << Slot;
695       else Out << ":<badref>";
696     }
697     Out << " [#uses=" << V.use_size() << "]";  // Output # uses
698   }
699 }
700
701 // printInstruction - This member is called for each Instruction in a methd.
702 //
703 void AssemblyWriter::printInstruction(const Instruction &I) {
704   Out << "\t";
705
706   // Print out name if it exists...
707   if (I.hasName())
708     Out << "%" << I.getName() << " = ";
709
710   // Print out the opcode...
711   Out << I.getOpcodeName();
712
713   // Print out the type of the operands...
714   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
715
716   // Special case conditional branches to swizzle the condition out to the front
717   if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
718     writeOperand(I.getOperand(2), true);
719     Out << ",";
720     writeOperand(Operand, true);
721     Out << ",";
722     writeOperand(I.getOperand(1), true);
723
724   } else if (isa<SwitchInst>(I)) {
725     // Special case switch statement to get formatting nice and correct...
726     writeOperand(Operand        , true); Out << ",";
727     writeOperand(I.getOperand(1), true); Out << " [";
728
729     for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
730       Out << "\n\t\t";
731       writeOperand(I.getOperand(op  ), true); Out << ",";
732       writeOperand(I.getOperand(op+1), true);
733     }
734     Out << "\n\t]";
735   } else if (isa<PHINode>(I)) {
736     Out << " ";
737     printType(I.getType());
738     Out << " ";
739
740     for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
741       if (op) Out << ", ";
742       Out << "[";  
743       writeOperand(I.getOperand(op  ), false); Out << ",";
744       writeOperand(I.getOperand(op+1), false); Out << " ]";
745     }
746   } else if (isa<ReturnInst>(I) && !Operand) {
747     Out << " void";
748   } else if (isa<CallInst>(I)) {
749     const PointerType *PTy = dyn_cast<PointerType>(Operand->getType());
750     const FunctionType*MTy = PTy ? dyn_cast<FunctionType>(PTy->getElementType()):0;
751     const Type      *RetTy = MTy ? MTy->getReturnType() : 0;
752
753     // If possible, print out the short form of the call instruction, but we can
754     // only do this if the first argument is a pointer to a nonvararg function,
755     // and if the value returned is not a pointer to a function.
756     //
757     if (RetTy && MTy && !MTy->isVarArg() &&
758         (!isa<PointerType>(RetTy) || 
759          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
760       Out << " "; printType(RetTy);
761       writeOperand(Operand, false);
762     } else {
763       writeOperand(Operand, true);
764     }
765     Out << "(";
766     if (I.getNumOperands() > 1) writeOperand(I.getOperand(1), true);
767     for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
768       Out << ",";
769       writeOperand(I.getOperand(op), true);
770     }
771
772     Out << " )";
773   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
774     // TODO: Should try to print out short form of the Invoke instruction
775     writeOperand(Operand, true);
776     Out << "(";
777     if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
778     for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
779       Out << ",";
780       writeOperand(I.getOperand(op), true);
781     }
782
783     Out << " )\n\t\t\tto";
784     writeOperand(II->getNormalDest(), true);
785     Out << " except";
786     writeOperand(II->getExceptionalDest(), true);
787
788   } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
789     Out << " ";
790     printType(AI->getType()->getElementType());
791     if (AI->isArrayAllocation()) {
792       Out << ",";
793       writeOperand(AI->getArraySize(), true);
794     }
795   } else if (isa<CastInst>(I)) {
796     if (Operand) writeOperand(Operand, true);
797     Out << " to ";
798     printType(I.getType());
799   } else if (Operand) {   // Print the normal way...
800
801     // PrintAllTypes - Instructions who have operands of all the same type 
802     // omit the type from all but the first operand.  If the instruction has
803     // different type operands (for example br), then they are all printed.
804     bool PrintAllTypes = false;
805     const Type *TheType = Operand->getType();
806
807     for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
808       Operand = I.getOperand(i);
809       if (Operand->getType() != TheType) {
810         PrintAllTypes = true;       // We have differing types!  Print them all!
811         break;
812       }
813     }
814
815     // Shift Left & Right print both types even for Ubyte LHS
816     if (isa<ShiftInst>(I)) PrintAllTypes = true;
817
818     if (!PrintAllTypes) {
819       Out << " ";
820       printType(I.getOperand(0)->getType());
821     }
822
823     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
824       if (i) Out << ",";
825       writeOperand(I.getOperand(i), PrintAllTypes);
826     }
827   }
828
829   printInfoComment(I);
830   Out << "\n";
831 }
832
833
834 //===----------------------------------------------------------------------===//
835 //                       External Interface declarations
836 //===----------------------------------------------------------------------===//
837
838
839 void Module::print(std::ostream &o) const {
840   SlotCalculator SlotTable(this, true);
841   AssemblyWriter W(o, SlotTable, this);
842   W.write(this);
843 }
844
845 void GlobalVariable::print(std::ostream &o) const {
846   SlotCalculator SlotTable(getParent(), true);
847   AssemblyWriter W(o, SlotTable, getParent());
848   W.write(this);
849 }
850
851 void Function::print(std::ostream &o) const {
852   SlotCalculator SlotTable(getParent(), true);
853   AssemblyWriter W(o, SlotTable, getParent());
854
855   W.write(this);
856 }
857
858 void BasicBlock::print(std::ostream &o) const {
859   SlotCalculator SlotTable(getParent(), true);
860   AssemblyWriter W(o, SlotTable, 
861                    getParent() ? getParent()->getParent() : 0);
862   W.write(this);
863 }
864
865 void Instruction::print(std::ostream &o) const {
866   const Function *F = getParent() ? getParent()->getParent() : 0;
867   SlotCalculator SlotTable(F, true);
868   AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0);
869
870   W.write(this);
871 }
872
873 void Constant::print(std::ostream &o) const {
874   if (this == 0) { o << "<null> constant value\n"; return; }
875
876   // Handle CPR's special, because they have context information...
877   if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
878     CPR->getValue()->print(o);  // Print as a global value, with context info.
879     return;
880   }
881
882   o << " " << getType()->getDescription() << " ";
883
884   map<const Type *, string> TypeTable;
885   WriteConstantInt(o, this, false, TypeTable, 0);
886 }
887
888 void Type::print(std::ostream &o) const { 
889   if (this == 0)
890     o << "<null Type>";
891   else
892     o << getDescription();
893 }
894
895 void Argument::print(std::ostream &o) const {
896   o << getType() << " " << getName();
897 }
898
899 void Value::dump() const { print(std::cerr); }
900
901 //===----------------------------------------------------------------------===//
902 //  CachedWriter Class Implementation
903 //===----------------------------------------------------------------------===//
904
905 void CachedWriter::setModule(const Module *M) {
906   delete SC; delete AW;
907   if (M) {
908     SC = new SlotCalculator(M, true);
909     AW = new AssemblyWriter(Out, *SC, M);
910   } else {
911     SC = 0; AW = 0;
912   }
913 }
914
915 CachedWriter::~CachedWriter() {
916   delete AW;
917   delete SC;
918 }
919
920 CachedWriter &CachedWriter::operator<<(const Value *V) {
921   assert(AW && SC && "CachedWriter does not have a current module!");
922   switch (V->getValueType()) {
923   case Value::ConstantVal:
924   case Value::ArgumentVal:       AW->writeOperand(V, true, true); break;
925   case Value::TypeVal:           AW->write(cast<const Type>(V)); break;
926   case Value::InstructionVal:    AW->write(cast<Instruction>(V)); break;
927   case Value::BasicBlockVal:     AW->write(cast<BasicBlock>(V)); break;
928   case Value::FunctionVal:       AW->write(cast<Function>(V)); break;
929   case Value::GlobalVariableVal: AW->write(cast<GlobalVariable>(V)); break;
930   default: Out << "<unknown value type: " << V->getValueType() << ">"; break;
931   }
932   return *this;
933 }