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