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