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