* Fix a nefarious bugs: TypesEqual was wrong for varargs methods
[oota-llvm.git] / lib / VMCore / Type.cpp
1 //===-- Type.cpp - Implement the Type class ----------------------*- C++ -*--=//
2 //
3 // This file implements the Type class for the VMCore library.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "llvm/DerivedTypes.h"
8 #include "llvm/Support/StringExtras.h"
9 #include "llvm/SymbolTable.h"
10 #include "llvm/Support/STLExtras.h"
11
12 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
13 // created and later destroyed, all in an effort to make sure that there is only
14 // a single cannonical version of a type.
15 //
16 //#define DEBUG_MERGE_TYPES 1
17
18
19
20 //===----------------------------------------------------------------------===//
21 //                         Type Class Implementation
22 //===----------------------------------------------------------------------===//
23
24 static unsigned CurUID = 0;
25 static vector<const Type *> UIDMappings;
26
27 Type::Type(const string &name, PrimitiveID id)
28   : Value(Type::TypeTy, Value::TypeVal) {
29   setDescription(name);
30   ID = id;
31   Abstract = false;
32   UID = CurUID++;       // Assign types UID's as they are created
33   UIDMappings.push_back(this);
34 }
35
36 void Type::setName(const string &Name, SymbolTable *ST) {
37   assert(ST && "Type::setName - Must provide symbol table argument!");
38
39   if (Name.size()) ST->insert(Name, this);
40 }
41
42
43 const Type *Type::getUniqueIDType(unsigned UID) {
44   assert(UID < UIDMappings.size() && 
45          "Type::getPrimitiveType: UID out of range!");
46   return UIDMappings[UID];
47 }
48
49 const Type *Type::getPrimitiveType(PrimitiveID IDNumber) {
50   switch (IDNumber) {
51   case VoidTyID  : return VoidTy;
52   case BoolTyID  : return BoolTy;
53   case UByteTyID : return UByteTy;
54   case SByteTyID : return SByteTy;
55   case UShortTyID: return UShortTy;
56   case ShortTyID : return ShortTy;
57   case UIntTyID  : return UIntTy;
58   case IntTyID   : return IntTy;
59   case ULongTyID : return ULongTy;
60   case LongTyID  : return LongTy;
61   case FloatTyID : return FloatTy;
62   case DoubleTyID: return DoubleTy;
63   case TypeTyID  : return TypeTy;
64   case LabelTyID : return LabelTy;
65   default:
66     return 0;
67   }
68 }
69
70 //===----------------------------------------------------------------------===//
71 //                           Auxilliary classes
72 //===----------------------------------------------------------------------===//
73 //
74 // These classes are used to implement specialized behavior for each different
75 // type.
76 //
77 class SignedIntType : public Type {
78   int Size;
79 public:
80   SignedIntType(const string &Name, PrimitiveID id, int size) : Type(Name, id) {
81     Size = size;
82   }
83
84   // isSigned - Return whether a numeric type is signed.
85   virtual bool isSigned() const { return 1; }
86
87   // isIntegral - Equivalent to isSigned() || isUnsigned, but with only a single
88   // virtual function invocation.
89   //
90   virtual bool isIntegral() const { return 1; }
91 };
92
93 class UnsignedIntType : public Type {
94   uint64_t Size;
95 public:
96   UnsignedIntType(const string &N, PrimitiveID id, int size) : Type(N, id) {
97     Size = size;
98   }
99
100   // isUnsigned - Return whether a numeric type is signed.
101   virtual bool isUnsigned() const { return 1; }
102
103   // isIntegral - Equivalent to isSigned() || isUnsigned, but with only a single
104   // virtual function invocation.
105   //
106   virtual bool isIntegral() const { return 1; }
107 };
108
109 static struct TypeType : public Type {
110   TypeType() : Type("type", TypeTyID) {}
111 } TheTypeType;   // Implement the type that is global.
112
113
114 //===----------------------------------------------------------------------===//
115 //                           Static 'Type' data
116 //===----------------------------------------------------------------------===//
117
118 Type *Type::VoidTy   = new            Type("void"  , VoidTyID),
119      *Type::BoolTy   = new            Type("bool"  , BoolTyID),
120      *Type::SByteTy  = new   SignedIntType("sbyte" , SByteTyID, 1),
121      *Type::UByteTy  = new UnsignedIntType("ubyte" , UByteTyID, 1),
122      *Type::ShortTy  = new   SignedIntType("short" ,  ShortTyID, 2),
123      *Type::UShortTy = new UnsignedIntType("ushort", UShortTyID, 2),
124      *Type::IntTy    = new   SignedIntType("int"   ,  IntTyID, 4), 
125      *Type::UIntTy   = new UnsignedIntType("uint"  , UIntTyID, 4),
126      *Type::LongTy   = new   SignedIntType("long"  ,  LongTyID, 8),
127      *Type::ULongTy  = new UnsignedIntType("ulong" , ULongTyID, 8),
128      *Type::FloatTy  = new            Type("float" , FloatTyID),
129      *Type::DoubleTy = new            Type("double", DoubleTyID),
130      *Type::TypeTy   =        &TheTypeType,
131      *Type::LabelTy  = new            Type("label" , LabelTyID);
132
133
134 //===----------------------------------------------------------------------===//
135 //                          Derived Type Constructors
136 //===----------------------------------------------------------------------===//
137
138 MethodType::MethodType(const Type *Result, const vector<const Type*> &Params, 
139                        bool IsVarArgs) : DerivedType("", MethodTyID), 
140     ResultType(PATypeHandle<Type>(Result, this)),
141     isVarArgs(IsVarArgs) {
142   ParamTys.reserve(Params.size());
143   for (unsigned i = 0; i < Params.size(); ++i)
144     ParamTys.push_back(PATypeHandle<Type>(Params[i], this));
145
146   setDerivedTypeProperties();
147 }
148
149 ArrayType::ArrayType(const Type *ElType, int NumEl)
150   : DerivedType("", ArrayTyID), ElementType(PATypeHandle<Type>(ElType, this)) {
151   NumElements = NumEl;
152   setDerivedTypeProperties();
153 }
154
155 StructType::StructType(const vector<const Type*> &Types)
156   : DerivedType("", StructTyID) {
157   ETypes.reserve(Types.size());
158   for (unsigned i = 0; i < Types.size(); ++i) {
159     assert(Types[i] != Type::VoidTy && "Void type in method prototype!!");
160     ETypes.push_back(PATypeHandle<Type>(Types[i], this));
161   }
162   setDerivedTypeProperties();
163 }
164
165 PointerType::PointerType(const Type *E) : DerivedType("", PointerTyID),
166                           ValueType(PATypeHandle<Type>(E, this)) {
167   setDerivedTypeProperties();
168 }
169
170 OpaqueType::OpaqueType() : DerivedType("", OpaqueTyID) {
171   setAbstract(true);
172   setDescription("opaque"+utostr(getUniqueID()));
173 #ifdef DEBUG_MERGE_TYPES
174   cerr << "Derived new type: " << getDescription() << endl;
175 #endif
176 }
177
178
179
180
181 //===----------------------------------------------------------------------===//
182 //               Derived Type setDerivedTypeProperties Function
183 //===----------------------------------------------------------------------===//
184
185 // getTypeProps - This is a recursive function that walks a type hierarchy
186 // calculating the description for a type and whether or not it is abstract or
187 // recursive.  Worst case it will have to do a lot of traversing if you have
188 // some whacko opaque types, but in most cases, it will do some simple stuff
189 // when it hits non-abstract types that aren't recursive.
190 //
191 static string getTypeProps(const Type *Ty, vector<const Type *> &TypeStack,
192                            bool &isAbstract, bool &isRecursive) {
193   string Result;
194   if (!Ty->isAbstract() && !Ty->isRecursive() && // Base case for the recursion
195       Ty->getDescription().size()) {
196     Result = Ty->getDescription();               // Primitive = leaf type
197   } else if (isa<OpaqueType>(Ty)) {              // Base case for the recursion
198     Result = Ty->getDescription();               // Opaque = leaf type
199     isAbstract = true;                           // This whole type is abstract!
200   } else {
201     // Check to see if the Type is already on the stack...
202     unsigned Slot = 0, CurSize = TypeStack.size();
203     while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
204     
205     // This is another base case for the recursion.  In this case, we know 
206     // that we have looped back to a type that we have previously visited.
207     // Generate the appropriate upreference to handle this.
208     // 
209     if (Slot < CurSize) {
210       Result = "\\" + utostr(CurSize-Slot);       // Here's the upreference
211       isRecursive = true;                         // We know we are recursive
212     } else {                      // Recursive case: abstract derived type...
213       TypeStack.push_back(Ty);    // Add us to the stack..
214       
215       switch (Ty->getPrimitiveID()) {
216       case Type::MethodTyID: {
217         const MethodType *MTy = cast<const MethodType>(Ty);
218         Result = getTypeProps(MTy->getReturnType(), TypeStack,
219                               isAbstract, isRecursive)+" (";
220         for (MethodType::ParamTypes::const_iterator
221                I = MTy->getParamTypes().begin(),
222                E = MTy->getParamTypes().end(); I != E; ++I) {
223           if (I != MTy->getParamTypes().begin())
224             Result += ", ";
225           Result += getTypeProps(*I, TypeStack, isAbstract, isRecursive);
226         }
227         if (MTy->isVarArg()) {
228           if (!MTy->getParamTypes().empty()) Result += ", ";
229           Result += "...";
230         }
231         Result += ")";
232         break;
233       }
234       case Type::StructTyID: {
235         const StructType *STy = cast<const StructType>(Ty);
236         Result = "{ ";
237         for (StructType::ElementTypes::const_iterator
238                I = STy->getElementTypes().begin(),
239                E = STy->getElementTypes().end(); I != E; ++I) {
240           if (I != STy->getElementTypes().begin())
241             Result += ", ";
242           Result += getTypeProps(*I, TypeStack, isAbstract, isRecursive);
243         }
244         Result += " }";
245         break;
246       }
247       case Type::PointerTyID: {
248         const PointerType *PTy = cast<const PointerType>(Ty);
249         Result = getTypeProps(PTy->getValueType(), TypeStack,
250                               isAbstract, isRecursive) + " *";
251         break;
252       }
253       case Type::ArrayTyID: {
254         const ArrayType *ATy = cast<const ArrayType>(Ty);
255         int NumElements = ATy->getNumElements();
256         Result = "[";
257         if (NumElements != -1) Result += itostr(NumElements) + " x ";
258         Result += getTypeProps(ATy->getElementType(), TypeStack,
259                                isAbstract, isRecursive) + "]";
260         break;
261       }
262       default:
263         assert(0 && "Unhandled case in getTypeProps!");
264         Result = "<error>";
265       }
266
267       TypeStack.pop_back();       // Remove self from stack...
268     }
269   }
270   return Result;
271 }
272
273
274 // setDerivedTypeProperties - This function is used to calculate the
275 // isAbstract, isRecursive, and the Description settings for a type.  The
276 // getTypeProps function does all the dirty work.
277 //
278 void DerivedType::setDerivedTypeProperties() {
279   vector<const Type *> TypeStack;
280   bool isAbstract = false, isRecursive = false;
281   
282   setDescription(getTypeProps(this, TypeStack, isAbstract, isRecursive));
283   setAbstract(isAbstract);
284   setRecursive(isRecursive);
285 }
286
287
288 //===----------------------------------------------------------------------===//
289 //                      Type Structural Equality Testing
290 //===----------------------------------------------------------------------===//
291
292 // TypesEqual - Two types are considered structurally equal if they have the
293 // same "shape": Every level and element of the types have identical primitive
294 // ID's, and the graphs have the same edges/nodes in them.  Nodes do not have to
295 // be pointer equals to be equivalent though.  This uses an optimistic algorithm
296 // that assumes that two graphs are the same until proven otherwise.
297 //
298 static bool TypesEqual(const Type *Ty, const Type *Ty2,
299                        map<const Type *, const Type *> &EqTypes) {
300   if (Ty == Ty2) return true;
301   if (Ty->getPrimitiveID() != Ty2->getPrimitiveID()) return false;
302   if (Ty->isPrimitiveType()) return true;
303
304   if (Ty != Ty2) {
305     map<const Type*, const Type*>::iterator I = EqTypes.find(Ty);
306     if (I != EqTypes.end())
307       return I->second == Ty2;    // Looping back on a type, check for equality
308
309     // Otherwise, add the mapping to the table to make sure we don't get
310     // recursion on the types...
311     EqTypes.insert(make_pair(Ty, Ty2));
312   }
313
314   // Iterate over the types and make sure the the contents are equivalent...
315   Type::subtype_iterator I  = Ty ->subtype_begin(), IE  = Ty ->subtype_end();
316   Type::subtype_iterator I2 = Ty2->subtype_begin(), IE2 = Ty2->subtype_end();
317   for (; I != IE && I2 != IE2; ++I, ++I2)
318     if (!TypesEqual(*I, *I2, EqTypes)) return false;
319
320   // Two really annoying special cases that breaks an otherwise nice simple
321   // algorithm is the fact that arraytypes have sizes that differentiates types,
322   // and that method types can be varargs or not.  Consider this now.
323   if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
324     if (ATy->getNumElements() != cast<const ArrayType>(Ty2)->getNumElements())
325       return false;
326   } else if (const MethodType *MTy = dyn_cast<MethodType>(Ty)) {
327     if (MTy->isVarArg() != cast<const MethodType>(Ty2)->isVarArg())
328       return false;
329   }
330
331
332   return I == IE && I2 == IE2;    // Types equal if both iterators are done
333 }
334
335 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
336   map<const Type *, const Type *> EqTypes;
337   return TypesEqual(Ty, Ty2, EqTypes);
338 }
339
340
341
342 //===----------------------------------------------------------------------===//
343 //                       Derived Type Factory Functions
344 //===----------------------------------------------------------------------===//
345
346 // TypeMap - Make sure that only one instance of a particular type may be
347 // created on any given run of the compiler... note that this involves updating
348 // our map if an abstract type gets refined somehow...
349 //
350 template<class ValType, class TypeClass>
351 class TypeMap : public AbstractTypeUser {
352   typedef map<ValType, PATypeHandle<TypeClass> > MapTy;
353   MapTy Map;
354 public:
355
356   ~TypeMap() { print("ON EXIT"); }
357
358   inline TypeClass *get(const ValType &V) {
359     map<ValType, PATypeHandle<TypeClass> >::iterator I = Map.find(V);
360     // TODO: FIXME: When Types are not CONST.
361     return (I != Map.end()) ? (TypeClass*)I->second.get() : 0;
362   }
363
364   inline void add(const ValType &V, TypeClass *T) {
365     Map.insert(make_pair(V, PATypeHandle<TypeClass>(T, this)));
366     print("add");
367   }
368
369   // containsEquivalent - Return true if the typemap contains a type that is
370   // structurally equivalent to the specified type.
371   //
372   inline const TypeClass *containsEquivalent(const TypeClass *Ty) {
373     for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
374       if (I->second.get() != Ty && TypesEqual(Ty, I->second.get()))
375         return (TypeClass*)I->second.get();  // FIXME TODO when types not const
376     return 0;
377   }
378
379   // refineAbstractType - This is called when one of the contained abstract
380   // types gets refined... this simply removes the abstract type from our table.
381   // We expect that whoever refined the type will add it back to the table,
382   // corrected.
383   //
384   virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
385     if (OldTy == NewTy) return;
386 #ifdef DEBUG_MERGE_TYPES
387     cerr << "Removing Old type from Tab: " << (void*)OldTy << ", "
388          << OldTy->getDescription() << "  replacement == " << (void*)NewTy
389          << ", " << NewTy->getDescription() << endl;
390 #endif
391     for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
392       if (I->second == OldTy) {
393         Map.erase(I);
394         print("refineAbstractType after");
395         return;
396       }
397     assert(0 && "Abstract type not found in table!");
398   }
399
400   void remove(const ValType &OldVal) {
401     MapTy::iterator I = Map.find(OldVal);
402     assert(I != Map.end() && "TypeMap::remove, element not found!");
403     Map.erase(I);
404   }
405
406   void print(const char *Arg) {
407 #ifdef DEBUG_MERGE_TYPES
408     cerr << "TypeMap<>::" << Arg << " table contents:\n";
409     unsigned i = 0;
410     for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
411       cerr << " " << (++i) << ". " << I->second << " " 
412            << I->second->getDescription() << endl;
413 #endif
414   }
415 };
416
417
418 // ValTypeBase - This is the base class that is used by the various
419 // instantiations of TypeMap.  This class is an AbstractType user that notifies
420 // the underlying TypeMap when it gets modified.
421 //
422 template<class ValType, class TypeClass>
423 class ValTypeBase : public AbstractTypeUser {
424   TypeMap<ValType, TypeClass> &MyTable;
425 protected:
426   inline ValTypeBase(TypeMap<ValType, TypeClass> &tab) : MyTable(tab) {}
427
428   // Subclass should override this... to update self as usual
429   virtual void doRefinement(const DerivedType *OldTy, const Type *NewTy) = 0;
430   
431   virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
432     if (OldTy == NewTy) return;
433     TypeMap<ValType, TypeClass> &Table = MyTable;     // Copy MyTable reference
434     ValType Tmp(*(ValType*)this);                     // Copy this.
435     PATypeHandle<TypeClass> OldType(Table.get(*(ValType*)this), this);
436     Table.remove(*(ValType*)this);                    // Destroy's this!
437
438     // Refine temporary to new state...
439     Tmp.doRefinement(OldTy, NewTy); 
440
441     Table.add((ValType&)Tmp, (TypeClass*)OldType.get());
442   }
443 };
444
445
446
447 //===----------------------------------------------------------------------===//
448 // Method Type Factory and Value Class...
449 //
450
451 // MethodValType - Define a class to hold the key that goes into the TypeMap
452 //
453 class MethodValType : public ValTypeBase<MethodValType, MethodType> {
454   PATypeHandle<Type> RetTy;
455   vector<PATypeHandle<Type> > ArgTypes;
456   bool isVarArg;
457 public:
458   MethodValType(const Type *ret, const vector<const Type*> &args,
459                 bool IVA, TypeMap<MethodValType, MethodType> &Tab)
460     : ValTypeBase<MethodValType, MethodType>(Tab), RetTy(ret, this),
461       isVarArg(IVA) {
462     for (unsigned i = 0; i < args.size(); ++i)
463       ArgTypes.push_back(PATypeHandle<Type>(args[i], this));
464   }
465
466   // We *MUST* have an explicit copy ctor so that the TypeHandles think that
467   // this MethodValType owns them, not the old one!
468   //
469   MethodValType(const MethodValType &MVT) 
470     : ValTypeBase<MethodValType, MethodType>(MVT), RetTy(MVT.RetTy, this),
471       isVarArg(MVT.isVarArg) {
472     ArgTypes.reserve(MVT.ArgTypes.size());
473     for (unsigned i = 0; i < MVT.ArgTypes.size(); ++i)
474       ArgTypes.push_back(PATypeHandle<Type>(MVT.ArgTypes[i], this));
475   }
476
477   // Subclass should override this... to update self as usual
478   virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
479     if (RetTy == OldType) RetTy = NewType;
480     for (unsigned i = 0; i < ArgTypes.size(); ++i)
481       if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
482   }
483
484   inline bool operator<(const MethodValType &MTV) const {
485     if (RetTy.get() < MTV.RetTy.get()) return true;
486     if (RetTy.get() > MTV.RetTy.get()) return false;
487
488     if (ArgTypes < MTV.ArgTypes) return true;
489     return (ArgTypes == MTV.ArgTypes) && isVarArg < MTV.isVarArg;
490   }
491 };
492
493 // Define the actual map itself now...
494 static TypeMap<MethodValType, MethodType> MethodTypes;
495
496 // MethodType::get - The factory function for the MethodType class...
497 MethodType *MethodType::get(const Type *ReturnType, 
498                             const vector<const Type*> &Params,
499                             bool isVarArg) {
500   MethodValType VT(ReturnType, Params, isVarArg, MethodTypes);
501   MethodType *MT = MethodTypes.get(VT);
502   if (MT) return MT;
503
504   MethodTypes.add(VT, MT = new MethodType(ReturnType, Params, isVarArg));
505
506 #ifdef DEBUG_MERGE_TYPES
507   cerr << "Derived new type: " << MT << endl;
508 #endif
509   return MT;
510 }
511
512 //===----------------------------------------------------------------------===//
513 // Array Type Factory...
514 //
515 class ArrayValType : public ValTypeBase<ArrayValType, ArrayType> {
516   PATypeHandle<Type> ValTy;
517   int Size;
518 public:
519   ArrayValType(const Type *val, int sz, TypeMap<ArrayValType, ArrayType> &Tab)
520     : ValTypeBase<ArrayValType, ArrayType>(Tab), ValTy(val, this), Size(sz) {}
521
522   // We *MUST* have an explicit copy ctor so that the ValTy thinks that this
523   // ArrayValType owns it, not the old one!
524   //
525   ArrayValType(const ArrayValType &AVT) 
526     : ValTypeBase<ArrayValType, ArrayType>(AVT), ValTy(AVT.ValTy, this),
527       Size(AVT.Size) {}
528
529   // Subclass should override this... to update self as usual
530   virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
531     if (ValTy == OldType) ValTy = NewType;
532   }
533
534   inline bool operator<(const ArrayValType &MTV) const {
535     if (Size < MTV.Size) return true;
536     return Size == MTV.Size && ValTy.get() < MTV.ValTy.get();
537   }
538 };
539
540 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
541
542 ArrayType *ArrayType::get(const Type *ElementType, int NumElements = -1) {
543   assert(ElementType && "Can't get array of null types!");
544
545   ArrayValType AVT(ElementType, NumElements, ArrayTypes);
546   ArrayType *AT = ArrayTypes.get(AVT);
547   if (AT) return AT;           // Found a match, return it!
548
549   // Value not found.  Derive a new type!
550   ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
551
552 #ifdef DEBUG_MERGE_TYPES
553   cerr << "Derived new type: " << AT->getDescription() << endl;
554 #endif
555   return AT;
556 }
557
558 //===----------------------------------------------------------------------===//
559 // Struct Type Factory...
560 //
561
562 // StructValType - Define a class to hold the key that goes into the TypeMap
563 //
564 class StructValType : public ValTypeBase<StructValType, StructType> {
565   vector<PATypeHandle<Type> > ElTypes;
566 public:
567   StructValType(const vector<const Type*> &args,
568                 TypeMap<StructValType, StructType> &Tab)
569     : ValTypeBase<StructValType, StructType>(Tab) {
570     for (unsigned i = 0; i < args.size(); ++i)
571       ElTypes.push_back(PATypeHandle<Type>(args[i], this));
572   }
573
574   // We *MUST* have an explicit copy ctor so that the TypeHandles think that
575   // this StructValType owns them, not the old one!
576   //
577   StructValType(const StructValType &SVT) 
578     : ValTypeBase<StructValType, StructType>(SVT){
579     ElTypes.reserve(SVT.ElTypes.size());
580     for (unsigned i = 0; i < SVT.ElTypes.size(); ++i)
581       ElTypes.push_back(PATypeHandle<Type>(SVT.ElTypes[i], this));
582   }
583
584   // Subclass should override this... to update self as usual
585   virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
586     for (unsigned i = 0; i < ElTypes.size(); ++i)
587       if (ElTypes[i] == OldType) ElTypes[i] = NewType;
588   }
589
590   inline bool operator<(const StructValType &STV) const {
591     return ElTypes < STV.ElTypes;
592   }
593 };
594
595 static TypeMap<StructValType, StructType> StructTypes;
596
597 StructType *StructType::get(const vector<const Type*> &ETypes) {
598   StructValType STV(ETypes, StructTypes);
599   StructType *ST = StructTypes.get(STV);
600   if (ST) return ST;
601
602   // Value not found.  Derive a new type!
603   StructTypes.add(STV, ST = new StructType(ETypes));
604
605 #ifdef DEBUG_MERGE_TYPES
606   cerr << "Derived new type: " << ST->getDescription() << endl;
607 #endif
608   return ST;
609 }
610
611 //===----------------------------------------------------------------------===//
612 // Pointer Type Factory...
613 //
614
615 // PointerValType - Define a class to hold the key that goes into the TypeMap
616 //
617 class PointerValType : public ValTypeBase<PointerValType, PointerType> {
618   PATypeHandle<Type> ValTy;
619 public:
620   PointerValType(const Type *val, TypeMap<PointerValType, PointerType> &Tab)
621     : ValTypeBase<PointerValType, PointerType>(Tab), ValTy(val, this) {}
622
623   // We *MUST* have an explicit copy ctor so that the ValTy thinks that this
624   // PointerValType owns it, not the old one!
625   //
626   PointerValType(const PointerValType &PVT) 
627     : ValTypeBase<PointerValType, PointerType>(PVT), ValTy(PVT.ValTy, this) {}
628
629   // Subclass should override this... to update self as usual
630   virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
631     if (ValTy == OldType) ValTy = NewType;
632   }
633
634   inline bool operator<(const PointerValType &MTV) const {
635     return ValTy.get() < MTV.ValTy.get();
636   }
637 };
638
639 static TypeMap<PointerValType, PointerType> PointerTypes;
640
641 PointerType *PointerType::get(const Type *ValueType) {
642   assert(ValueType && "Can't get a pointer to <null> type!");
643   PointerValType PVT(ValueType, PointerTypes);
644
645   PointerType *PT = PointerTypes.get(PVT);
646   if (PT) return PT;
647
648   // Value not found.  Derive a new type!
649   PointerTypes.add(PVT, PT = new PointerType(ValueType));
650
651 #ifdef DEBUG_MERGE_TYPES
652   cerr << "Derived new type: " << PT->getDescription() << endl;
653 #endif
654   return PT;
655 }
656
657
658
659 //===----------------------------------------------------------------------===//
660 //                     Derived Type Refinement Functions
661 //===----------------------------------------------------------------------===//
662
663 // removeAbstractTypeUser - Notify an abstract type that a user of the class
664 // no longer has a handle to the type.  This function is called primarily by
665 // the PATypeHandle class.  When there are no users of the abstract type, it
666 // is anihilated, because there is no way to get a reference to it ever again.
667 //
668 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
669   // Search from back to front because we will notify users from back to
670   // front.  Also, it is likely that there will be a stack like behavior to
671   // users that register and unregister users.
672   //
673   for (unsigned i = AbstractTypeUsers.size(); i > 0; --i) {
674     if (AbstractTypeUsers[i-1] == U) {
675       AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i-1);
676       
677 #ifdef DEBUG_MERGE_TYPES
678       cerr << "  removeAbstractTypeUser[" << (void*)this << ", "
679            << getDescription() << "][" << AbstractTypeUsers.size()
680            << "] User = " << U << endl;
681 #endif
682
683       if (AbstractTypeUsers.empty()) {
684 #ifdef DEBUG_MERGE_TYPES
685         cerr << "DELETEing unused abstract type: " << getDescription()
686              << " " << (void*)this << endl;
687 #endif
688         delete this;                  // No users of this abstract type!
689       }
690       return;
691     }
692   }
693   assert(isAbstract() && "removeAbstractTypeUser: Type not abstract!");
694   assert(0 && "AbstractTypeUser not in user list!");
695 }
696
697
698 // refineAbstractTypeTo - This function is used to when it is discovered that
699 // the 'this' abstract type is actually equivalent to the NewType specified.
700 // This causes all users of 'this' to switch to reference the more concrete
701 // type NewType and for 'this' to be deleted.
702 //
703 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
704   assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
705   assert(this != NewType && "Can't refine to myself!");
706
707 #ifdef DEBUG_MERGE_TYPES
708   cerr << "REFINING abstract type [" << (void*)this << " " << getDescription()
709        << "] to [" << (void*)NewType << " " << NewType->getDescription()
710        << "]!\n";
711 #endif
712
713
714   // Make sure to put the type to be refined to into a holder so that if IT gets
715   // refined, that we will not continue using a dead reference...
716   //
717   PATypeHolder<Type> NewTy(NewType);
718
719   // Add a self use of the current type so that we don't delete ourself until
720   // after this while loop.  We are careful to never invoke refine on ourself,
721   // so this extra reference shouldn't be a problem.  Note that we must only
722   // remove a single reference at the end, but we must tolerate multiple self
723   // references because we could be refineAbstractTypeTo'ing recursively on the
724   // same type.
725   //
726   addAbstractTypeUser(this);
727
728   // Count the number of self uses.  Stop looping when sizeof(list) == NSU.
729   unsigned NumSelfUses = 0;
730
731   // Iterate over all of the uses of this type, invoking callback.  Each user
732   // should remove itself from our use list automatically.
733   //
734   while (AbstractTypeUsers.size() > NumSelfUses) {
735     AbstractTypeUser *User = AbstractTypeUsers.back();
736
737     if (User == this) {
738       // Move self use to the start of the list.  Increment NSU.
739       swap(AbstractTypeUsers.back(), AbstractTypeUsers[NumSelfUses++]);
740     } else {
741       unsigned OldSize = AbstractTypeUsers.size();
742 #ifdef DEBUG_MERGE_TYPES
743       cerr << " REFINING user " << OldSize-1 << " of abstract type ["
744            << (void*)this << " " << getDescription() << "] to [" 
745            << (void*)NewTy.get() << " " << NewTy->getDescription() << "]!\n";
746 #endif
747       AbstractTypeUsers.back()->refineAbstractType(this, NewTy);
748
749       assert(AbstractTypeUsers.size() != OldSize &&
750              "AbsTyUser did not remove self from user list!");
751     }
752   }
753
754   // Remove a single self use, even though there may be several here. This will
755   // probably 'delete this', so no instance variables may be used after this
756   // occurs...
757   assert(AbstractTypeUsers.back() == this && "Only self uses should be left!");
758   removeAbstractTypeUser(this);
759 }
760
761
762 // typeIsRefined - Notify AbstractTypeUsers of this type that the current type
763 // has been refined a bit.  The pointer is still valid and still should be
764 // used, but the subtypes have changed.
765 //
766 void DerivedType::typeIsRefined() {
767   assert(isRefining >= 0 && isRefining <= 2 && "isRefining out of bounds!");
768   if (isRefining == 2) return;  // Kill recursion here...
769   ++isRefining;
770
771 #ifdef DEBUG_MERGE_TYPES
772   cerr << "typeIsREFINED type: " << (void*)this <<" "<<getDescription() << endl;
773 #endif
774   for (unsigned i = 0; i < AbstractTypeUsers.size(); ) {
775     AbstractTypeUser *ATU = AbstractTypeUsers[i];
776 #ifdef DEBUG_MERGE_TYPES
777     cerr << " typeIsREFINED user " << i << " of abstract type ["
778          << (void*)this << " " << getDescription() << "]\n";
779 #endif
780     ATU->refineAbstractType(this, this);
781     
782     // If the user didn't remove itself from the list, continue...
783     if (AbstractTypeUsers.size() > i && AbstractTypeUsers[i] == ATU)
784       ++i;
785   }
786
787   --isRefining;
788 }
789   
790
791
792
793 // refineAbstractType - Called when a contained type is found to be more
794 // concrete - this could potentially change us from an abstract type to a
795 // concrete type.
796 //
797 void MethodType::refineAbstractType(const DerivedType *OldType,
798                                     const Type *NewType) {
799 #ifdef DEBUG_MERGE_TYPES
800   cerr << "MethodTy::refineAbstractTy(" << (void*)OldType << "[" 
801        << OldType->getDescription() << "], " << (void*)NewType << " [" 
802        << NewType->getDescription() << "])\n";
803 #endif
804
805   if (OldType == ResultType) {
806     ResultType = NewType;
807   } else {
808     unsigned i;
809     for (i = 0; i < ParamTys.size(); ++i)
810       if (OldType == ParamTys[i]) {
811         ParamTys[i] = NewType;
812         break;
813       }
814     assert(i != ParamTys.size() && "Did not contain oldtype!");
815   }
816
817
818   // Notify everyone that I have changed!
819   if (const MethodType *MTy = MethodTypes.containsEquivalent(this)) {
820 #ifndef _NDEBUG
821     // Calculate accurate name for debugging purposes
822     vector<const Type *> TypeStack;
823     bool isAbstract = false, isRecursive = false;
824     setDescription(getTypeProps(this, TypeStack, isAbstract, isRecursive));
825 #endif
826
827 #ifdef DEBUG_MERGE_TYPES
828     cerr << "Type " << (void*)this << " equilivant to existing " << (void*)MTy
829          << " - destroying!\n";
830 #endif
831     refineAbstractTypeTo(MTy);      // Different type altogether...
832     return;
833   }
834   setDerivedTypeProperties();  // Update the name and isAbstract
835   typeIsRefined();
836 }
837
838
839 // refineAbstractType - Called when a contained type is found to be more
840 // concrete - this could potentially change us from an abstract type to a
841 // concrete type.
842 //
843 void ArrayType::refineAbstractType(const DerivedType *OldType,
844                                    const Type *NewType) {
845 #ifdef DEBUG_MERGE_TYPES
846   cerr << "ArrayTy::refineAbstractTy(" << (void*)OldType << "[" 
847        << OldType->getDescription() << "], " << (void*)NewType << " [" 
848        << NewType->getDescription() << "])\n";
849 #endif
850   assert(OldType == ElementType && "Cannot refine from OldType!");
851   ElementType = NewType;
852
853   // Notify everyone that I have changed!
854   if (const ArrayType *ATy = ArrayTypes.containsEquivalent(this)) {
855 #ifndef _NDEBUG
856     // Calculate accurate name for debugging purposes
857     vector<const Type *> TypeStack;
858     bool isAbstract = false, isRecursive = false;
859     setDescription(getTypeProps(this, TypeStack, isAbstract, isRecursive));
860 #endif
861
862 #ifdef DEBUG_MERGE_TYPES
863     cerr << "Type " << (void*)this << " equilivant to existing " << (void*)ATy
864          << " - destroying!\n";
865 #endif
866     refineAbstractTypeTo(ATy);      // Different type altogether...
867     return;
868   }
869   setDerivedTypeProperties();   // Update the name and isAbstract
870   typeIsRefined();              // Same type, different contents...
871 }
872
873
874 // refineAbstractType - Called when a contained type is found to be more
875 // concrete - this could potentially change us from an abstract type to a
876 // concrete type.
877 //
878 void StructType::refineAbstractType(const DerivedType *OldType,
879                                     const Type *NewType) {
880 #ifdef DEBUG_MERGE_TYPES
881   cerr << "StructTy::refineAbstractTy(" << (void*)OldType << "[" 
882        << OldType->getDescription() << "], " << (void*)NewType << " [" 
883        << NewType->getDescription() << "])\n";
884 #endif
885
886   if (OldType != NewType) {
887     unsigned i;
888     for (i = 0; i < ETypes.size(); ++i)
889       if (OldType == ETypes[i]) {
890         ETypes[i] = NewType;
891         break;
892       }
893     assert(i != ETypes.size() && "Did not contain oldtype!");
894   }
895
896   vector<const Type *> ElTypes(
897       map_iterator(ETypes.begin(), mem_fun_ref(&PATypeHandle<Type>::get)),
898       map_iterator(ETypes.end()  , mem_fun_ref(&PATypeHandle<Type>::get)));
899
900
901   // Notify everyone that I have changed!
902   if (const StructType *STy = StructTypes.containsEquivalent(this)) {
903 #ifndef _NDEBUG
904     // Calculate accurate name for debugging purposes
905     vector<const Type *> TypeStack;
906     bool isAbstract = false, isRecursive = false;
907     setDescription(getTypeProps(this, TypeStack, isAbstract, isRecursive));
908 #endif
909
910 #ifdef DEBUG_MERGE_TYPES
911     cerr << "Type " << (void*)this << " equilivant to existing " << (void*)STy
912          << " - destroying!\n";
913 #endif
914     refineAbstractTypeTo(STy);      // Different type altogether...
915     return;
916   }
917   setDerivedTypeProperties();          // Update the name and isAbstract
918   typeIsRefined();                   // Same type, different contents...
919 }
920
921 // refineAbstractType - Called when a contained type is found to be more
922 // concrete - this could potentially change us from an abstract type to a
923 // concrete type.
924 //
925 void PointerType::refineAbstractType(const DerivedType *OldType,
926                                      const Type *NewType) {
927 #ifdef DEBUG_MERGE_TYPES
928   cerr << "PointerTy::refineAbstractTy(" << (void*)OldType << "[" 
929        << OldType->getDescription() << "], " << (void*)NewType << " [" 
930        << NewType->getDescription() << "])\n";
931 #endif
932   assert(OldType == ValueType && "Cannot refine from OldType!");
933   ValueType = NewType;
934
935   // Notify everyone that I have changed!
936   if (const PointerType *PTy = PointerTypes.containsEquivalent(this)) {
937 #ifndef _NDEBUG
938     // Calculate accurate name for debugging purposes
939     vector<const Type *> TypeStack;
940     bool isAbstract = false, isRecursive = false;
941     setDescription(getTypeProps(this, TypeStack, isAbstract, isRecursive));
942 #endif
943
944 #ifdef DEBUG_MERGE_TYPES
945     cerr << "Type " << (void*)this << " equilivant to existing " << (void*)PTy
946          << " - destroying!\n";
947 #endif
948     refineAbstractTypeTo(PTy);      // Different type altogether...
949     return;
950   }
951   setDerivedTypeProperties();  // Update the name and isAbstract
952   typeIsRefined();                   // Same type, different contents...
953 }
954