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