give FP stack registers names
[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/Instructions.h"
25 #include "llvm/Module.h"
26 #include "llvm/SymbolTable.h"
27 #include "llvm/Assembly/Writer.h"
28 #include "llvm/Support/CFG.h"
29 #include "Support/StringExtras.h"
30 #include "Support/STLExtras.h"
31 #include <algorithm>
32 using namespace llvm;
33
34 namespace llvm {
35
36 /// This class provides computation of slot numbers for LLVM Assembly writing.
37 /// @brief LLVM Assembly Writing Slot Computation.
38 class SlotMachine {
39
40 /// @name Types
41 /// @{
42 public:
43
44   /// @brief A mapping of Values to slot numbers
45   typedef std::map<const Value*, unsigned> ValueMap;
46   typedef std::map<const Type*, unsigned> TypeMap;
47
48   /// @brief A plane with next slot number and ValueMap
49   struct ValuePlane { 
50     unsigned next_slot;        ///< The next slot number to use
51     ValueMap map;              ///< The map of Value* -> unsigned
52     ValuePlane() { next_slot = 0; } ///< Make sure we start at 0
53   };
54
55   struct TypePlane {
56     unsigned next_slot;
57     TypeMap map;
58     TypePlane() { next_slot = 0; }
59     void clear() { map.clear(); next_slot = 0; }
60   };
61
62   /// @brief The map of planes by Type
63   typedef std::map<const Type*, ValuePlane> TypedPlanes;
64
65 /// @}
66 /// @name Constructors
67 /// @{
68 public:
69   /// @brief Construct from a module
70   SlotMachine(const Module *M );
71
72   /// @brief Construct from a function, starting out in incorp state.
73   SlotMachine(const Function *F );
74
75 /// @}
76 /// @name Accessors
77 /// @{
78 public:
79   /// Return the slot number of the specified value in it's type
80   /// plane.  Its an error to ask for something not in the SlotMachine.
81   /// Its an error to ask for a Type*
82   int getSlot(const Value *V);
83   int getSlot(const Type*Ty);
84
85   /// Determine if a Value has a slot or not
86   bool hasSlot(const Value* V);
87   bool hasSlot(const Type* Ty);
88
89 /// @}
90 /// @name Mutators
91 /// @{
92 public:
93   /// If you'd like to deal with a function instead of just a module, use 
94   /// this method to get its data into the SlotMachine.
95   void incorporateFunction(const Function *F) { TheFunction = F; }
96
97   /// After calling incorporateFunction, use this method to remove the 
98   /// most recently incorporated function from the SlotMachine. This 
99   /// will reset the state of the machine back to just the module contents.
100   void purgeFunction();
101
102 /// @}
103 /// @name Implementation Details
104 /// @{
105 private:
106   /// This function does the actual initialization.
107   inline void initialize();
108
109   /// Values can be crammed into here at will. If they haven't 
110   /// been inserted already, they get inserted, otherwise they are ignored.
111   /// Either way, the slot number for the Value* is returned.
112   unsigned createSlot(const Value *V);
113   unsigned createSlot(const Type* Ty);
114
115   /// Insert a value into the value table. Return the slot number
116   /// that it now occupies.  BadThings(TM) will happen if you insert a
117   /// Value that's already been inserted. 
118   unsigned insertValue( const Value *V );
119   unsigned insertValue( const Type* Ty);
120
121   /// Add all of the module level global variables (and their initializers)
122   /// and function declarations, but not the contents of those functions.
123   void processModule();
124
125   /// Add all of the functions arguments, basic blocks, and instructions
126   void processFunction();
127
128   SlotMachine(const SlotMachine &);  // DO NOT IMPLEMENT
129   void operator=(const SlotMachine &);  // DO NOT IMPLEMENT
130
131 /// @}
132 /// @name Data
133 /// @{
134 public:
135
136   /// @brief The module for which we are holding slot numbers
137   const Module* TheModule;
138
139   /// @brief The function for which we are holding slot numbers
140   const Function* TheFunction;
141
142   /// @brief The TypePlanes map for the module level data
143   TypedPlanes mMap;
144   TypePlane mTypes;
145
146   /// @brief The TypePlanes map for the function level data
147   TypedPlanes fMap;
148   TypePlane fTypes;
149
150 /// @}
151
152 };
153
154 }  // end namespace llvm
155
156 static RegisterPass<PrintModulePass>
157 X("printm", "Print module to stderr",PassInfo::Analysis|PassInfo::Optimization);
158 static RegisterPass<PrintFunctionPass>
159 Y("print","Print function to stderr",PassInfo::Analysis|PassInfo::Optimization);
160
161 static void WriteAsOperandInternal(std::ostream &Out, const Value *V, 
162                                    bool PrintName,
163                                  std::map<const Type *, std::string> &TypeTable,
164                                    SlotMachine *Machine);
165
166 static void WriteAsOperandInternal(std::ostream &Out, const Type *T, 
167                                    bool PrintName,
168                                  std::map<const Type *, std::string> &TypeTable,
169                                    SlotMachine *Machine);
170
171 static const Module *getModuleFromVal(const Value *V) {
172   if (const Argument *MA = dyn_cast<Argument>(V))
173     return MA->getParent() ? MA->getParent()->getParent() : 0;
174   else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
175     return BB->getParent() ? BB->getParent()->getParent() : 0;
176   else if (const Instruction *I = dyn_cast<Instruction>(V)) {
177     const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
178     return M ? M->getParent() : 0;
179   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
180     return GV->getParent();
181   return 0;
182 }
183
184 static SlotMachine *createSlotMachine(const Value *V) {
185   if (const Argument *FA = dyn_cast<Argument>(V)) {
186     return new SlotMachine(FA->getParent());
187   } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
188     return new SlotMachine(I->getParent()->getParent());
189   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
190     return new SlotMachine(BB->getParent());
191   } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
192     return new SlotMachine(GV->getParent());
193   } else if (const Function *Func = dyn_cast<Function>(V)) {
194     return new SlotMachine(Func);
195   }
196   return 0;
197 }
198
199 // getLLVMName - Turn the specified string into an 'LLVM name', which is either
200 // prefixed with % (if the string only contains simple characters) or is
201 // surrounded with ""'s (if it has special chars in it).
202 static std::string getLLVMName(const std::string &Name) {
203   assert(!Name.empty() && "Cannot get empty name!");
204
205   // First character cannot start with a number...
206   if (Name[0] >= '0' && Name[0] <= '9')
207     return "\"" + Name + "\"";
208
209   // Scan to see if we have any characters that are not on the "white list"
210   for (unsigned i = 0, e = Name.size(); i != e; ++i) {
211     char C = Name[i];
212     assert(C != '"' && "Illegal character in LLVM value name!");
213     if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
214         C != '-' && C != '.' && C != '_')
215       return "\"" + Name + "\"";
216   }
217   
218   // If we get here, then the identifier is legal to use as a "VarID".
219   return "%"+Name;
220 }
221
222
223 /// fillTypeNameTable - If the module has a symbol table, take all global types
224 /// and stuff their names into the TypeNames map.
225 ///
226 static void fillTypeNameTable(const Module *M,
227                               std::map<const Type *, std::string> &TypeNames) {
228   if (!M) return;
229   const SymbolTable &ST = M->getSymbolTable();
230   SymbolTable::type_const_iterator TI = ST.type_begin();
231   for (; TI != ST.type_end(); ++TI ) {
232     // As a heuristic, don't insert pointer to primitive types, because
233     // they are used too often to have a single useful name.
234     //
235     const Type *Ty = cast<Type>(TI->second);
236     if (!isa<PointerType>(Ty) ||
237         !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
238         isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
239       TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first)));
240   }
241 }
242
243
244
245 static void calcTypeName(const Type *Ty, 
246                          std::vector<const Type *> &TypeStack,
247                          std::map<const Type *, std::string> &TypeNames,
248                          std::string & Result){
249   if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)) {
250     Result += Ty->getDescription();  // Base case
251     return;
252   }
253
254   // Check to see if the type is named.
255   std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
256   if (I != TypeNames.end()) {
257     Result += I->second;
258     return;
259   }
260
261   if (isa<OpaqueType>(Ty)) {
262     Result += "opaque";
263     return;
264   }
265
266   // Check to see if the Type is already on the stack...
267   unsigned Slot = 0, CurSize = TypeStack.size();
268   while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
269
270   // This is another base case for the recursion.  In this case, we know 
271   // that we have looped back to a type that we have previously visited.
272   // Generate the appropriate upreference to handle this.
273   if (Slot < CurSize) {
274     Result += "\\" + utostr(CurSize-Slot);     // Here's the upreference
275     return;
276   }
277
278   TypeStack.push_back(Ty);    // Recursive case: Add us to the stack..
279   
280   switch (Ty->getTypeID()) {
281   case Type::FunctionTyID: {
282     const FunctionType *FTy = cast<FunctionType>(Ty);
283     calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
284     Result += " (";
285     for (FunctionType::param_iterator I = FTy->param_begin(),
286            E = FTy->param_end(); I != E; ++I) {
287       if (I != FTy->param_begin())
288         Result += ", ";
289       calcTypeName(*I, TypeStack, TypeNames, Result);
290     }
291     if (FTy->isVarArg()) {
292       if (FTy->getNumParams()) Result += ", ";
293       Result += "...";
294     }
295     Result += ")";
296     break;
297   }
298   case Type::StructTyID: {
299     const StructType *STy = cast<StructType>(Ty);
300     Result += "{ ";
301     for (StructType::element_iterator I = STy->element_begin(),
302            E = STy->element_end(); I != E; ++I) {
303       if (I != STy->element_begin())
304         Result += ", ";
305       calcTypeName(*I, TypeStack, TypeNames, Result);
306     }
307     Result += " }";
308     break;
309   }
310   case Type::PointerTyID:
311     calcTypeName(cast<PointerType>(Ty)->getElementType(), 
312                           TypeStack, TypeNames, Result);
313     Result += "*";
314     break;
315   case Type::ArrayTyID: {
316     const ArrayType *ATy = cast<ArrayType>(Ty);
317     Result += "[" + utostr(ATy->getNumElements()) + " x ";
318     calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
319     Result += "]";
320     break;
321   }
322   case Type::OpaqueTyID:
323     Result += "opaque";
324     break;
325   default:
326     Result += "<unrecognized-type>";
327   }
328
329   TypeStack.pop_back();       // Remove self from stack...
330   return;
331 }
332
333
334 /// printTypeInt - The internal guts of printing out a type that has a
335 /// potentially named portion.
336 ///
337 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
338                               std::map<const Type *, std::string> &TypeNames) {
339   // Primitive types always print out their description, regardless of whether
340   // they have been named or not.
341   //
342   if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
343     return Out << Ty->getDescription();
344
345   // Check to see if the type is named.
346   std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
347   if (I != TypeNames.end()) return Out << I->second;
348
349   // Otherwise we have a type that has not been named but is a derived type.
350   // Carefully recurse the type hierarchy to print out any contained symbolic
351   // names.
352   //
353   std::vector<const Type *> TypeStack;
354   std::string TypeName;
355   calcTypeName(Ty, TypeStack, TypeNames, TypeName);
356   TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
357   return (Out << TypeName);
358 }
359
360
361 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
362 /// type, iff there is an entry in the modules symbol table for the specified
363 /// type or one of it's component types. This is slower than a simple x << Type
364 ///
365 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
366                                       const Module *M) {
367   Out << ' '; 
368
369   // If they want us to print out a type, attempt to make it symbolic if there
370   // is a symbol table in the module...
371   if (M) {
372     std::map<const Type *, std::string> TypeNames;
373     fillTypeNameTable(M, TypeNames);
374     
375     return printTypeInt(Out, Ty, TypeNames);
376   } else {
377     return Out << Ty->getDescription();
378   }
379 }
380
381 /// @brief Internal constant writer. 
382 static void WriteConstantInt(std::ostream &Out, const Constant *CV, 
383                              bool PrintName,
384                              std::map<const Type *, std::string> &TypeTable,
385                              SlotMachine *Machine) {
386   if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
387     Out << (CB == ConstantBool::True ? "true" : "false");
388   } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
389     Out << CI->getValue();
390   } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
391     Out << CI->getValue();
392   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
393     // We would like to output the FP constant value in exponential notation,
394     // but we cannot do this if doing so will lose precision.  Check here to
395     // make sure that we only output it in exponential format if we can parse
396     // the value back and get the same value.
397     //
398     std::string StrVal = ftostr(CFP->getValue());
399
400     // Check to make sure that the stringized number is not some string like
401     // "Inf" or NaN, that atof will accept, but the lexer will not.  Check that
402     // the string matches the "[-+]?[0-9]" regex.
403     //
404     if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
405         ((StrVal[0] == '-' || StrVal[0] == '+') &&
406          (StrVal[1] >= '0' && StrVal[1] <= '9')))
407       // Reparse stringized version!
408       if (atof(StrVal.c_str()) == CFP->getValue()) {
409         Out << StrVal; return;
410       }
411     
412     // Otherwise we could not reparse it to exactly the same value, so we must
413     // output the string in hexadecimal format!
414     //
415     // Behave nicely in the face of C TBAA rules... see:
416     // http://www.nullstone.com/htmls/category/aliastyp.htm
417     //
418     double Val = CFP->getValue();
419     char *Ptr = (char*)&Val;
420     assert(sizeof(double) == sizeof(uint64_t) && sizeof(double) == 8 &&
421            "assuming that double is 64 bits!");
422     Out << "0x" << utohexstr(*(uint64_t*)Ptr);
423
424   } else if (isa<ConstantAggregateZero>(CV)) {
425     Out << "zeroinitializer";
426   } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
427     // As a special case, print the array as a string if it is an array of
428     // ubytes or an array of sbytes with positive values.
429     // 
430     const Type *ETy = CA->getType()->getElementType();
431     bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
432
433     if (ETy == Type::SByteTy)
434       for (unsigned i = 0; i < CA->getNumOperands(); ++i)
435         if (cast<ConstantSInt>(CA->getOperand(i))->getValue() < 0) {
436           isString = false;
437           break;
438         }
439
440     if (isString) {
441       Out << "c\"";
442       for (unsigned i = 0; i < CA->getNumOperands(); ++i) {
443         unsigned char C = 
444           (unsigned char)cast<ConstantInt>(CA->getOperand(i))->getRawValue();
445         
446         if (isprint(C) && C != '"' && C != '\\') {
447           Out << C;
448         } else {
449           Out << '\\'
450               << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
451               << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
452         }
453       }
454       Out << "\"";
455
456     } else {                // Cannot output in string format...
457       Out << '[';
458       if (CA->getNumOperands()) {
459         Out << ' ';
460         printTypeInt(Out, ETy, TypeTable);
461         WriteAsOperandInternal(Out, CA->getOperand(0),
462                                PrintName, TypeTable, Machine);
463         for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
464           Out << ", ";
465           printTypeInt(Out, ETy, TypeTable);
466           WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
467                                  TypeTable, Machine);
468         }
469       }
470       Out << " ]";
471     }
472   } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
473     Out << '{';
474     if (CS->getNumOperands()) {
475       Out << ' ';
476       printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
477
478       WriteAsOperandInternal(Out, CS->getOperand(0),
479                              PrintName, TypeTable, Machine);
480
481       for (unsigned i = 1; i < CS->getNumOperands(); i++) {
482         Out << ", ";
483         printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
484
485         WriteAsOperandInternal(Out, CS->getOperand(i),
486                                PrintName, TypeTable, Machine);
487       }
488     }
489
490     Out << " }";
491   } else if (isa<ConstantPointerNull>(CV)) {
492     Out << "null";
493
494   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
495     Out << CE->getOpcodeName() << " (";
496     
497     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
498       printTypeInt(Out, (*OI)->getType(), TypeTable);
499       WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Machine);
500       if (OI+1 != CE->op_end())
501         Out << ", ";
502     }
503     
504     if (CE->getOpcode() == Instruction::Cast) {
505       Out << " to ";
506       printTypeInt(Out, CE->getType(), TypeTable);
507     }
508     Out << ')';
509
510   } else {
511     Out << "<placeholder or erroneous Constant>";
512   }
513 }
514
515
516 /// WriteAsOperand - Write the name of the specified value out to the specified
517 /// ostream.  This can be useful when you just want to print int %reg126, not
518 /// the whole instruction that generated it.
519 ///
520 static void WriteAsOperandInternal(std::ostream &Out, const Value *V, 
521                                    bool PrintName,
522                                   std::map<const Type*, std::string> &TypeTable,
523                                    SlotMachine *Machine) {
524   Out << ' ';
525   if ((PrintName || isa<GlobalValue>(V)) && V->hasName())
526     Out << getLLVMName(V->getName());
527   else {
528     const Constant *CV = dyn_cast<Constant>(V);
529     if (CV && !isa<GlobalValue>(CV))
530       WriteConstantInt(Out, CV, PrintName, TypeTable, Machine);
531     else {
532       int Slot;
533       if (Machine) {
534         Slot = Machine->getSlot(V);
535       } else {
536         Machine = createSlotMachine(V);
537         if (Machine == 0) 
538           Slot = Machine->getSlot(V);
539         else
540           Slot = -1;
541         delete Machine;
542       }
543       if (Slot != -1)
544         Out << '%' << Slot;
545       else
546         Out << "<badref>";
547     }
548   }
549 }
550
551 /// WriteAsOperand - Write the name of the specified value out to the specified
552 /// ostream.  This can be useful when you just want to print int %reg126, not
553 /// the whole instruction that generated it.
554 ///
555 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
556                                    bool PrintType, bool PrintName, 
557                                    const Module *Context) {
558   std::map<const Type *, std::string> TypeNames;
559   if (Context == 0) Context = getModuleFromVal(V);
560
561   if (Context)
562     fillTypeNameTable(Context, TypeNames);
563
564   if (PrintType)
565     printTypeInt(Out, V->getType(), TypeNames);
566   
567   WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
568   return Out;
569 }
570
571 /// WriteAsOperandInternal - Write the name of the specified value out to 
572 /// the specified ostream.  This can be useful when you just want to print 
573 /// int %reg126, not the whole instruction that generated it.
574 ///
575 static void WriteAsOperandInternal(std::ostream &Out, const Type *T, 
576                                    bool PrintName,
577                                   std::map<const Type*, std::string> &TypeTable,
578                                    SlotMachine *Machine) {
579   Out << ' ';
580   int Slot;
581   if (Machine) {
582     Slot = Machine->getSlot(T);
583     if (Slot != -1)
584       Out << '%' << Slot;
585     else
586       Out << "<badref>";
587   } else {
588     Out << T->getDescription();
589   }
590 }
591
592 /// WriteAsOperand - Write the name of the specified value out to the specified
593 /// ostream.  This can be useful when you just want to print int %reg126, not
594 /// the whole instruction that generated it.
595 ///
596 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Type *Ty,
597                                    bool PrintType, bool PrintName, 
598                                    const Module *Context) {
599   std::map<const Type *, std::string> TypeNames;
600   assert(Context != 0 && "Can't write types as operand without module context");
601
602   fillTypeNameTable(Context, TypeNames);
603
604   // if (PrintType)
605     // printTypeInt(Out, V->getType(), TypeNames);
606   
607   printTypeInt(Out, Ty, TypeNames);
608
609   WriteAsOperandInternal(Out, Ty, PrintName, TypeNames, 0);
610   return Out;
611 }
612
613 namespace llvm {
614
615 class AssemblyWriter {
616   std::ostream &Out;
617   SlotMachine &Machine;
618   const Module *TheModule;
619   std::map<const Type *, std::string> TypeNames;
620   AssemblyAnnotationWriter *AnnotationWriter;
621 public:
622   inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
623                         AssemblyAnnotationWriter *AAW)
624     : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
625
626     // If the module has a symbol table, take all global types and stuff their
627     // names into the TypeNames map.
628     //
629     fillTypeNameTable(M, TypeNames);
630   }
631
632   inline void write(const Module *M)         { printModule(M);      }
633   inline void write(const GlobalVariable *G) { printGlobal(G);      }
634   inline void write(const Function *F)       { printFunction(F);    }
635   inline void write(const BasicBlock *BB)    { printBasicBlock(BB); }
636   inline void write(const Instruction *I)    { printInstruction(*I); }
637   inline void write(const Constant *CPV)     { printConstant(CPV);  }
638   inline void write(const Type *Ty)          { printType(Ty);       }
639
640   void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
641
642   const Module* getModule() { return TheModule; }
643
644 private :
645   void printModule(const Module *M);
646   void printSymbolTable(const SymbolTable &ST);
647   void printConstant(const Constant *CPV);
648   void printGlobal(const GlobalVariable *GV);
649   void printFunction(const Function *F);
650   void printArgument(const Argument *FA);
651   void printBasicBlock(const BasicBlock *BB);
652   void printInstruction(const Instruction &I);
653
654   // printType - Go to extreme measures to attempt to print out a short,
655   // symbolic version of a type name.
656   //
657   std::ostream &printType(const Type *Ty) {
658     return printTypeInt(Out, Ty, TypeNames);
659   }
660
661   // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
662   // without considering any symbolic types that we may have equal to it.
663   //
664   std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
665
666   // printInfoComment - Print a little comment after the instruction indicating
667   // which slot it occupies.
668   void printInfoComment(const Value &V);
669 };
670 }  // end of llvm namespace
671
672 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
673 /// without considering any symbolic types that we may have equal to it.
674 ///
675 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
676   if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
677     printType(FTy->getReturnType()) << " (";
678     for (FunctionType::param_iterator I = FTy->param_begin(),
679            E = FTy->param_end(); I != E; ++I) {
680       if (I != FTy->param_begin())
681         Out << ", ";
682       printType(*I);
683     }
684     if (FTy->isVarArg()) {
685       if (FTy->getNumParams()) Out << ", ";
686       Out << "...";
687     }
688     Out << ')';
689   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
690     Out << "{ ";
691     for (StructType::element_iterator I = STy->element_begin(),
692            E = STy->element_end(); I != E; ++I) {
693       if (I != STy->element_begin())
694         Out << ", ";
695       printType(*I);
696     }
697     Out << " }";
698   } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
699     printType(PTy->getElementType()) << '*';
700   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
701     Out << '[' << ATy->getNumElements() << " x ";
702     printType(ATy->getElementType()) << ']';
703   } else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
704     Out << "opaque";
705   } else {
706     if (!Ty->isPrimitiveType())
707       Out << "<unknown derived type>";
708     printType(Ty);
709   }
710   return Out;
711 }
712
713
714 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType, 
715                                   bool PrintName) {
716   if (PrintType) { Out << ' '; printType(Operand->getType()); }
717   WriteAsOperandInternal(Out, Operand, PrintName, TypeNames, &Machine);
718 }
719
720
721 void AssemblyWriter::printModule(const Module *M) {
722   switch (M->getEndianness()) {
723   case Module::LittleEndian: Out << "target endian = little\n"; break;
724   case Module::BigEndian:    Out << "target endian = big\n";    break;
725   case Module::AnyEndianness: break;
726   }
727   switch (M->getPointerSize()) {
728   case Module::Pointer32:    Out << "target pointersize = 32\n"; break;
729   case Module::Pointer64:    Out << "target pointersize = 64\n"; break;
730   case Module::AnyPointerSize: break;
731   }
732   if (!M->getTargetTriple().empty())
733     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
734   
735   // Loop over the dependent libraries and emit them
736   Module::lib_iterator LI= M->lib_begin();
737   Module::lib_iterator LE= M->lib_end();
738   if (LI != LE) {
739     Out << "deplibs = [\n";
740     while ( LI != LE ) {
741       Out << "\"" << *LI << "\"";
742       ++LI;
743       if ( LI != LE )
744         Out << ",\n";
745     }
746     Out << " ]\n";
747   }
748   
749   // Loop over the symbol table, emitting all named constants...
750   printSymbolTable(M->getSymbolTable());
751   
752   for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
753     printGlobal(I);
754
755   Out << "\nimplementation   ; Functions:\n";
756   
757   // Output all of the functions...
758   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
759     printFunction(I);
760 }
761
762 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
763   if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
764
765   if (!GV->hasInitializer()) 
766     Out << "external ";
767   else
768     switch (GV->getLinkage()) {
769     case GlobalValue::InternalLinkage:  Out << "internal "; break;
770     case GlobalValue::LinkOnceLinkage:  Out << "linkonce "; break;
771     case GlobalValue::WeakLinkage:      Out << "weak "; break;
772     case GlobalValue::AppendingLinkage: Out << "appending "; break;
773     case GlobalValue::ExternalLinkage: break;
774     }
775
776   Out << (GV->isConstant() ? "constant " : "global ");
777   printType(GV->getType()->getElementType());
778
779   if (GV->hasInitializer()) {
780     Constant* C = cast<Constant>(GV->getInitializer());
781     assert(C &&  "GlobalVar initializer isn't constant?");
782     writeOperand(GV->getInitializer(), false, isa<GlobalValue>(C));
783   }
784
785   printInfoComment(*GV);
786   Out << "\n";
787 }
788
789
790 // printSymbolTable - Run through symbol table looking for constants
791 // and types. Emit their declarations.
792 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
793
794   // Print the types.
795   for (SymbolTable::type_const_iterator TI = ST.type_begin();
796        TI != ST.type_end(); ++TI ) {
797     Out << "\t" << getLLVMName(TI->first) << " = type ";
798
799     // Make sure we print out at least one level of the type structure, so
800     // that we do not get %FILE = type %FILE
801     //
802     printTypeAtLeastOneLevel(TI->second) << "\n";
803   }
804     
805   // Print the constants, in type plane order.
806   for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
807        PI != ST.plane_end(); ++PI ) {
808     SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
809     SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
810
811     for (; VI != VE; ++VI) {
812       const Value* V = VI->second;
813       const Constant *CPV = dyn_cast<Constant>(V) ;
814       if (CPV && !isa<GlobalValue>(V)) {
815         printConstant(CPV);
816       }
817     }
818   }
819 }
820
821
822 /// printConstant - Print out a constant pool entry...
823 ///
824 void AssemblyWriter::printConstant(const Constant *CPV) {
825   // Don't print out unnamed constants, they will be inlined
826   if (!CPV->hasName()) return;
827
828   // Print out name...
829   Out << "\t" << getLLVMName(CPV->getName()) << " =";
830
831   // Write the value out now...
832   writeOperand(CPV, true, false);
833
834   printInfoComment(*CPV);
835   Out << "\n";
836 }
837
838 /// printFunction - Print all aspects of a function.
839 ///
840 void AssemblyWriter::printFunction(const Function *F) {
841   // Print out the return type and name...
842   Out << "\n";
843
844   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
845
846   if (F->isExternal())
847     Out << "declare ";
848   else
849     switch (F->getLinkage()) {
850     case GlobalValue::InternalLinkage:  Out << "internal "; break;
851     case GlobalValue::LinkOnceLinkage:  Out << "linkonce "; break;
852     case GlobalValue::WeakLinkage:      Out << "weak "; break;
853     case GlobalValue::AppendingLinkage: Out << "appending "; break;
854     case GlobalValue::ExternalLinkage: break;
855     }
856
857   printType(F->getReturnType()) << ' ';
858   if (!F->getName().empty())
859     Out << getLLVMName(F->getName());
860   else
861     Out << "\"\"";
862   Out << '(';
863   Machine.incorporateFunction(F);
864
865   // Loop over the arguments, printing them...
866   const FunctionType *FT = F->getFunctionType();
867
868   for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
869     printArgument(I);
870
871   // Finish printing arguments...
872   if (FT->isVarArg()) {
873     if (FT->getNumParams()) Out << ", ";
874     Out << "...";  // Output varargs portion of signature!
875   }
876   Out << ')';
877
878   if (F->isExternal()) {
879     Out << "\n";
880   } else {
881     Out << " {";
882   
883     // Output all of its basic blocks... for the function
884     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
885       printBasicBlock(I);
886
887     Out << "}\n";
888   }
889
890   Machine.purgeFunction();
891 }
892
893 /// printArgument - This member is called for every argument that is passed into
894 /// the function.  Simply print it out
895 ///
896 void AssemblyWriter::printArgument(const Argument *Arg) {
897   // Insert commas as we go... the first arg doesn't get a comma
898   if (Arg != &Arg->getParent()->afront()) Out << ", ";
899
900   // Output type...
901   printType(Arg->getType());
902   
903   // Output name, if available...
904   if (Arg->hasName())
905     Out << ' ' << getLLVMName(Arg->getName());
906 }
907
908 /// printBasicBlock - This member is called for each basic block in a method.
909 ///
910 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
911   if (BB->hasName()) {              // Print out the label if it exists...
912     Out << "\n" << BB->getName() << ':';
913   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
914     Out << "\n; <label>:";
915     int Slot = Machine.getSlot(BB);
916     if (Slot != -1)
917       Out << Slot;
918     else
919       Out << "<badref>";
920   }
921
922   if (BB->getParent() == 0)
923     Out << "\t\t; Error: Block without parent!";
924   else {
925     if (BB != &BB->getParent()->front()) {  // Not the entry block?
926       // Output predecessors for the block...
927       Out << "\t\t;";
928       pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
929       
930       if (PI == PE) {
931         Out << " No predecessors!";
932       } else {
933         Out << " preds =";
934         writeOperand(*PI, false, true);
935         for (++PI; PI != PE; ++PI) {
936           Out << ',';
937           writeOperand(*PI, false, true);
938         }
939       }
940     }
941   }
942   
943   Out << "\n";
944
945   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
946
947   // Output all of the instructions in the basic block...
948   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
949     printInstruction(*I);
950
951   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
952 }
953
954
955 /// printInfoComment - Print a little comment after the instruction indicating
956 /// which slot it occupies.
957 ///
958 void AssemblyWriter::printInfoComment(const Value &V) {
959   if (V.getType() != Type::VoidTy) {
960     Out << "\t\t; <";
961     printType(V.getType()) << '>';
962
963     if (!V.hasName()) {
964       int SlotNum = Machine.getSlot(&V);
965       if (SlotNum == -1)
966         Out << ":<badref>";
967       else
968         Out << ':' << SlotNum; // Print out the def slot taken.
969     }
970     Out << " [#uses=" << V.use_size() << ']';  // Output # uses
971   }
972 }
973
974 /// printInstruction - This member is called for each Instruction in a function..
975 ///
976 void AssemblyWriter::printInstruction(const Instruction &I) {
977   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
978
979   Out << "\t";
980
981   // Print out name if it exists...
982   if (I.hasName())
983     Out << getLLVMName(I.getName()) << " = ";
984
985   // If this is a volatile load or store, print out the volatile marker
986   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
987       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()))
988       Out << "volatile ";
989
990   // Print out the opcode...
991   Out << I.getOpcodeName();
992
993   // Print out the type of the operands...
994   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
995
996   // Special case conditional branches to swizzle the condition out to the front
997   if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
998     writeOperand(I.getOperand(2), true);
999     Out << ',';
1000     writeOperand(Operand, true);
1001     Out << ',';
1002     writeOperand(I.getOperand(1), true);
1003
1004   } else if (isa<SwitchInst>(I)) {
1005     // Special case switch statement to get formatting nice and correct...
1006     writeOperand(Operand        , true); Out << ',';
1007     writeOperand(I.getOperand(1), true); Out << " [";
1008
1009     for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1010       Out << "\n\t\t";
1011       writeOperand(I.getOperand(op  ), true); Out << ',';
1012       writeOperand(I.getOperand(op+1), true);
1013     }
1014     Out << "\n\t]";
1015   } else if (isa<PHINode>(I)) {
1016     Out << ' ';
1017     printType(I.getType());
1018     Out << ' ';
1019
1020     for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1021       if (op) Out << ", ";
1022       Out << '[';  
1023       writeOperand(I.getOperand(op  ), false); Out << ',';
1024       writeOperand(I.getOperand(op+1), false); Out << " ]";
1025     }
1026   } else if (isa<ReturnInst>(I) && !Operand) {
1027     Out << " void";
1028   } else if (isa<CallInst>(I)) {
1029     const PointerType  *PTy = cast<PointerType>(Operand->getType());
1030     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1031     const Type       *RetTy = FTy->getReturnType();
1032
1033     // If possible, print out the short form of the call instruction.  We can
1034     // only do this if the first argument is a pointer to a nonvararg function,
1035     // and if the return type is not a pointer to a function.
1036     //
1037     if (!FTy->isVarArg() &&
1038         (!isa<PointerType>(RetTy) || 
1039          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1040       Out << ' '; printType(RetTy);
1041       writeOperand(Operand, false);
1042     } else {
1043       writeOperand(Operand, true);
1044     }
1045     Out << '(';
1046     if (I.getNumOperands() > 1) writeOperand(I.getOperand(1), true);
1047     for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
1048       Out << ',';
1049       writeOperand(I.getOperand(op), true);
1050     }
1051
1052     Out << " )";
1053   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1054     const PointerType  *PTy = cast<PointerType>(Operand->getType());
1055     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1056     const Type       *RetTy = FTy->getReturnType();
1057
1058     // If possible, print out the short form of the invoke instruction. We can
1059     // only do this if the first argument is a pointer to a nonvararg function,
1060     // and if the return type is not a pointer to a function.
1061     //
1062     if (!FTy->isVarArg() &&
1063         (!isa<PointerType>(RetTy) || 
1064          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1065       Out << ' '; printType(RetTy);
1066       writeOperand(Operand, false);
1067     } else {
1068       writeOperand(Operand, true);
1069     }
1070
1071     Out << '(';
1072     if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
1073     for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
1074       Out << ',';
1075       writeOperand(I.getOperand(op), true);
1076     }
1077
1078     Out << " )\n\t\t\tto";
1079     writeOperand(II->getNormalDest(), true);
1080     Out << " unwind";
1081     writeOperand(II->getUnwindDest(), true);
1082
1083   } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1084     Out << ' ';
1085     printType(AI->getType()->getElementType());
1086     if (AI->isArrayAllocation()) {
1087       Out << ',';
1088       writeOperand(AI->getArraySize(), true);
1089     }
1090   } else if (isa<CastInst>(I)) {
1091     if (Operand) writeOperand(Operand, true);   // Work with broken code
1092     Out << " to ";
1093     printType(I.getType());
1094   } else if (isa<VAArgInst>(I)) {
1095     if (Operand) writeOperand(Operand, true);   // Work with broken code
1096     Out << ", ";
1097     printType(I.getType());
1098   } else if (const VANextInst *VAN = dyn_cast<VANextInst>(&I)) {
1099     if (Operand) writeOperand(Operand, true);   // Work with broken code
1100     Out << ", ";
1101     printType(VAN->getArgType());
1102   } else if (Operand) {   // Print the normal way...
1103
1104     // PrintAllTypes - Instructions who have operands of all the same type 
1105     // omit the type from all but the first operand.  If the instruction has
1106     // different type operands (for example br), then they are all printed.
1107     bool PrintAllTypes = false;
1108     const Type *TheType = Operand->getType();
1109
1110     // Shift Left & Right print both types even for Ubyte LHS, and select prints
1111     // types even if all operands are bools.
1112     if (isa<ShiftInst>(I) || isa<SelectInst>(I)) {
1113       PrintAllTypes = true;
1114     } else {
1115       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1116         Operand = I.getOperand(i);
1117         if (Operand->getType() != TheType) {
1118           PrintAllTypes = true;    // We have differing types!  Print them all!
1119           break;
1120         }
1121       }
1122     }
1123     
1124     if (!PrintAllTypes) {
1125       Out << ' ';
1126       printType(TheType);
1127     }
1128
1129     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1130       if (i) Out << ',';
1131       writeOperand(I.getOperand(i), PrintAllTypes);
1132     }
1133   }
1134
1135   printInfoComment(I);
1136   Out << "\n";
1137 }
1138
1139
1140 //===----------------------------------------------------------------------===//
1141 //                       External Interface declarations
1142 //===----------------------------------------------------------------------===//
1143
1144 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1145   SlotMachine SlotTable(this);
1146   AssemblyWriter W(o, SlotTable, this, AAW);
1147   W.write(this);
1148 }
1149
1150 void GlobalVariable::print(std::ostream &o) const {
1151   SlotMachine SlotTable(getParent());
1152   AssemblyWriter W(o, SlotTable, getParent(), 0);
1153   W.write(this);
1154 }
1155
1156 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1157   SlotMachine SlotTable(getParent());
1158   AssemblyWriter W(o, SlotTable, getParent(), AAW);
1159
1160   W.write(this);
1161 }
1162
1163 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1164   SlotMachine SlotTable(getParent());
1165   AssemblyWriter W(o, SlotTable, 
1166                    getParent() ? getParent()->getParent() : 0, AAW);
1167   W.write(this);
1168 }
1169
1170 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1171   const Function *F = getParent() ? getParent()->getParent() : 0;
1172   SlotMachine SlotTable(F);
1173   AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1174
1175   W.write(this);
1176 }
1177
1178 void Constant::print(std::ostream &o) const {
1179   if (this == 0) { o << "<null> constant value\n"; return; }
1180
1181   o << ' ' << getType()->getDescription() << ' ';
1182
1183   std::map<const Type *, std::string> TypeTable;
1184   WriteConstantInt(o, this, false, TypeTable, 0);
1185 }
1186
1187 void Type::print(std::ostream &o) const { 
1188   if (this == 0)
1189     o << "<null Type>";
1190   else
1191     o << getDescription();
1192 }
1193
1194 void Argument::print(std::ostream &o) const {
1195   WriteAsOperand(o, this, true, true,
1196                  getParent() ? getParent()->getParent() : 0);
1197 }
1198
1199 // Value::dump - allow easy printing of  Values from the debugger.
1200 // Located here because so much of the needed functionality is here.
1201 void Value::dump() const { print(std::cerr); }
1202
1203 // Type::dump - allow easy printing of  Values from the debugger.
1204 // Located here because so much of the needed functionality is here.
1205 void Type::dump() const { print(std::cerr); }
1206
1207 //===----------------------------------------------------------------------===//
1208 //  CachedWriter Class Implementation
1209 //===----------------------------------------------------------------------===//
1210
1211 void CachedWriter::setModule(const Module *M) {
1212   delete SC; delete AW;
1213   if (M) {
1214     SC = new SlotMachine(M );
1215     AW = new AssemblyWriter(Out, *SC, M, 0);
1216   } else {
1217     SC = 0; AW = 0;
1218   }
1219 }
1220
1221 CachedWriter::~CachedWriter() {
1222   delete AW;
1223   delete SC;
1224 }
1225
1226 CachedWriter &CachedWriter::operator<<(const Value &V) {
1227   assert(AW && SC && "CachedWriter does not have a current module!");
1228   if (const Instruction *I = dyn_cast<Instruction>(&V))
1229     AW->write(I);
1230   else if (const BasicBlock *BB = dyn_cast<BasicBlock>(&V))
1231     AW->write(BB);
1232   else if (const Function *F = dyn_cast<Function>(&V))
1233     AW->write(F);
1234   else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(&V))
1235     AW->write(GV);
1236   else 
1237     AW->writeOperand(&V, true, true);
1238   return *this;
1239 }
1240
1241 CachedWriter& CachedWriter::operator<<(const Type &Ty) {
1242   if (SymbolicTypes) {
1243     const Module *M = AW->getModule();
1244     if (M) WriteTypeSymbolic(Out, &Ty, M);
1245   } else {
1246     AW->write(&Ty);
1247   }
1248   return *this;
1249 }
1250
1251 //===----------------------------------------------------------------------===//
1252 //===--                    SlotMachine Implementation
1253 //===----------------------------------------------------------------------===//
1254
1255 #if 0
1256 #define SC_DEBUG(X) std::cerr << X
1257 #else
1258 #define SC_DEBUG(X)
1259 #endif
1260
1261 // Module level constructor. Causes the contents of the Module (sans functions)
1262 // to be added to the slot table.
1263 SlotMachine::SlotMachine(const Module *M) 
1264   : TheModule(M)    ///< Saved for lazy initialization.
1265   , TheFunction(0)
1266   , mMap()
1267   , mTypes()
1268   , fMap()
1269   , fTypes()
1270 {
1271 }
1272
1273 // Function level constructor. Causes the contents of the Module and the one
1274 // function provided to be added to the slot table.
1275 SlotMachine::SlotMachine(const Function *F ) 
1276   : TheModule( F ? F->getParent() : 0 ) ///< Saved for lazy initialization
1277   , TheFunction(F) ///< Saved for lazy initialization
1278   , mMap()
1279   , mTypes()
1280   , fMap()
1281   , fTypes()
1282 {
1283 }
1284
1285 inline void SlotMachine::initialize(void) {
1286   if ( TheModule) { 
1287     processModule(); 
1288     TheModule = 0; ///< Prevent re-processing next time we're called.
1289   }
1290   if ( TheFunction ) { 
1291     processFunction(); 
1292   }
1293 }
1294
1295 // Iterate through all the global variables, functions, and global
1296 // variable initializers and create slots for them. 
1297 void SlotMachine::processModule() {
1298   SC_DEBUG("begin processModule!\n");
1299
1300   // Add all of the global variables to the value table...
1301   for (Module::const_giterator I = TheModule->gbegin(), E = TheModule->gend();
1302        I != E; ++I)
1303     createSlot(I);
1304
1305   // Add all the functions to the table
1306   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1307        I != E; ++I)
1308     createSlot(I);
1309
1310   SC_DEBUG("end processModule!\n");
1311 }
1312
1313
1314 // Process the arguments, basic blocks, and instructions  of a function.
1315 void SlotMachine::processFunction() {
1316   SC_DEBUG("begin processFunction!\n");
1317
1318   // Add all the function arguments
1319   for(Function::const_aiterator AI = TheFunction->abegin(), 
1320       AE = TheFunction->aend(); AI != AE; ++AI)
1321     createSlot(AI);
1322
1323   SC_DEBUG("Inserting Instructions:\n");
1324
1325   // Add all of the basic blocks and instructions
1326   for (Function::const_iterator BB = TheFunction->begin(), 
1327        E = TheFunction->end(); BB != E; ++BB) {
1328     createSlot(BB);
1329     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1330       createSlot(I);
1331     }
1332   }
1333
1334   SC_DEBUG("end processFunction!\n");
1335 }
1336
1337 // Clean up after incorporating a function. This is the only way
1338 // to get out of the function incorporation state that affects the
1339 // getSlot/createSlot lock. Function incorporation state is indicated
1340 // by TheFunction != 0.
1341 void SlotMachine::purgeFunction() {
1342   SC_DEBUG("begin purgeFunction!\n");
1343   fMap.clear(); // Simply discard the function level map
1344   fTypes.clear();
1345   TheFunction = 0;
1346   SC_DEBUG("end purgeFunction!\n");
1347 }
1348
1349 /// Get the slot number for a value. This function will assert if you
1350 /// ask for a Value that hasn't previously been inserted with createSlot.
1351 /// Types are forbidden because Type does not inherit from Value (any more).
1352 int SlotMachine::getSlot(const Value *V) {
1353   assert( V && "Can't get slot for null Value" );
1354   assert(!isa<Constant>(V) || isa<GlobalValue>(V) && 
1355     "Can't insert a non-GlobalValue Constant into SlotMachine"); 
1356
1357   // Check for uninitialized state and do lazy initialization
1358   this->initialize();
1359
1360   // Get the type of the value
1361   const Type* VTy = V->getType();
1362
1363   // Find the type plane in the module map
1364   TypedPlanes::const_iterator MI = mMap.find(VTy);
1365
1366   if ( TheFunction ) {
1367     // Lookup the type in the function map too
1368     TypedPlanes::const_iterator FI = fMap.find(VTy);
1369     // If there is a corresponding type plane in the function map
1370     if ( FI != fMap.end() ) {
1371       // Lookup the Value in the function map
1372       ValueMap::const_iterator FVI = FI->second.map.find(V);
1373       // If the value doesn't exist in the function map
1374       if ( FVI == FI->second.map.end() ) {
1375         // Look up the value in the module map.
1376         if (MI == mMap.end()) return -1;
1377         ValueMap::const_iterator MVI = MI->second.map.find(V);
1378         // If we didn't find it, it wasn't inserted
1379         if (MVI == MI->second.map.end()) return -1;
1380         assert( MVI != MI->second.map.end() && "Value not found");
1381         // We found it only at the module level
1382         return MVI->second; 
1383
1384       // else the value exists in the function map
1385       } else {
1386         // Return the slot number as the module's contribution to
1387         // the type plane plus the index in the function's contribution
1388         // to the type plane.
1389         if (MI != mMap.end())
1390           return MI->second.next_slot + FVI->second;
1391         else
1392           return FVI->second;
1393       }
1394     }
1395   }
1396
1397   // N.B. Can get here only if either !TheFunction or the function doesn't
1398   // have a corresponding type plane for the Value
1399
1400   // Make sure the type plane exists
1401   if (MI == mMap.end()) return -1;
1402   // Lookup the value in the module's map
1403   ValueMap::const_iterator MVI = MI->second.map.find(V);
1404   // Make sure we found it.
1405   if (MVI == MI->second.map.end()) return -1;
1406   // Return it.
1407   return MVI->second;
1408 }
1409
1410 /// Get the slot number for a value. This function will assert if you
1411 /// ask for a Value that hasn't previously been inserted with createSlot.
1412 /// Types are forbidden because Type does not inherit from Value (any more).
1413 int SlotMachine::getSlot(const Type *Ty) {
1414   assert( Ty && "Can't get slot for null Type" );
1415
1416   // Check for uninitialized state and do lazy initialization
1417   this->initialize();
1418
1419   if ( TheFunction ) {
1420     // Lookup the Type in the function map
1421     TypeMap::const_iterator FTI = fTypes.map.find(Ty);
1422     // If the Type doesn't exist in the function map
1423     if ( FTI == fTypes.map.end() ) {
1424       TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1425       // If we didn't find it, it wasn't inserted
1426       if (MTI == mTypes.map.end()) 
1427         return -1;
1428       // We found it only at the module level
1429       return MTI->second; 
1430
1431     // else the value exists in the function map
1432     } else {
1433       // Return the slot number as the module's contribution to
1434       // the type plane plus the index in the function's contribution
1435       // to the type plane.
1436       return mTypes.next_slot + FTI->second;
1437     }
1438   }
1439
1440   // N.B. Can get here only if either !TheFunction
1441
1442   // Lookup the value in the module's map
1443   TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1444   // Make sure we found it.
1445   if (MTI == mTypes.map.end()) return -1;
1446   // Return it.
1447   return MTI->second;
1448 }
1449
1450 // Create a new slot, or return the existing slot if it is already
1451 // inserted. Note that the logic here parallels getSlot but instead
1452 // of asserting when the Value* isn't found, it inserts the value.
1453 unsigned SlotMachine::createSlot(const Value *V) {
1454   assert( V && "Can't insert a null Value to SlotMachine");
1455   assert(!isa<Constant>(V) || isa<GlobalValue>(V) && 
1456     "Can't insert a non-GlobalValue Constant into SlotMachine"); 
1457
1458   const Type* VTy = V->getType();
1459
1460   // Just ignore void typed things
1461   if (VTy == Type::VoidTy) return 0; // FIXME: Wrong return value!
1462
1463   // Look up the type plane for the Value's type from the module map
1464   TypedPlanes::const_iterator MI = mMap.find(VTy);
1465
1466   if ( TheFunction ) {
1467     // Get the type plane for the Value's type from the function map
1468     TypedPlanes::const_iterator FI = fMap.find(VTy);
1469     // If there is a corresponding type plane in the function map
1470     if ( FI != fMap.end() ) {
1471       // Lookup the Value in the function map
1472       ValueMap::const_iterator FVI = FI->second.map.find(V);
1473       // If the value doesn't exist in the function map
1474       if ( FVI == FI->second.map.end() ) {
1475         // If there is no corresponding type plane in the module map
1476         if ( MI == mMap.end() )
1477           return insertValue(V);
1478         // Look up the value in the module map
1479         ValueMap::const_iterator MVI = MI->second.map.find(V);
1480         // If we didn't find it, it wasn't inserted
1481         if ( MVI == MI->second.map.end() )
1482           return insertValue(V);
1483         else
1484           // We found it only at the module level
1485           return MVI->second;
1486
1487       // else the value exists in the function map
1488       } else {
1489         if ( MI == mMap.end() )
1490           return FVI->second;
1491         else
1492           // Return the slot number as the module's contribution to
1493           // the type plane plus the index in the function's contribution
1494           // to the type plane.
1495           return MI->second.next_slot + FVI->second;
1496       }
1497
1498     // else there is not a corresponding type plane in the function map
1499     } else {
1500       // If the type plane doesn't exists at the module level
1501       if ( MI == mMap.end() ) {
1502         return insertValue(V);
1503       // else type plane exists at the module level, examine it
1504       } else {
1505         // Look up the value in the module's map
1506         ValueMap::const_iterator MVI = MI->second.map.find(V);
1507         // If we didn't find it there either
1508         if ( MVI == MI->second.map.end() )
1509           // Return the slot number as the module's contribution to
1510           // the type plane plus the index of the function map insertion.
1511           return MI->second.next_slot + insertValue(V);
1512         else
1513           return MVI->second;
1514       }
1515     }
1516   }
1517
1518   // N.B. Can only get here if !TheFunction
1519
1520   // If the module map's type plane is not for the Value's type
1521   if ( MI != mMap.end() ) {
1522     // Lookup the value in the module's map
1523     ValueMap::const_iterator MVI = MI->second.map.find(V);
1524     if ( MVI != MI->second.map.end() ) 
1525       return MVI->second;
1526   }
1527
1528   return insertValue(V);
1529 }
1530
1531 // Create a new slot, or return the existing slot if it is already
1532 // inserted. Note that the logic here parallels getSlot but instead
1533 // of asserting when the Value* isn't found, it inserts the value.
1534 unsigned SlotMachine::createSlot(const Type *Ty) {
1535   assert( Ty && "Can't insert a null Type to SlotMachine");
1536
1537   if ( TheFunction ) {
1538     // Lookup the Type in the function map
1539     TypeMap::const_iterator FTI = fTypes.map.find(Ty);
1540     // If the type doesn't exist in the function map
1541     if ( FTI == fTypes.map.end() ) {
1542       // Look up the type in the module map
1543       TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1544       // If we didn't find it, it wasn't inserted
1545       if ( MTI == mTypes.map.end() )
1546         return insertValue(Ty);
1547       else
1548         // We found it only at the module level
1549         return MTI->second;
1550
1551     // else the value exists in the function map
1552     } else {
1553       // Return the slot number as the module's contribution to
1554       // the type plane plus the index in the function's contribution
1555       // to the type plane.
1556       return mTypes.next_slot + FTI->second;
1557     }
1558   }
1559
1560   // N.B. Can only get here if !TheFunction
1561
1562   // Lookup the type in the module's map
1563   TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1564   if ( MTI != mTypes.map.end() ) 
1565     return MTI->second;
1566
1567   return insertValue(Ty);
1568 }
1569
1570 // Low level insert function. Minimal checking is done. This
1571 // function is just for the convenience of createSlot (above).
1572 unsigned SlotMachine::insertValue(const Value *V ) {
1573   assert(V && "Can't insert a null Value into SlotMachine!");
1574   assert(!isa<Constant>(V) || isa<GlobalValue>(V) && 
1575     "Can't insert a non-GlobalValue Constant into SlotMachine"); 
1576
1577   // If this value does not contribute to a plane (is void)
1578   // or if the value already has a name then ignore it. 
1579   if (V->getType() == Type::VoidTy || V->hasName() ) {
1580       SC_DEBUG("ignored value " << *V << "\n");
1581       return 0;   // FIXME: Wrong return value
1582   }
1583
1584   const Type *VTy = V->getType();
1585   unsigned DestSlot = 0;
1586
1587   if ( TheFunction ) {
1588     TypedPlanes::iterator I = fMap.find( VTy );
1589     if ( I == fMap.end() ) 
1590       I = fMap.insert(std::make_pair(VTy,ValuePlane())).first;
1591     DestSlot = I->second.map[V] = I->second.next_slot++;
1592   } else {
1593     TypedPlanes::iterator I = mMap.find( VTy );
1594     if ( I == mMap.end() )
1595       I = mMap.insert(std::make_pair(VTy,ValuePlane())).first;
1596     DestSlot = I->second.map[V] = I->second.next_slot++;
1597   }
1598
1599   SC_DEBUG("  Inserting value [" << VTy << "] = " << V << " slot=" << 
1600            DestSlot << " [");
1601   // G = Global, C = Constant, T = Type, F = Function, o = other
1602   SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Function>(V) ? 'F' : 
1603            (isa<Constant>(V) ? 'C' : 'o'))));
1604   SC_DEBUG("]\n");
1605   return DestSlot;
1606 }
1607
1608 // Low level insert function. Minimal checking is done. This
1609 // function is just for the convenience of createSlot (above).
1610 unsigned SlotMachine::insertValue(const Type *Ty ) {
1611   assert(Ty && "Can't insert a null Type into SlotMachine!");
1612
1613   unsigned DestSlot = 0;
1614
1615   if ( TheFunction ) {
1616     DestSlot = fTypes.map[Ty] = fTypes.next_slot++;
1617   } else {
1618     DestSlot = fTypes.map[Ty] = fTypes.next_slot++;
1619   }
1620   SC_DEBUG("  Inserting type [" << DestSlot << "] = " << Ty << "\n");
1621   return DestSlot;
1622 }
1623
1624 // vim: sw=2