* No more CachedWriter::setStream()
[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 = cast<ConstantInt>(CA->getOperand(i))->getRawValue();
425         
426         if (isprint(C) && C != '"' && C != '\\') {
427           Out << C;
428         } else {
429           Out << '\\'
430               << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
431               << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
432         }
433       }
434       Out << "\"";
435
436     } else {                // Cannot output in string format...
437       Out << '[';
438       if (CA->getNumOperands()) {
439         Out << ' ';
440         printTypeInt(Out, ETy, TypeTable);
441         WriteAsOperandInternal(Out, CA->getOperand(0),
442                                PrintName, TypeTable, Machine);
443         for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
444           Out << ", ";
445           printTypeInt(Out, ETy, TypeTable);
446           WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
447                                  TypeTable, Machine);
448         }
449       }
450       Out << " ]";
451     }
452   } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
453     Out << '{';
454     if (CS->getNumOperands()) {
455       Out << ' ';
456       printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
457
458       WriteAsOperandInternal(Out, CS->getOperand(0),
459                              PrintName, TypeTable, Machine);
460
461       for (unsigned i = 1; i < CS->getNumOperands(); i++) {
462         Out << ", ";
463         printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
464
465         WriteAsOperandInternal(Out, CS->getOperand(i),
466                                PrintName, TypeTable, Machine);
467       }
468     }
469
470     Out << " }";
471   } else if (isa<ConstantPointerNull>(CV)) {
472     Out << "null";
473
474   } else if (const ConstantPointerRef *PR = dyn_cast<ConstantPointerRef>(CV)) {
475     WriteAsOperandInternal(Out, PR->getValue(), true, TypeTable, Machine);
476
477   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
478     Out << CE->getOpcodeName() << " (";
479     
480     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
481       printTypeInt(Out, (*OI)->getType(), TypeTable);
482       WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Machine);
483       if (OI+1 != CE->op_end())
484         Out << ", ";
485     }
486     
487     if (CE->getOpcode() == Instruction::Cast) {
488       Out << " to ";
489       printTypeInt(Out, CE->getType(), TypeTable);
490     }
491     Out << ')';
492
493   } else {
494     Out << "<placeholder or erroneous Constant>";
495   }
496 }
497
498
499 /// WriteAsOperand - Write the name of the specified value out to the specified
500 /// ostream.  This can be useful when you just want to print int %reg126, not
501 /// the whole instruction that generated it.
502 ///
503 static void WriteAsOperandInternal(std::ostream &Out, const Value *V, 
504                                    bool PrintName,
505                                   std::map<const Type*, std::string> &TypeTable,
506                                    SlotMachine *Machine) {
507   Out << ' ';
508   if (PrintName && V->hasName()) {
509     Out << getLLVMName(V->getName());
510   } else {
511     if (const Constant *CV = dyn_cast<Constant>(V)) {
512       WriteConstantInt(Out, CV, PrintName, TypeTable, Machine);
513     } else {
514       int Slot;
515       if (Machine) {
516         Slot = Machine->getSlot(V);
517       } else {
518         if (const Type *Ty = dyn_cast<Type>(V)) {
519           Out << Ty->getDescription();
520           return;
521         }
522
523         Machine = createSlotMachine(V);
524         if (Machine == 0) { Out << "BAD VALUE TYPE!"; return; }
525
526         Slot = Machine->getSlot(V);
527         delete Machine;
528       }
529       Out << '%' << Slot;
530     }
531   }
532 }
533
534
535 /// WriteAsOperand - Write the name of the specified value out to the specified
536 /// ostream.  This can be useful when you just want to print int %reg126, not
537 /// the whole instruction that generated it.
538 ///
539 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
540                                    bool PrintType, bool PrintName, 
541                                    const Module *Context) {
542   std::map<const Type *, std::string> TypeNames;
543   if (Context == 0) Context = getModuleFromVal(V);
544
545   if (Context)
546     fillTypeNameTable(Context, TypeNames);
547
548   if (PrintType)
549     printTypeInt(Out, V->getType(), TypeNames);
550   
551   if (const Type *Ty = dyn_cast<Type> (V))
552     printTypeInt(Out, Ty, TypeNames);
553
554   WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
555   return Out;
556 }
557
558 namespace llvm {
559
560 class AssemblyWriter {
561   std::ostream *Out;
562   SlotMachine &Machine;
563   const Module *TheModule;
564   std::map<const Type *, std::string> TypeNames;
565   AssemblyAnnotationWriter *AnnotationWriter;
566 public:
567   inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
568                         AssemblyAnnotationWriter *AAW)
569     : Out(&o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
570
571     // If the module has a symbol table, take all global types and stuff their
572     // names into the TypeNames map.
573     //
574     fillTypeNameTable(M, TypeNames);
575   }
576
577   inline void write(const Module *M)         { printModule(M);      }
578   inline void write(const GlobalVariable *G) { printGlobal(G);      }
579   inline void write(const Function *F)       { printFunction(F);    }
580   inline void write(const BasicBlock *BB)    { printBasicBlock(BB); }
581   inline void write(const Instruction *I)    { printInstruction(*I); }
582   inline void write(const Constant *CPV)     { printConstant(CPV);  }
583   inline void write(const Type *Ty)          { printType(Ty);       }
584
585   void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
586
587   const Module* getModule() { return TheModule; }
588   void setStream(std::ostream &os) { Out = &os; }
589
590 private :
591   void printModule(const Module *M);
592   void printSymbolTable(const SymbolTable &ST);
593   void printConstant(const Constant *CPV);
594   void printGlobal(const GlobalVariable *GV);
595   void printFunction(const Function *F);
596   void printArgument(const Argument *FA);
597   void printBasicBlock(const BasicBlock *BB);
598   void printInstruction(const Instruction &I);
599
600   // printType - Go to extreme measures to attempt to print out a short,
601   // symbolic version of a type name.
602   //
603   std::ostream &printType(const Type *Ty) {
604     return printTypeInt(*Out, Ty, TypeNames);
605   }
606
607   // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
608   // without considering any symbolic types that we may have equal to it.
609   //
610   std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
611
612   // printInfoComment - Print a little comment after the instruction indicating
613   // which slot it occupies.
614   void printInfoComment(const Value &V);
615 };
616 }  // end of llvm namespace
617
618 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
619 /// without considering any symbolic types that we may have equal to it.
620 ///
621 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
622   if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
623     printType(FTy->getReturnType()) << " (";
624     for (FunctionType::param_iterator I = FTy->param_begin(),
625            E = FTy->param_end(); I != E; ++I) {
626       if (I != FTy->param_begin())
627         *Out << ", ";
628       printType(*I);
629     }
630     if (FTy->isVarArg()) {
631       if (FTy->getNumParams()) *Out << ", ";
632       *Out << "...";
633     }
634     *Out << ')';
635   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
636     *Out << "{ ";
637     for (StructType::element_iterator I = STy->element_begin(),
638            E = STy->element_end(); I != E; ++I) {
639       if (I != STy->element_begin())
640         *Out << ", ";
641       printType(*I);
642     }
643     *Out << " }";
644   } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
645     printType(PTy->getElementType()) << '*';
646   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
647     *Out << '[' << ATy->getNumElements() << " x ";
648     printType(ATy->getElementType()) << ']';
649   } else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
650     *Out << "opaque";
651   } else {
652     if (!Ty->isPrimitiveType())
653       *Out << "<unknown derived type>";
654     printType(Ty);
655   }
656   return *Out;
657 }
658
659
660 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType, 
661                                   bool PrintName) {
662   if (PrintType) { *Out << ' '; printType(Operand->getType()); }
663   WriteAsOperandInternal(*Out, Operand, PrintName, TypeNames, &Machine);
664 }
665
666
667 void AssemblyWriter::printModule(const Module *M) {
668   switch (M->getEndianness()) {
669   case Module::LittleEndian: *Out << "target endian = little\n"; break;
670   case Module::BigEndian:    *Out << "target endian = big\n";    break;
671   case Module::AnyEndianness: break;
672   }
673   switch (M->getPointerSize()) {
674   case Module::Pointer32:    *Out << "target pointersize = 32\n"; break;
675   case Module::Pointer64:    *Out << "target pointersize = 64\n"; break;
676   case Module::AnyPointerSize: break;
677   }
678   
679   // Loop over the symbol table, emitting all named constants...
680   printSymbolTable(M->getSymbolTable());
681   
682   for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
683     printGlobal(I);
684
685   *Out << "\nimplementation   ; Functions:\n";
686   
687   // Output all of the functions...
688   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
689     printFunction(I);
690 }
691
692 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
693   if (GV->hasName()) *Out << getLLVMName(GV->getName()) << " = ";
694
695   if (!GV->hasInitializer()) 
696     *Out << "external ";
697   else
698     switch (GV->getLinkage()) {
699     case GlobalValue::InternalLinkage:  *Out << "internal "; break;
700     case GlobalValue::LinkOnceLinkage:  *Out << "linkonce "; break;
701     case GlobalValue::WeakLinkage:      *Out << "weak "; break;
702     case GlobalValue::AppendingLinkage: *Out << "appending "; break;
703     case GlobalValue::ExternalLinkage: break;
704     }
705
706   *Out << (GV->isConstant() ? "constant " : "global ");
707   printType(GV->getType()->getElementType());
708
709   if (GV->hasInitializer())
710     writeOperand(GV->getInitializer(), false, false);
711
712   printInfoComment(*GV);
713   *Out << "\n";
714 }
715
716
717 // printSymbolTable - Run through symbol table looking for constants
718 // and types. Emit their declarations.
719 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
720
721   // Print the types.
722   for (SymbolTable::type_const_iterator TI = ST.type_begin();
723        TI != ST.type_end(); ++TI ) {
724     *Out << "\t" << getLLVMName(TI->first) << " = type ";
725
726     // Make sure we print out at least one level of the type structure, so
727     // that we do not get %FILE = type %FILE
728     //
729     printTypeAtLeastOneLevel(TI->second) << "\n";
730   }
731     
732   // Print the constants, in type plane order.
733   for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
734        PI != ST.plane_end(); ++PI ) {
735     SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
736     SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
737
738     for (; VI != VE; ++VI) {
739       const Value *V = VI->second;
740       if (const Constant *CPV = dyn_cast<Constant>(V)) {
741         printConstant(CPV);
742       }
743     }
744   }
745 }
746
747
748 /// printConstant - Print out a constant pool entry...
749 ///
750 void AssemblyWriter::printConstant(const Constant *CPV) {
751   // Don't print out unnamed constants, they will be inlined
752   if (!CPV->hasName()) return;
753
754   // Print out name...
755   *Out << "\t" << getLLVMName(CPV->getName()) << " =";
756
757   // Write the value out now...
758   writeOperand(CPV, true, false);
759
760   printInfoComment(*CPV);
761   *Out << "\n";
762 }
763
764 /// printFunction - Print all aspects of a function.
765 ///
766 void AssemblyWriter::printFunction(const Function *F) {
767   // Print out the return type and name...
768   *Out << "\n";
769
770   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, *Out);
771
772   if (F->isExternal())
773     *Out << "declare ";
774   else
775     switch (F->getLinkage()) {
776     case GlobalValue::InternalLinkage:  *Out << "internal "; break;
777     case GlobalValue::LinkOnceLinkage:  *Out << "linkonce "; break;
778     case GlobalValue::WeakLinkage:      *Out << "weak "; break;
779     case GlobalValue::AppendingLinkage: *Out << "appending "; break;
780     case GlobalValue::ExternalLinkage: break;
781     }
782
783   printType(F->getReturnType()) << ' ';
784   if (!F->getName().empty())
785     *Out << getLLVMName(F->getName());
786   else
787     *Out << "\"\"";
788   *Out << '(';
789   Machine.incorporateFunction(F);
790
791   // Loop over the arguments, printing them...
792   const FunctionType *FT = F->getFunctionType();
793
794   for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
795     printArgument(I);
796
797   // Finish printing arguments...
798   if (FT->isVarArg()) {
799     if (FT->getNumParams()) *Out << ", ";
800     *Out << "...";  // Output varargs portion of signature!
801   }
802   *Out << ')';
803
804   if (F->isExternal()) {
805     *Out << "\n";
806   } else {
807     *Out << " {";
808   
809     // Output all of its basic blocks... for the function
810     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
811       printBasicBlock(I);
812
813     *Out << "}\n";
814   }
815
816   Machine.purgeFunction();
817 }
818
819 /// printArgument - This member is called for every argument that is passed into
820 /// the function.  Simply print it out
821 ///
822 void AssemblyWriter::printArgument(const Argument *Arg) {
823   // Insert commas as we go... the first arg doesn't get a comma
824   if (Arg != &Arg->getParent()->afront()) *Out << ", ";
825
826   // Output type...
827   printType(Arg->getType());
828   
829   // Output name, if available...
830   if (Arg->hasName())
831     *Out << ' ' << getLLVMName(Arg->getName());
832 }
833
834 /// printBasicBlock - This member is called for each basic block in a method.
835 ///
836 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
837   if (BB->hasName()) {              // Print out the label if it exists...
838     *Out << "\n" << BB->getName() << ':';
839   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
840     *Out << "\n; <label>:" << Machine.getSlot(BB);
841   }
842
843   if (BB->getParent() == 0)
844     *Out << "\t\t; Error: Block without parent!";
845   else {
846     if (BB != &BB->getParent()->front()) {  // Not the entry block?
847       // Output predecessors for the block...
848       *Out << "\t\t;";
849       pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
850       
851       if (PI == PE) {
852         *Out << " No predecessors!";
853       } else {
854         *Out << " preds =";
855         writeOperand(*PI, false, true);
856         for (++PI; PI != PE; ++PI) {
857           *Out << ',';
858           writeOperand(*PI, false, true);
859         }
860       }
861     }
862   }
863   
864   *Out << "\n";
865
866   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, *Out);
867
868   // Output all of the instructions in the basic block...
869   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
870     printInstruction(*I);
871
872   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, *Out);
873 }
874
875
876 /// printInfoComment - Print a little comment after the instruction indicating
877 /// which slot it occupies.
878 ///
879 void AssemblyWriter::printInfoComment(const Value &V) {
880   if (V.getType() != Type::VoidTy) {
881     *Out << "\t\t; <";
882     printType(V.getType()) << '>';
883
884     if (!V.hasName()) {
885       *Out << ':' << Machine.getSlot(&V); // Print out the def slot taken.
886     }
887     *Out << " [#uses=" << V.use_size() << ']';  // Output # uses
888   }
889 }
890
891 /// printInstruction - This member is called for each Instruction in a method.
892 ///
893 void AssemblyWriter::printInstruction(const Instruction &I) {
894   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, *Out);
895
896   *Out << "\t";
897
898   // Print out name if it exists...
899   if (I.hasName())
900     *Out << getLLVMName(I.getName()) << " = ";
901
902   // If this is a volatile load or store, print out the volatile marker
903   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
904       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()))
905       *Out << "volatile ";
906
907   // Print out the opcode...
908   *Out << I.getOpcodeName();
909
910   // Print out the type of the operands...
911   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
912
913   // Special case conditional branches to swizzle the condition out to the front
914   if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
915     writeOperand(I.getOperand(2), true);
916     *Out << ',';
917     writeOperand(Operand, true);
918     *Out << ',';
919     writeOperand(I.getOperand(1), true);
920
921   } else if (isa<SwitchInst>(I)) {
922     // Special case switch statement to get formatting nice and correct...
923     writeOperand(Operand        , true); *Out << ',';
924     writeOperand(I.getOperand(1), true); *Out << " [";
925
926     for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
927       *Out << "\n\t\t";
928       writeOperand(I.getOperand(op  ), true); *Out << ',';
929       writeOperand(I.getOperand(op+1), true);
930     }
931     *Out << "\n\t]";
932   } else if (isa<PHINode>(I)) {
933     *Out << ' ';
934     printType(I.getType());
935     *Out << ' ';
936
937     for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
938       if (op) *Out << ", ";
939       *Out << '[';  
940       writeOperand(I.getOperand(op  ), false); *Out << ',';
941       writeOperand(I.getOperand(op+1), false); *Out << " ]";
942     }
943   } else if (isa<ReturnInst>(I) && !Operand) {
944     *Out << " void";
945   } else if (isa<CallInst>(I)) {
946     const PointerType  *PTy = cast<PointerType>(Operand->getType());
947     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
948     const Type       *RetTy = FTy->getReturnType();
949
950     // If possible, print out the short form of the call instruction.  We can
951     // only do this if the first argument is a pointer to a nonvararg function,
952     // and if the return type is not a pointer to a function.
953     //
954     if (!FTy->isVarArg() &&
955         (!isa<PointerType>(RetTy) || 
956          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
957       *Out << ' '; printType(RetTy);
958       writeOperand(Operand, false);
959     } else {
960       writeOperand(Operand, true);
961     }
962     *Out << '(';
963     if (I.getNumOperands() > 1) writeOperand(I.getOperand(1), true);
964     for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
965       *Out << ',';
966       writeOperand(I.getOperand(op), true);
967     }
968
969     *Out << " )";
970   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
971     const PointerType  *PTy = cast<PointerType>(Operand->getType());
972     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
973     const Type       *RetTy = FTy->getReturnType();
974
975     // If possible, print out the short form of the invoke instruction. We can
976     // only do this if the first argument is a pointer to a nonvararg function,
977     // and if the return type is not a pointer to a function.
978     //
979     if (!FTy->isVarArg() &&
980         (!isa<PointerType>(RetTy) || 
981          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
982       *Out << ' '; printType(RetTy);
983       writeOperand(Operand, false);
984     } else {
985       writeOperand(Operand, true);
986     }
987
988     *Out << '(';
989     if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
990     for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
991       *Out << ',';
992       writeOperand(I.getOperand(op), true);
993     }
994
995     *Out << " )\n\t\t\tto";
996     writeOperand(II->getNormalDest(), true);
997     *Out << " unwind";
998     writeOperand(II->getUnwindDest(), true);
999
1000   } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1001     *Out << ' ';
1002     printType(AI->getType()->getElementType());
1003     if (AI->isArrayAllocation()) {
1004       *Out << ',';
1005       writeOperand(AI->getArraySize(), true);
1006     }
1007   } else if (isa<CastInst>(I)) {
1008     if (Operand) writeOperand(Operand, true);   // Work with broken code
1009     *Out << " to ";
1010     printType(I.getType());
1011   } else if (isa<VAArgInst>(I)) {
1012     if (Operand) writeOperand(Operand, true);   // Work with broken code
1013     *Out << ", ";
1014     printType(I.getType());
1015   } else if (const VANextInst *VAN = dyn_cast<VANextInst>(&I)) {
1016     if (Operand) writeOperand(Operand, true);   // Work with broken code
1017     *Out << ", ";
1018     printType(VAN->getArgType());
1019   } else if (Operand) {   // Print the normal way...
1020
1021     // PrintAllTypes - Instructions who have operands of all the same type 
1022     // omit the type from all but the first operand.  If the instruction has
1023     // different type operands (for example br), then they are all printed.
1024     bool PrintAllTypes = false;
1025     const Type *TheType = Operand->getType();
1026
1027     // Shift Left & Right print both types even for Ubyte LHS, and select prints
1028     // types even if all operands are bools.
1029     if (isa<ShiftInst>(I) || isa<SelectInst>(I)) {
1030       PrintAllTypes = true;
1031     } else {
1032       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1033         Operand = I.getOperand(i);
1034         if (Operand->getType() != TheType) {
1035           PrintAllTypes = true;    // We have differing types!  Print them all!
1036           break;
1037         }
1038       }
1039     }
1040     
1041     if (!PrintAllTypes) {
1042       *Out << ' ';
1043       printType(TheType);
1044     }
1045
1046     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1047       if (i) *Out << ',';
1048       writeOperand(I.getOperand(i), PrintAllTypes);
1049     }
1050   }
1051
1052   printInfoComment(I);
1053   *Out << "\n";
1054 }
1055
1056
1057 //===----------------------------------------------------------------------===//
1058 //                       External Interface declarations
1059 //===----------------------------------------------------------------------===//
1060
1061 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1062   SlotMachine SlotTable(this);
1063   AssemblyWriter W(o, SlotTable, this, AAW);
1064   W.write(this);
1065 }
1066
1067 void GlobalVariable::print(std::ostream &o) const {
1068   SlotMachine SlotTable(getParent());
1069   AssemblyWriter W(o, SlotTable, getParent(), 0);
1070   W.write(this);
1071 }
1072
1073 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1074   SlotMachine SlotTable(getParent());
1075   AssemblyWriter W(o, SlotTable, getParent(), AAW);
1076
1077   W.write(this);
1078 }
1079
1080 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1081   SlotMachine SlotTable(getParent());
1082   AssemblyWriter W(o, SlotTable, 
1083                    getParent() ? getParent()->getParent() : 0, AAW);
1084   W.write(this);
1085 }
1086
1087 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1088   const Function *F = getParent() ? getParent()->getParent() : 0;
1089   SlotMachine SlotTable(F);
1090   AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1091
1092   W.write(this);
1093 }
1094
1095 void Constant::print(std::ostream &o) const {
1096   if (this == 0) { o << "<null> constant value\n"; return; }
1097
1098   // Handle CPR's special, because they have context information...
1099   if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
1100     CPR->getValue()->print(o);  // Print as a global value, with context info.
1101     return;
1102   }
1103
1104   o << ' ' << getType()->getDescription() << ' ';
1105
1106   std::map<const Type *, std::string> TypeTable;
1107   WriteConstantInt(o, this, false, TypeTable, 0);
1108 }
1109
1110 void Type::print(std::ostream &o) const { 
1111   if (this == 0)
1112     o << "<null Type>";
1113   else
1114     o << getDescription();
1115 }
1116
1117 void Argument::print(std::ostream &o) const {
1118   o << getType() << ' ' << getName();
1119 }
1120
1121 // Value::dump - allow easy printing of  Values from the debugger.
1122 // Located here because so much of the needed functionality is here.
1123 void Value::dump() const { print(std::cerr); }
1124
1125 // Type::dump - allow easy printing of  Values from the debugger.
1126 // Located here because so much of the needed functionality is here.
1127 void Type::dump() const { print(std::cerr); }
1128
1129 //===----------------------------------------------------------------------===//
1130 //  CachedWriter Class Implementation
1131 //===----------------------------------------------------------------------===//
1132
1133 void CachedWriter::setModule(const Module *M) {
1134   delete SC; delete AW;
1135   if (M) {
1136     SC = new SlotMachine(M );
1137     AW = new AssemblyWriter(Out, *SC, M, 0);
1138   } else {
1139     SC = 0; AW = 0;
1140   }
1141 }
1142
1143 CachedWriter::~CachedWriter() {
1144   delete AW;
1145   delete SC;
1146 }
1147
1148 CachedWriter &CachedWriter::operator<<(const Value *V) {
1149   assert(AW && SC && "CachedWriter does not have a current module!");
1150   switch (V->getValueType()) {
1151   case Value::ConstantVal:
1152   case Value::ArgumentVal:       AW->writeOperand(V, true, true); break;
1153   case Value::TypeVal:           AW->write(cast<Type>(V)); break;
1154   case Value::InstructionVal:    AW->write(cast<Instruction>(V)); break;
1155   case Value::BasicBlockVal:     AW->write(cast<BasicBlock>(V)); break;
1156   case Value::FunctionVal:       AW->write(cast<Function>(V)); break;
1157   case Value::GlobalVariableVal: AW->write(cast<GlobalVariable>(V)); break;
1158   default: Out << "<unknown value type: " << V->getValueType() << '>'; break;
1159   }
1160   return *this;
1161 }
1162
1163 CachedWriter& CachedWriter::operator<<(const Type *X) {
1164   if (SymbolicTypes) {
1165     const Module *M = AW->getModule();
1166     if (M) WriteTypeSymbolic(Out, X, M);
1167     return *this;
1168   } else
1169     return *this << (const Value*)X;
1170 }
1171
1172 //===----------------------------------------------------------------------===//
1173 //===--                    SlotMachine Implementation
1174 //===----------------------------------------------------------------------===//
1175
1176 #if 0
1177 #define SC_DEBUG(X) std::cerr << X
1178 #else
1179 #define SC_DEBUG(X)
1180 #endif
1181
1182 // Module level constructor. Causes the contents of the Module (sans functions)
1183 // to be added to the slot table.
1184 SlotMachine::SlotMachine(const Module *M) 
1185   : TheModule(M)    ///< Saved for lazy initialization.
1186   , TheFunction(0)
1187   , mMap()
1188   , fMap()
1189 {
1190 }
1191
1192 // Function level constructor. Causes the contents of the Module and the one
1193 // function provided to be added to the slot table.
1194 SlotMachine::SlotMachine(const Function *F ) 
1195   : TheModule( F ? F->getParent() : 0 ) ///< Saved for lazy initialization
1196   , TheFunction(F) ///< Saved for lazy initialization
1197   , mMap()
1198   , fMap()
1199 {
1200 }
1201
1202 inline void SlotMachine::initialize(void) {
1203   if ( TheModule) { 
1204     processModule(); 
1205     TheModule = 0; ///< Prevent re-processing next time we're called.
1206   }
1207   if ( TheFunction ) { 
1208     processFunction(); 
1209   }
1210 }
1211
1212 // Iterate through all the global variables, functions, and global
1213 // variable initializers and create slots for them. 
1214 void SlotMachine::processModule() {
1215   SC_DEBUG("begin processModule!\n");
1216
1217   // Add all of the global variables to the value table...
1218   for (Module::const_giterator I = TheModule->gbegin(), E = TheModule->gend();
1219        I != E; ++I)
1220     createSlot(I);
1221
1222   // Add all the functions to the table
1223   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1224        I != E; ++I)
1225     createSlot(I);
1226
1227   SC_DEBUG("end processModule!\n");
1228 }
1229
1230
1231 // Process the arguments, basic blocks, and instructions  of a function.
1232 void SlotMachine::processFunction() {
1233   SC_DEBUG("begin processFunction!\n");
1234
1235   // Add all the function arguments
1236   for(Function::const_aiterator AI = TheFunction->abegin(), 
1237       AE = TheFunction->aend(); AI != AE; ++AI)
1238     createSlot(AI);
1239
1240   SC_DEBUG("Inserting Instructions:\n");
1241
1242   // Add all of the basic blocks and instructions
1243   for (Function::const_iterator BB = TheFunction->begin(), 
1244        E = TheFunction->end(); BB != E; ++BB) {
1245     createSlot(BB);
1246     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1247       createSlot(I);
1248     }
1249   }
1250
1251   SC_DEBUG("end processFunction!\n");
1252 }
1253
1254 // Clean up after incorporating a function. This is the only way
1255 // to get out of the function incorporation state that affects the
1256 // getSlot/createSlot lock. Function incorporation state is indicated
1257 // by TheFunction != 0.
1258 void SlotMachine::purgeFunction() {
1259   SC_DEBUG("begin purgeFunction!\n");
1260   fMap.clear(); // Simply discard the function level map
1261   TheFunction = 0;
1262   SC_DEBUG("end purgeFunction!\n");
1263 }
1264
1265 /// Get the slot number for a value. This function will assert if you
1266 /// ask for a Value that hasn't previously been inserted with createSlot.
1267 /// Types are forbidden because Type does not inherit from Value (any more).
1268 unsigned SlotMachine::getSlot(const Value *V) {
1269   assert( V && "Can't get slot for null Value" );
1270   assert( !isa<Type>(V) && "Can't get slot for a type" );
1271   assert(!isa<Constant>(V) || isa<GlobalValue>(V) && 
1272     "Can't insert a non-GlobalValue Constant into SlotMachine"); 
1273
1274   // Check for uninitialized state and do lazy initialization
1275   this->initialize();
1276
1277   // Do not number CPR's at all. They are an abomination
1278   if ( const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(V) )
1279     V = CPR->getValue() ;
1280
1281   // Get the type of the value
1282   const Type* VTy = V->getType();
1283
1284   // Find the type plane in the module map
1285   TypedPlanes::const_iterator MI = mMap.find(VTy);
1286
1287   if ( TheFunction ) {
1288     // Lookup the type in the function map too
1289     TypedPlanes::const_iterator FI = fMap.find(VTy);
1290     // If there is a corresponding type plane in the function map
1291     if ( FI != fMap.end() ) {
1292       // Lookup the Value in the function map
1293       ValueMap::const_iterator FVI = FI->second.map.find(V);
1294       // If the value doesn't exist in the function map
1295       if ( FVI == FI->second.map.end() ) {
1296         // Look up the value in the module map
1297         ValueMap::const_iterator MVI = MI->second.map.find(V);
1298         // If we didn't find it, it wasn't inserted
1299         assert( MVI != MI->second.map.end() && "Value not found");
1300         // We found it only at the module level
1301         return MVI->second; 
1302
1303       // else the value exists in the function map
1304       } else {
1305         // Return the slot number as the module's contribution to
1306         // the type plane plus the index in the function's contribution
1307         // to the type plane.
1308         return MI->second.next_slot + FVI->second;
1309       }
1310
1311     // else there is not a corresponding type plane in the function map
1312     } else  {
1313       assert( MI != mMap.end() && "No such type plane!" );
1314       // Look up the value in the module's map
1315       ValueMap::const_iterator MVI = MI->second.map.find(V);
1316       // If we didn't find it, it wasn't inserted.
1317       assert( MVI != MI->second.map.end() && "Value not found");
1318       // We found it only in the module level and function level
1319       // didn't even have a type plane.
1320       return MVI->second; 
1321     }
1322   }
1323
1324   // N.B. Can only get here if !TheFunction
1325
1326   // Make sure the type plane exists
1327   assert( MI != mMap.end() && "No such type plane!" );
1328   // Lookup the value in the module's map
1329   ValueMap::const_iterator MVI = MI->second.map.find(V);
1330   // Make sure we found it.
1331   assert( MVI != MI->second.map.end() && "Value not found" );
1332   // Return it.
1333   return MVI->second;
1334 }
1335
1336
1337 // Create a new slot, or return the existing slot if it is already
1338 // inserted. Note that the logic here parallels getSlot but instead
1339 // of asserting when the Value* isn't found, it inserts the value.
1340 unsigned SlotMachine::createSlot(const Value *V) {
1341   assert( V && "Can't insert a null Value to SlotMachine");
1342   assert( !isa<Type>(V) && "Can't insert a Type into SlotMachine"); 
1343   assert(!isa<Constant>(V) || isa<GlobalValue>(V) && 
1344     "Can't insert a non-GlobalValue Constant into SlotMachine"); 
1345
1346   const Type* VTy = V->getType();
1347
1348   // Just ignore void typed things
1349   if (VTy == Type::VoidTy) return 0; // FIXME: Wrong return value!
1350
1351   // Look up the type plane for the Value's type from the module map
1352   TypedPlanes::const_iterator MI = mMap.find(VTy);
1353
1354   if ( TheFunction ) {
1355     // Get the type plane for the Value's type from the function map
1356     TypedPlanes::const_iterator FI = fMap.find(VTy);
1357     // If there is a corresponding type plane in the function map
1358     if ( FI != fMap.end() ) {
1359       // Lookup the Value in the function map
1360       ValueMap::const_iterator FVI = FI->second.map.find(V);
1361       // If the value doesn't exist in the function map
1362       if ( FVI == FI->second.map.end() ) {
1363         // If there is no corresponding type plane in the module map
1364         if ( MI == mMap.end() )
1365           return insertValue(V);
1366         // Look up the value in the module map
1367         ValueMap::const_iterator MVI = MI->second.map.find(V);
1368         // If we didn't find it, it wasn't inserted
1369         if ( MVI == MI->second.map.end() )
1370           return insertValue(V);
1371         else
1372           // We found it only at the module level
1373           return MVI->second;
1374
1375       // else the value exists in the function map
1376       } else {
1377         if ( MI == mMap.end() )
1378           return FVI->second;
1379         else
1380           // Return the slot number as the module's contribution to
1381           // the type plane plus the index in the function's contribution
1382           // to the type plane.
1383           return MI->second.next_slot + FVI->second;
1384       }
1385
1386     // else there is not a corresponding type plane in the function map
1387     } else {
1388       // If the type plane doesn't exists at the module level
1389       if ( MI == mMap.end() ) {
1390         return insertValue(V);
1391       // else type plane exists at the module level, examine it
1392       } else {
1393         // Look up the value in the module's map
1394         ValueMap::const_iterator MVI = MI->second.map.find(V);
1395         // If we didn't find it there either
1396         if ( MVI == MI->second.map.end() )
1397           // Return the slot number as the module's contribution to
1398           // the type plane plus the index of the function map insertion.
1399           return MI->second.next_slot + insertValue(V);
1400         else
1401           return MVI->second;
1402       }
1403     }
1404   }
1405
1406   // N.B. Can only get here if !TheFunction
1407
1408   // If the module map's type plane is not for the Value's type
1409   if ( MI != mMap.end() ) {
1410     // Lookup the value in the module's map
1411     ValueMap::const_iterator MVI = MI->second.map.find(V);
1412     if ( MVI != MI->second.map.end() ) 
1413       return MVI->second;
1414   }
1415
1416   return insertValue(V);
1417 }
1418
1419
1420 // Low level insert function. Minimal checking is done. This
1421 // function is just for the convenience of createSlot (above).
1422 unsigned SlotMachine::insertValue(const Value *V ) {
1423   assert(V && "Can't insert a null Value into SlotMachine!");
1424   assert(!isa<Type>(V) && "Can't insert a Type into SlotMachine!");
1425   assert(!isa<Constant>(V) || isa<GlobalValue>(V) && 
1426     "Can't insert a non-GlobalValue Constant into SlotMachine"); 
1427
1428   // If this value does not contribute to a plane (is void)
1429   // or if the value already has a name then ignore it. 
1430   if (V->getType() == Type::VoidTy || V->hasName() ) {
1431       SC_DEBUG("ignored value " << *V << "\n");
1432       return 0;   // FIXME: Wrong return value
1433   }
1434
1435   const Type *VTy = V->getType();
1436   unsigned DestSlot = 0;
1437
1438   if ( TheFunction ) {
1439     TypedPlanes::iterator I = fMap.find( VTy );
1440     if ( I == fMap.end() ) 
1441       I = fMap.insert(std::make_pair(VTy,Plane())).first;
1442     DestSlot = I->second.map[V] = I->second.next_slot++;
1443   } else {
1444     TypedPlanes::iterator I = mMap.find( VTy );
1445     if ( I == mMap.end() )
1446       I = mMap.insert(std::make_pair(VTy,Plane())).first;
1447     DestSlot = I->second.map[V] = I->second.next_slot++;
1448   }
1449
1450   SC_DEBUG("  Inserting value [" << VTy << "] = " << V << " slot=" << 
1451            DestSlot << " [");
1452   // G = Global, C = Constant, T = Type, F = Function, o = other
1453   SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Constant>(V) ? 'C' : 
1454            (isa<Function>(V) ? 'F' : 'o'))));
1455   SC_DEBUG("]\n");
1456   return DestSlot;
1457 }
1458
1459 // vim: sw=2