Remove obsolete method
[oota-llvm.git] / lib / VMCore / Type.cpp
1 //===-- Type.cpp - Implement the Type class -------------------------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Type class for the VMCore library.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/DerivedTypes.h"
15 #include "llvm/SymbolTable.h"
16 #include "llvm/Constants.h"
17 #include "Support/DepthFirstIterator.h"
18 #include "Support/StringExtras.h"
19 #include "Support/STLExtras.h"
20 #include <algorithm>
21 using namespace llvm;
22
23 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
24 // created and later destroyed, all in an effort to make sure that there is only
25 // a single canonical version of a type.
26 //
27 //#define DEBUG_MERGE_TYPES 1
28
29
30 //===----------------------------------------------------------------------===//
31 //                         Type Class Implementation
32 //===----------------------------------------------------------------------===//
33
34 static unsigned CurUID = 0;
35 static std::vector<const Type *> UIDMappings;
36
37 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
38 // for types as they are needed.  Because resolution of types must invalidate
39 // all of the abstract type descriptions, we keep them in a seperate map to make
40 // this easy.
41 static std::map<const Type*, std::string> ConcreteTypeDescriptions;
42 static std::map<const Type*, std::string> AbstractTypeDescriptions;
43
44 Type::Type(const std::string &name, PrimitiveID id)
45   : Value(Type::TypeTy, Value::TypeVal), ForwardType(0) {
46   if (!name.empty())
47     ConcreteTypeDescriptions[this] = name;
48   ID = id;
49   Abstract = false;
50   UID = CurUID++;       // Assign types UID's as they are created
51   UIDMappings.push_back(this);
52 }
53
54 void Type::setName(const std::string &Name, SymbolTable *ST) {
55   assert(ST && "Type::setName - Must provide symbol table argument!");
56
57   if (Name.size()) ST->insert(Name, this);
58 }
59
60
61 const Type *Type::getUniqueIDType(unsigned UID) {
62   assert(UID < UIDMappings.size() && 
63          "Type::getPrimitiveType: UID out of range!");
64   return UIDMappings[UID];
65 }
66
67 const Type *Type::getPrimitiveType(PrimitiveID IDNumber) {
68   switch (IDNumber) {
69   case VoidTyID  : return VoidTy;
70   case BoolTyID  : return BoolTy;
71   case UByteTyID : return UByteTy;
72   case SByteTyID : return SByteTy;
73   case UShortTyID: return UShortTy;
74   case ShortTyID : return ShortTy;
75   case UIntTyID  : return UIntTy;
76   case IntTyID   : return IntTy;
77   case ULongTyID : return ULongTy;
78   case LongTyID  : return LongTy;
79   case FloatTyID : return FloatTy;
80   case DoubleTyID: return DoubleTy;
81   case TypeTyID  : return TypeTy;
82   case LabelTyID : return LabelTy;
83   default:
84     return 0;
85   }
86 }
87
88 // isLosslesslyConvertibleTo - Return true if this type can be converted to
89 // 'Ty' without any reinterpretation of bits.  For example, uint to int.
90 //
91 bool Type::isLosslesslyConvertibleTo(const Type *Ty) const {
92   if (this == Ty) return true;
93   if ((!isPrimitiveType()    && !isa<PointerType>(this)) ||
94       (!isa<PointerType>(Ty) && !Ty->isPrimitiveType())) return false;
95
96   if (getPrimitiveID() == Ty->getPrimitiveID())
97     return true;  // Handles identity cast, and cast of differing pointer types
98
99   // Now we know that they are two differing primitive or pointer types
100   switch (getPrimitiveID()) {
101   case Type::UByteTyID:   return Ty == Type::SByteTy;
102   case Type::SByteTyID:   return Ty == Type::UByteTy;
103   case Type::UShortTyID:  return Ty == Type::ShortTy;
104   case Type::ShortTyID:   return Ty == Type::UShortTy;
105   case Type::UIntTyID:    return Ty == Type::IntTy;
106   case Type::IntTyID:     return Ty == Type::UIntTy;
107   case Type::ULongTyID:   return Ty == Type::LongTy;
108   case Type::LongTyID:    return Ty == Type::ULongTy;
109   case Type::PointerTyID: return isa<PointerType>(Ty);
110   default:
111     return false;  // Other types have no identity values
112   }
113 }
114
115 // getPrimitiveSize - Return the basic size of this type if it is a primitive
116 // type.  These are fixed by LLVM and are not target dependent.  This will
117 // return zero if the type does not have a size or is not a primitive type.
118 //
119 unsigned Type::getPrimitiveSize() const {
120   switch (getPrimitiveID()) {
121 #define HANDLE_PRIM_TYPE(TY,SIZE)  case TY##TyID: return SIZE;
122 #include "llvm/Type.def"
123   default: return 0;
124   }
125 }
126
127
128 /// getForwardedTypeInternal - This method is used to implement the union-find
129 /// algorithm for when a type is being forwarded to another type.
130 const Type *Type::getForwardedTypeInternal() const {
131   assert(ForwardType && "This type is not being forwarded to another type!");
132   
133   // Check to see if the forwarded type has been forwarded on.  If so, collapse
134   // the forwarding links.
135   const Type *RealForwardedType = ForwardType->getForwardedType();
136   if (!RealForwardedType)
137     return ForwardType;  // No it's not forwarded again
138
139   // Yes, it is forwarded again.  First thing, add the reference to the new
140   // forward type.
141   if (RealForwardedType->isAbstract())
142     cast<DerivedType>(RealForwardedType)->addRef();
143
144   // Now drop the old reference.  This could cause ForwardType to get deleted.
145   cast<DerivedType>(ForwardType)->dropRef();
146   
147   // Return the updated type.
148   ForwardType = RealForwardedType;
149   return ForwardType;
150 }
151
152 // getTypeDescription - This is a recursive function that walks a type hierarchy
153 // calculating the description for a type.
154 //
155 static std::string getTypeDescription(const Type *Ty,
156                                       std::vector<const Type *> &TypeStack) {
157   if (isa<OpaqueType>(Ty)) {                     // Base case for the recursion
158     std::map<const Type*, std::string>::iterator I =
159       AbstractTypeDescriptions.lower_bound(Ty);
160     if (I != AbstractTypeDescriptions.end() && I->first == Ty)
161       return I->second;
162     std::string Desc = "opaque"+utostr(Ty->getUniqueID());
163     AbstractTypeDescriptions.insert(std::make_pair(Ty, Desc));
164     return Desc;
165   }
166   
167   if (!Ty->isAbstract()) {                       // Base case for the recursion
168     std::map<const Type*, std::string>::iterator I =
169       ConcreteTypeDescriptions.find(Ty);
170     if (I != ConcreteTypeDescriptions.end()) return I->second;
171   }
172       
173   // Check to see if the Type is already on the stack...
174   unsigned Slot = 0, CurSize = TypeStack.size();
175   while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
176   
177   // This is another base case for the recursion.  In this case, we know 
178   // that we have looped back to a type that we have previously visited.
179   // Generate the appropriate upreference to handle this.
180   // 
181   if (Slot < CurSize)
182     return "\\" + utostr(CurSize-Slot);         // Here's the upreference
183
184   // Recursive case: derived types...
185   std::string Result;
186   TypeStack.push_back(Ty);    // Add us to the stack..
187       
188   switch (Ty->getPrimitiveID()) {
189   case Type::FunctionTyID: {
190     const FunctionType *FTy = cast<FunctionType>(Ty);
191     Result = getTypeDescription(FTy->getReturnType(), TypeStack) + " (";
192     for (FunctionType::param_iterator I = FTy->param_begin(),
193            E = FTy->param_end(); I != E; ++I) {
194       if (I != FTy->param_begin())
195         Result += ", ";
196       Result += getTypeDescription(*I, TypeStack);
197     }
198     if (FTy->isVarArg()) {
199       if (FTy->getNumParams()) Result += ", ";
200       Result += "...";
201     }
202     Result += ")";
203     break;
204   }
205   case Type::StructTyID: {
206     const StructType *STy = cast<StructType>(Ty);
207     Result = "{ ";
208     for (StructType::element_iterator I = STy->element_begin(),
209            E = STy->element_end(); I != E; ++I) {
210       if (I != STy->element_begin())
211         Result += ", ";
212       Result += getTypeDescription(*I, TypeStack);
213     }
214     Result += " }";
215     break;
216   }
217   case Type::PointerTyID: {
218     const PointerType *PTy = cast<PointerType>(Ty);
219     Result = getTypeDescription(PTy->getElementType(), TypeStack) + " *";
220     break;
221   }
222   case Type::ArrayTyID: {
223     const ArrayType *ATy = cast<ArrayType>(Ty);
224     unsigned NumElements = ATy->getNumElements();
225     Result = "[";
226     Result += utostr(NumElements) + " x ";
227     Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
228     break;
229   }
230   default:
231     Result = "<error>";
232     assert(0 && "Unhandled type in getTypeDescription!");
233   }
234
235   TypeStack.pop_back();       // Remove self from stack...
236
237   return Result;
238 }
239
240
241
242 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
243                                           const Type *Ty) {
244   std::map<const Type*, std::string>::iterator I = Map.find(Ty);
245   if (I != Map.end()) return I->second;
246     
247   std::vector<const Type *> TypeStack;
248   return Map[Ty] = getTypeDescription(Ty, TypeStack);
249 }
250
251
252 const std::string &Type::getDescription() const {
253   if (isAbstract())
254     return getOrCreateDesc(AbstractTypeDescriptions, this);
255   else
256     return getOrCreateDesc(ConcreteTypeDescriptions, this);
257 }
258
259
260 bool StructType::indexValid(const Value *V) const {
261   // Structure indexes require unsigned integer constants.
262   if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(V))
263     return CU->getValue() < ContainedTys.size();
264   return false;
265 }
266
267 // getTypeAtIndex - Given an index value into the type, return the type of the
268 // element.  For a structure type, this must be a constant value...
269 //
270 const Type *StructType::getTypeAtIndex(const Value *V) const {
271   assert(isa<Constant>(V) && "Structure index must be a constant!!");
272   unsigned Idx = cast<ConstantUInt>(V)->getValue();
273   assert(Idx < ContainedTys.size() && "Structure index out of range!");
274   assert(indexValid(V) && "Invalid structure index!"); // Duplicate check
275   return ContainedTys[Idx];
276 }
277
278
279 //===----------------------------------------------------------------------===//
280 //                           Auxiliary classes
281 //===----------------------------------------------------------------------===//
282 //
283 // These classes are used to implement specialized behavior for each different
284 // type.
285 //
286 struct SignedIntType : public Type {
287   SignedIntType(const std::string &Name, PrimitiveID id) : Type(Name, id) {}
288
289   // isSigned - Return whether a numeric type is signed.
290   virtual bool isSigned() const { return 1; }
291
292   // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
293   // virtual function invocation.
294   //
295   virtual bool isInteger() const { return 1; }
296 };
297
298 struct UnsignedIntType : public Type {
299   UnsignedIntType(const std::string &N, PrimitiveID id) : Type(N, id) {}
300
301   // isUnsigned - Return whether a numeric type is signed.
302   virtual bool isUnsigned() const { return 1; }
303
304   // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
305   // virtual function invocation.
306   //
307   virtual bool isInteger() const { return 1; }
308 };
309
310 struct OtherType : public Type {
311   OtherType(const std::string &N, PrimitiveID id) : Type(N, id) {}
312 };
313
314 static struct TypeType : public Type {
315   TypeType() : Type("type", TypeTyID) {}
316 } TheTypeTy;   // Implement the type that is global.
317
318
319 //===----------------------------------------------------------------------===//
320 //                           Static 'Type' data
321 //===----------------------------------------------------------------------===//
322
323 static OtherType       TheVoidTy  ("void"  , Type::VoidTyID);
324 static OtherType       TheBoolTy  ("bool"  , Type::BoolTyID);
325 static SignedIntType   TheSByteTy ("sbyte" , Type::SByteTyID);
326 static UnsignedIntType TheUByteTy ("ubyte" , Type::UByteTyID);
327 static SignedIntType   TheShortTy ("short" , Type::ShortTyID);
328 static UnsignedIntType TheUShortTy("ushort", Type::UShortTyID);
329 static SignedIntType   TheIntTy   ("int"   , Type::IntTyID); 
330 static UnsignedIntType TheUIntTy  ("uint"  , Type::UIntTyID);
331 static SignedIntType   TheLongTy  ("long"  , Type::LongTyID);
332 static UnsignedIntType TheULongTy ("ulong" , Type::ULongTyID);
333 static OtherType       TheFloatTy ("float" , Type::FloatTyID);
334 static OtherType       TheDoubleTy("double", Type::DoubleTyID);
335 static OtherType       TheLabelTy ("label" , Type::LabelTyID);
336
337 Type *Type::VoidTy   = &TheVoidTy;
338 Type *Type::BoolTy   = &TheBoolTy;
339 Type *Type::SByteTy  = &TheSByteTy;
340 Type *Type::UByteTy  = &TheUByteTy;
341 Type *Type::ShortTy  = &TheShortTy;
342 Type *Type::UShortTy = &TheUShortTy;
343 Type *Type::IntTy    = &TheIntTy;
344 Type *Type::UIntTy   = &TheUIntTy;
345 Type *Type::LongTy   = &TheLongTy;
346 Type *Type::ULongTy  = &TheULongTy;
347 Type *Type::FloatTy  = &TheFloatTy;
348 Type *Type::DoubleTy = &TheDoubleTy;
349 Type *Type::TypeTy   = &TheTypeTy;
350 Type *Type::LabelTy  = &TheLabelTy;
351
352
353 //===----------------------------------------------------------------------===//
354 //                          Derived Type Constructors
355 //===----------------------------------------------------------------------===//
356
357 FunctionType::FunctionType(const Type *Result,
358                            const std::vector<const Type*> &Params, 
359                            bool IsVarArgs) : DerivedType(FunctionTyID), 
360                                              isVarArgs(IsVarArgs) {
361   bool isAbstract = Result->isAbstract();
362   ContainedTys.reserve(Params.size()+1);
363   ContainedTys.push_back(PATypeHandle(Result, this));
364
365   for (unsigned i = 0; i != Params.size(); ++i) {
366     ContainedTys.push_back(PATypeHandle(Params[i], this));
367     isAbstract |= Params[i]->isAbstract();
368   }
369
370   // Calculate whether or not this type is abstract
371   setAbstract(isAbstract);
372 }
373
374 StructType::StructType(const std::vector<const Type*> &Types)
375   : CompositeType(StructTyID) {
376   ContainedTys.reserve(Types.size());
377   bool isAbstract = false;
378   for (unsigned i = 0; i < Types.size(); ++i) {
379     assert(Types[i] != Type::VoidTy && "Void type in method prototype!!");
380     ContainedTys.push_back(PATypeHandle(Types[i], this));
381     isAbstract |= Types[i]->isAbstract();
382   }
383
384   // Calculate whether or not this type is abstract
385   setAbstract(isAbstract);
386 }
387
388 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
389   : SequentialType(ArrayTyID, ElType) {
390   NumElements = NumEl;
391
392   // Calculate whether or not this type is abstract
393   setAbstract(ElType->isAbstract());
394 }
395
396 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
397   // Calculate whether or not this type is abstract
398   setAbstract(E->isAbstract());
399 }
400
401 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
402   setAbstract(true);
403 #ifdef DEBUG_MERGE_TYPES
404   std::cerr << "Derived new type: " << *this << "\n";
405 #endif
406 }
407
408 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
409 // another (more concrete) type, we must eliminate all references to other
410 // types, to avoid some circular reference problems.
411 void DerivedType::dropAllTypeUses() {
412   if (!ContainedTys.empty()) {
413     while (ContainedTys.size() > 1)
414       ContainedTys.pop_back();
415     
416     // The type must stay abstract.  To do this, we insert a pointer to a type
417     // that will never get resolved, thus will always be abstract.
418     static Type *AlwaysOpaqueTy = OpaqueType::get();
419     static PATypeHolder Holder(AlwaysOpaqueTy);
420     ContainedTys[0] = AlwaysOpaqueTy;
421   }
422 }
423
424 // isTypeAbstract - This is a recursive function that walks a type hierarchy
425 // calculating whether or not a type is abstract.  Worst case it will have to do
426 // a lot of traversing if you have some whacko opaque types, but in most cases,
427 // it will do some simple stuff when it hits non-abstract types that aren't
428 // recursive.
429 //
430 bool Type::isTypeAbstract() {
431   if (!isAbstract())                           // Base case for the recursion
432     return false;                              // Primitive = leaf type
433   
434   if (isa<OpaqueType>(this))                   // Base case for the recursion
435     return true;                               // This whole type is abstract!
436
437   // We have to guard against recursion.  To do this, we temporarily mark this
438   // type as concrete, so that if we get back to here recursively we will think
439   // it's not abstract, and thus not scan it again.
440   setAbstract(false);
441
442   // Scan all of the sub-types.  If any of them are abstract, than so is this
443   // one!
444   for (Type::subtype_iterator I = subtype_begin(), E = subtype_end();
445        I != E; ++I)
446     if (const_cast<Type*>(I->get())->isTypeAbstract()) {
447       setAbstract(true);        // Restore the abstract bit.
448       return true;              // This type is abstract if subtype is abstract!
449     }
450   
451   // Restore the abstract bit.
452   setAbstract(true);
453
454   // Nothing looks abstract here...
455   return false;
456 }
457
458
459 //===----------------------------------------------------------------------===//
460 //                      Type Structural Equality Testing
461 //===----------------------------------------------------------------------===//
462
463 // TypesEqual - Two types are considered structurally equal if they have the
464 // same "shape": Every level and element of the types have identical primitive
465 // ID's, and the graphs have the same edges/nodes in them.  Nodes do not have to
466 // be pointer equals to be equivalent though.  This uses an optimistic algorithm
467 // that assumes that two graphs are the same until proven otherwise.
468 //
469 static bool TypesEqual(const Type *Ty, const Type *Ty2,
470                        std::map<const Type *, const Type *> &EqTypes) {
471   if (Ty == Ty2) return true;
472   if (Ty->getPrimitiveID() != Ty2->getPrimitiveID()) return false;
473   if (isa<OpaqueType>(Ty))
474     return false;  // Two unequal opaque types are never equal
475
476   std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
477   if (It != EqTypes.end() && It->first == Ty)
478     return It->second == Ty2;    // Looping back on a type, check for equality
479
480   // Otherwise, add the mapping to the table to make sure we don't get
481   // recursion on the types...
482   EqTypes.insert(It, std::make_pair(Ty, Ty2));
483
484   // Two really annoying special cases that breaks an otherwise nice simple
485   // algorithm is the fact that arraytypes have sizes that differentiates types,
486   // and that function types can be varargs or not.  Consider this now.
487   //
488   if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
489     return TypesEqual(PTy->getElementType(),
490                       cast<PointerType>(Ty2)->getElementType(), EqTypes);
491   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
492     const StructType *STy2 = cast<StructType>(Ty2);
493     if (STy->getNumElements() != STy2->getNumElements()) return false;
494     for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
495       if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
496         return false;
497     return true;
498   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
499     const ArrayType *ATy2 = cast<ArrayType>(Ty2);
500     return ATy->getNumElements() == ATy2->getNumElements() &&
501            TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
502   } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
503     const FunctionType *FTy2 = cast<FunctionType>(Ty2);
504     if (FTy->isVarArg() != FTy2->isVarArg() ||
505         FTy->getNumParams() != FTy2->getNumParams() ||
506         !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
507       return false;
508     for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i)
509       if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
510         return false;
511     return true;
512   } else {
513     assert(0 && "Unknown derived type!");
514     return false;
515   }
516 }
517
518 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
519   std::map<const Type *, const Type *> EqTypes;
520   return TypesEqual(Ty, Ty2, EqTypes);
521 }
522
523 // TypeHasCycleThrough - Return true there is a path from CurTy to TargetTy in
524 // the type graph.  We know that Ty is an abstract type, so if we ever reach a
525 // non-abstract type, we know that we don't need to search the subgraph.
526 static bool TypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
527                                 std::set<const Type*> &VisitedTypes) {
528   if (TargetTy == CurTy) return true;
529   if (!CurTy->isAbstract()) return false;
530
531   std::set<const Type*>::iterator VTI = VisitedTypes.lower_bound(CurTy);
532   if (VTI != VisitedTypes.end() && *VTI == CurTy)
533     return false;
534   VisitedTypes.insert(VTI, CurTy);
535
536   for (Type::subtype_iterator I = CurTy->subtype_begin(),
537          E = CurTy->subtype_end(); I != E; ++I)
538     if (TypeHasCycleThrough(TargetTy, *I, VisitedTypes))
539       return true;
540   return false;
541 }
542
543
544 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
545 /// back to itself.
546 static bool TypeHasCycleThroughItself(const Type *Ty) {
547   assert(Ty->isAbstract() && "This code assumes that Ty was abstract!");
548   std::set<const Type*> VisitedTypes;
549   for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
550        I != E; ++I)
551     if (TypeHasCycleThrough(Ty, *I, VisitedTypes))
552       return true;
553   return false;
554 }
555
556
557 //===----------------------------------------------------------------------===//
558 //                       Derived Type Factory Functions
559 //===----------------------------------------------------------------------===//
560
561 // TypeMap - Make sure that only one instance of a particular type may be
562 // created on any given run of the compiler... note that this involves updating
563 // our map if an abstract type gets refined somehow.
564 //
565 namespace llvm {
566 template<class ValType, class TypeClass>
567 class TypeMap {
568   std::map<ValType, PATypeHolder> Map;
569
570   /// TypesByHash - Keep track of each type by its structure hash value.
571   ///
572   std::multimap<unsigned, PATypeHolder> TypesByHash;
573 public:
574   typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
575   ~TypeMap() { print("ON EXIT"); }
576
577   inline TypeClass *get(const ValType &V) {
578     iterator I = Map.find(V);
579     return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
580   }
581
582   inline void add(const ValType &V, TypeClass *Ty) {
583     Map.insert(std::make_pair(V, Ty));
584
585     // If this type has a cycle, remember it.
586     TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
587     print("add");
588   }
589
590   void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
591     std::multimap<unsigned, PATypeHolder>::iterator I = 
592       TypesByHash.lower_bound(Hash);
593     while (I->second != Ty) {
594       ++I;
595       assert(I != TypesByHash.end() && I->first == Hash);
596     }
597     TypesByHash.erase(I);
598   }
599
600   /// finishRefinement - This method is called after we have updated an existing
601   /// type with its new components.  We must now either merge the type away with
602   /// some other type or reinstall it in the map with it's new configuration.
603   /// The specified iterator tells us what the type USED to look like.
604   void finishRefinement(TypeClass *Ty, const DerivedType *OldType,
605                         const Type *NewType) {
606     assert((Ty->isAbstract() || !OldType->isAbstract()) &&
607            "Refining a non-abstract type!");
608 #ifdef DEBUG_MERGE_TYPES
609     std::cerr << "refineAbstractTy(" << (void*)OldType << "[" << *OldType
610               << "], " << (void*)NewType << " [" << *NewType << "])\n";
611 #endif
612
613     // Make a temporary type holder for the type so that it doesn't disappear on
614     // us when we erase the entry from the map.
615     PATypeHolder TyHolder = Ty;
616
617     // The old record is now out-of-date, because one of the children has been
618     // updated.  Remove the obsolete entry from the map.
619     Map.erase(ValType::get(Ty));
620
621     // Remember the structural hash for the type before we start hacking on it,
622     // in case we need it later.  Also, check to see if the type HAD a cycle
623     // through it, if so, we know it will when we hack on it.
624     unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
625
626     // Find the type element we are refining... and change it now!
627     for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
628       if (Ty->ContainedTys[i] == OldType) {
629         Ty->ContainedTys[i].removeUserFromConcrete();
630         Ty->ContainedTys[i] = NewType;
631       }
632
633     unsigned TypeHash = ValType::hashTypeStructure(Ty);
634     
635     // If there are no cycles going through this node, we can do a simple,
636     // efficient lookup in the map, instead of an inefficient nasty linear
637     // lookup.
638     bool TypeHasCycle = Ty->isAbstract() && TypeHasCycleThroughItself(Ty);
639     if (!TypeHasCycle) {
640       iterator I = Map.find(ValType::get(Ty));
641       if (I != Map.end()) {
642         // We already have this type in the table.  Get rid of the newly refined
643         // type.
644         assert(Ty->isAbstract() && "Replacing a non-abstract type?");
645         TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
646         
647         // Refined to a different type altogether?
648         RemoveFromTypesByHash(TypeHash, Ty);
649         Ty->refineAbstractTypeTo(NewTy);
650         return;
651       }
652       
653     } else {
654       // Now we check to see if there is an existing entry in the table which is
655       // structurally identical to the newly refined type.  If so, this type
656       // gets refined to the pre-existing type.
657       //
658       std::multimap<unsigned, PATypeHolder>::iterator I,E, Entry;
659       tie(I, E) = TypesByHash.equal_range(TypeHash);
660       Entry = E;
661       for (; I != E; ++I) {
662         if (I->second != Ty) {
663           if (TypesEqual(Ty, I->second)) {
664             assert(Ty->isAbstract() && "Replacing a non-abstract type?");
665             TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
666             
667             if (Entry == E) {
668               // Find the location of Ty in the TypesByHash structure.
669               while (I->second != Ty) {
670                 ++I;
671                 assert(I != E && "Structure doesn't contain type??");
672               }
673               Entry = I;
674             }
675
676             TypesByHash.erase(Entry);
677             Ty->refineAbstractTypeTo(NewTy);
678             return;
679           }
680         } else {
681           // Remember the position of 
682           Entry = I;
683         }
684       }
685     }
686
687     // If we succeeded, we need to insert the type into the cycletypes table.
688     // There are several cases here, depending on whether the original type
689     // had the same hash code and was itself cyclic.
690     if (TypeHash != OldTypeHash) {
691       RemoveFromTypesByHash(OldTypeHash, Ty);
692       TypesByHash.insert(std::make_pair(TypeHash, Ty));
693     }
694
695     // If there is no existing type of the same structure, we reinsert an
696     // updated record into the map.
697     Map.insert(std::make_pair(ValType::get(Ty), Ty));
698
699     // If the type is currently thought to be abstract, rescan all of our
700     // subtypes to see if the type has just become concrete!
701     if (Ty->isAbstract()) {
702       Ty->setAbstract(Ty->isTypeAbstract());
703
704       // If the type just became concrete, notify all users!
705       if (!Ty->isAbstract())
706         Ty->notifyUsesThatTypeBecameConcrete();
707     }
708   }
709   
710   void print(const char *Arg) const {
711 #ifdef DEBUG_MERGE_TYPES
712     std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
713     unsigned i = 0;
714     for (typename std::map<ValType, PATypeHolder>::const_iterator I
715            = Map.begin(), E = Map.end(); I != E; ++I)
716       std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " " 
717                 << *I->second.get() << "\n";
718 #endif
719   }
720
721   void dump() const { print("dump output"); }
722 };
723 }
724
725
726 //===----------------------------------------------------------------------===//
727 // Function Type Factory and Value Class...
728 //
729
730 // FunctionValType - Define a class to hold the key that goes into the TypeMap
731 //
732 namespace llvm {
733 class FunctionValType {
734   const Type *RetTy;
735   std::vector<const Type*> ArgTypes;
736   bool isVarArg;
737 public:
738   FunctionValType(const Type *ret, const std::vector<const Type*> &args,
739                   bool IVA) : RetTy(ret), isVarArg(IVA) {
740     for (unsigned i = 0; i < args.size(); ++i)
741       ArgTypes.push_back(args[i]);
742   }
743
744   static FunctionValType get(const FunctionType *FT);
745
746   static unsigned hashTypeStructure(const FunctionType *FT) {
747     return FT->getNumParams()*2+FT->isVarArg();
748   }
749
750   // Subclass should override this... to update self as usual
751   void doRefinement(const DerivedType *OldType, const Type *NewType) {
752     if (RetTy == OldType) RetTy = NewType;
753     for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
754       if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
755   }
756
757   inline bool operator<(const FunctionValType &MTV) const {
758     if (RetTy < MTV.RetTy) return true;
759     if (RetTy > MTV.RetTy) return false;
760
761     if (ArgTypes < MTV.ArgTypes) return true;
762     return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
763   }
764 };
765 }
766
767 // Define the actual map itself now...
768 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
769
770 FunctionValType FunctionValType::get(const FunctionType *FT) {
771   // Build up a FunctionValType
772   std::vector<const Type *> ParamTypes;
773   ParamTypes.reserve(FT->getNumParams());
774   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
775     ParamTypes.push_back(FT->getParamType(i));
776   return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
777 }
778
779
780 // FunctionType::get - The factory function for the FunctionType class...
781 FunctionType *FunctionType::get(const Type *ReturnType, 
782                                 const std::vector<const Type*> &Params,
783                                 bool isVarArg) {
784   FunctionValType VT(ReturnType, Params, isVarArg);
785   FunctionType *MT = FunctionTypes.get(VT);
786   if (MT) return MT;
787
788   FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
789
790 #ifdef DEBUG_MERGE_TYPES
791   std::cerr << "Derived new type: " << MT << "\n";
792 #endif
793   return MT;
794 }
795
796 //===----------------------------------------------------------------------===//
797 // Array Type Factory...
798 //
799 namespace llvm {
800 class ArrayValType {
801   const Type *ValTy;
802   unsigned Size;
803 public:
804   ArrayValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
805
806   static ArrayValType get(const ArrayType *AT) {
807     return ArrayValType(AT->getElementType(), AT->getNumElements());
808   }
809
810   static unsigned hashTypeStructure(const ArrayType *AT) {
811     return AT->getNumElements();
812   }
813
814   // Subclass should override this... to update self as usual
815   void doRefinement(const DerivedType *OldType, const Type *NewType) {
816     assert(ValTy == OldType);
817     ValTy = NewType;
818   }
819
820   inline bool operator<(const ArrayValType &MTV) const {
821     if (Size < MTV.Size) return true;
822     return Size == MTV.Size && ValTy < MTV.ValTy;
823   }
824 };
825 }
826 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
827
828
829 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
830   assert(ElementType && "Can't get array of null types!");
831
832   ArrayValType AVT(ElementType, NumElements);
833   ArrayType *AT = ArrayTypes.get(AVT);
834   if (AT) return AT;           // Found a match, return it!
835
836   // Value not found.  Derive a new type!
837   ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
838
839 #ifdef DEBUG_MERGE_TYPES
840   std::cerr << "Derived new type: " << *AT << "\n";
841 #endif
842   return AT;
843 }
844
845 //===----------------------------------------------------------------------===//
846 // Struct Type Factory...
847 //
848
849 namespace llvm {
850 // StructValType - Define a class to hold the key that goes into the TypeMap
851 //
852 class StructValType {
853   std::vector<const Type*> ElTypes;
854 public:
855   StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
856
857   static StructValType get(const StructType *ST) {
858     std::vector<const Type *> ElTypes;
859     ElTypes.reserve(ST->getNumElements());
860     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
861       ElTypes.push_back(ST->getElementType(i));
862     
863     return StructValType(ElTypes);
864   }
865
866   static unsigned hashTypeStructure(const StructType *ST) {
867     return ST->getNumElements();
868   }
869
870   // Subclass should override this... to update self as usual
871   void doRefinement(const DerivedType *OldType, const Type *NewType) {
872     for (unsigned i = 0; i < ElTypes.size(); ++i)
873       if (ElTypes[i] == OldType) ElTypes[i] = NewType;
874   }
875
876   inline bool operator<(const StructValType &STV) const {
877     return ElTypes < STV.ElTypes;
878   }
879 };
880 }
881
882 static TypeMap<StructValType, StructType> StructTypes;
883
884 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
885   StructValType STV(ETypes);
886   StructType *ST = StructTypes.get(STV);
887   if (ST) return ST;
888
889   // Value not found.  Derive a new type!
890   StructTypes.add(STV, ST = new StructType(ETypes));
891
892 #ifdef DEBUG_MERGE_TYPES
893   std::cerr << "Derived new type: " << *ST << "\n";
894 #endif
895   return ST;
896 }
897
898
899
900 //===----------------------------------------------------------------------===//
901 // Pointer Type Factory...
902 //
903
904 // PointerValType - Define a class to hold the key that goes into the TypeMap
905 //
906 namespace llvm {
907 class PointerValType {
908   const Type *ValTy;
909 public:
910   PointerValType(const Type *val) : ValTy(val) {}
911
912   static PointerValType get(const PointerType *PT) {
913     return PointerValType(PT->getElementType());
914   }
915
916   static unsigned hashTypeStructure(const PointerType *PT) {
917     return 0;
918   }
919
920   // Subclass should override this... to update self as usual
921   void doRefinement(const DerivedType *OldType, const Type *NewType) {
922     assert(ValTy == OldType);
923     ValTy = NewType;
924   }
925
926   bool operator<(const PointerValType &MTV) const {
927     return ValTy < MTV.ValTy;
928   }
929 };
930 }
931
932 static TypeMap<PointerValType, PointerType> PointerTypes;
933
934 PointerType *PointerType::get(const Type *ValueType) {
935   assert(ValueType && "Can't get a pointer to <null> type!");
936   PointerValType PVT(ValueType);
937
938   PointerType *PT = PointerTypes.get(PVT);
939   if (PT) return PT;
940
941   // Value not found.  Derive a new type!
942   PointerTypes.add(PVT, PT = new PointerType(ValueType));
943
944 #ifdef DEBUG_MERGE_TYPES
945   std::cerr << "Derived new type: " << *PT << "\n";
946 #endif
947   return PT;
948 }
949
950
951 //===----------------------------------------------------------------------===//
952 //                     Derived Type Refinement Functions
953 //===----------------------------------------------------------------------===//
954
955 // removeAbstractTypeUser - Notify an abstract type that a user of the class
956 // no longer has a handle to the type.  This function is called primarily by
957 // the PATypeHandle class.  When there are no users of the abstract type, it
958 // is annihilated, because there is no way to get a reference to it ever again.
959 //
960 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
961   // Search from back to front because we will notify users from back to
962   // front.  Also, it is likely that there will be a stack like behavior to
963   // users that register and unregister users.
964   //
965   unsigned i;
966   for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
967     assert(i != 0 && "AbstractTypeUser not in user list!");
968
969   --i;  // Convert to be in range 0 <= i < size()
970   assert(i < AbstractTypeUsers.size() && "Index out of range!");  // Wraparound?
971
972   AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
973       
974 #ifdef DEBUG_MERGE_TYPES
975   std::cerr << "  remAbstractTypeUser[" << (void*)this << ", "
976             << *this << "][" << i << "] User = " << U << "\n";
977 #endif
978     
979   if (AbstractTypeUsers.empty() && RefCount == 0 && isAbstract()) {
980 #ifdef DEBUG_MERGE_TYPES
981     std::cerr << "DELETEing unused abstract type: <" << *this
982               << ">[" << (void*)this << "]" << "\n";
983 #endif
984     delete this;                  // No users of this abstract type!
985   }
986 }
987
988
989 // refineAbstractTypeTo - This function is used to when it is discovered that
990 // the 'this' abstract type is actually equivalent to the NewType specified.
991 // This causes all users of 'this' to switch to reference the more concrete type
992 // NewType and for 'this' to be deleted.
993 //
994 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
995   assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
996   assert(this != NewType && "Can't refine to myself!");
997   assert(ForwardType == 0 && "This type has already been refined!");
998
999   // The descriptions may be out of date.  Conservatively clear them all!
1000   AbstractTypeDescriptions.clear();
1001
1002 #ifdef DEBUG_MERGE_TYPES
1003   std::cerr << "REFINING abstract type [" << (void*)this << " "
1004             << *this << "] to [" << (void*)NewType << " "
1005             << *NewType << "]!\n";
1006 #endif
1007
1008   // Make sure to put the type to be refined to into a holder so that if IT gets
1009   // refined, that we will not continue using a dead reference...
1010   //
1011   PATypeHolder NewTy(NewType);
1012
1013   // Any PATypeHolders referring to this type will now automatically forward to
1014   // the type we are resolved to.
1015   ForwardType = NewType;
1016   if (NewType->isAbstract())
1017     cast<DerivedType>(NewType)->addRef();
1018
1019   // Add a self use of the current type so that we don't delete ourself until
1020   // after the function exits.
1021   //
1022   PATypeHolder CurrentTy(this);
1023
1024   // To make the situation simpler, we ask the subclass to remove this type from
1025   // the type map, and to replace any type uses with uses of non-abstract types.
1026   // This dramatically limits the amount of recursive type trouble we can find
1027   // ourselves in.
1028   dropAllTypeUses();
1029
1030   // Iterate over all of the uses of this type, invoking callback.  Each user
1031   // should remove itself from our use list automatically.  We have to check to
1032   // make sure that NewTy doesn't _become_ 'this'.  If it does, resolving types
1033   // will not cause users to drop off of the use list.  If we resolve to ourself
1034   // we succeed!
1035   //
1036   while (!AbstractTypeUsers.empty() && NewTy != this) {
1037     AbstractTypeUser *User = AbstractTypeUsers.back();
1038
1039     unsigned OldSize = AbstractTypeUsers.size();
1040 #ifdef DEBUG_MERGE_TYPES
1041     std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
1042               << "] of abstract type [" << (void*)this << " "
1043               << *this << "] to [" << (void*)NewTy.get() << " "
1044               << *NewTy << "]!\n";
1045 #endif
1046     User->refineAbstractType(this, NewTy);
1047
1048     assert(AbstractTypeUsers.size() != OldSize &&
1049            "AbsTyUser did not remove self from user list!");
1050   }
1051
1052   // If we were successful removing all users from the type, 'this' will be
1053   // deleted when the last PATypeHolder is destroyed or updated from this type.
1054   // This may occur on exit of this function, as the CurrentTy object is
1055   // destroyed.
1056 }
1057
1058 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1059 // the current type has transitioned from being abstract to being concrete.
1060 //
1061 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1062 #ifdef DEBUG_MERGE_TYPES
1063   std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1064 #endif
1065
1066   unsigned OldSize = AbstractTypeUsers.size();
1067   while (!AbstractTypeUsers.empty()) {
1068     AbstractTypeUser *ATU = AbstractTypeUsers.back();
1069     ATU->typeBecameConcrete(this);
1070
1071     assert(AbstractTypeUsers.size() < OldSize-- &&
1072            "AbstractTypeUser did not remove itself from the use list!");
1073   }
1074 }
1075   
1076
1077
1078
1079 // refineAbstractType - Called when a contained type is found to be more
1080 // concrete - this could potentially change us from an abstract type to a
1081 // concrete type.
1082 //
1083 void FunctionType::refineAbstractType(const DerivedType *OldType,
1084                                       const Type *NewType) {
1085   FunctionTypes.finishRefinement(this, OldType, NewType);
1086 }
1087
1088 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1089   refineAbstractType(AbsTy, AbsTy);
1090 }
1091
1092
1093 // refineAbstractType - Called when a contained type is found to be more
1094 // concrete - this could potentially change us from an abstract type to a
1095 // concrete type.
1096 //
1097 void ArrayType::refineAbstractType(const DerivedType *OldType,
1098                                    const Type *NewType) {
1099   ArrayTypes.finishRefinement(this, OldType, NewType);
1100 }
1101
1102 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1103   refineAbstractType(AbsTy, AbsTy);
1104 }
1105
1106
1107 // refineAbstractType - Called when a contained type is found to be more
1108 // concrete - this could potentially change us from an abstract type to a
1109 // concrete type.
1110 //
1111 void StructType::refineAbstractType(const DerivedType *OldType,
1112                                     const Type *NewType) {
1113   StructTypes.finishRefinement(this, OldType, NewType);
1114 }
1115
1116 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1117   refineAbstractType(AbsTy, AbsTy);
1118 }
1119
1120 // refineAbstractType - Called when a contained type is found to be more
1121 // concrete - this could potentially change us from an abstract type to a
1122 // concrete type.
1123 //
1124 void PointerType::refineAbstractType(const DerivedType *OldType,
1125                                      const Type *NewType) {
1126   PointerTypes.finishRefinement(this, OldType, NewType);
1127 }
1128
1129 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1130   refineAbstractType(AbsTy, AbsTy);
1131 }