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