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