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