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