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