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