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