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