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