For PR950:
[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/AbstractTypeUser.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/SymbolTable.h"
17 #include "llvm/Constants.h"
18 #include "llvm/ADT/DepthFirstIterator.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/SCCIterator.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include <algorithm>
26 #include <iostream>
27 using namespace llvm;
28
29 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
30 // created and later destroyed, all in an effort to make sure that there is only
31 // a single canonical version of a type.
32 //
33 //#define DEBUG_MERGE_TYPES 1
34
35 AbstractTypeUser::~AbstractTypeUser() {}
36
37
38 //===----------------------------------------------------------------------===//
39 //                         Type PATypeHolder Implementation
40 //===----------------------------------------------------------------------===//
41
42 /// get - This implements the forwarding part of the union-find algorithm for
43 /// abstract types.  Before every access to the Type*, we check to see if the
44 /// type we are pointing to is forwarding to a new type.  If so, we drop our
45 /// reference to the type.
46 ///
47 Type* PATypeHolder::get() const {
48   const Type *NewTy = Ty->getForwardedType();
49   if (!NewTy) return const_cast<Type*>(Ty);
50   return *const_cast<PATypeHolder*>(this) = NewTy;
51 }
52
53 //===----------------------------------------------------------------------===//
54 //                         Type Class Implementation
55 //===----------------------------------------------------------------------===//
56
57 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
58 // for types as they are needed.  Because resolution of types must invalidate
59 // all of the abstract type descriptions, we keep them in a seperate map to make
60 // this easy.
61 static ManagedStatic<std::map<const Type*, 
62                               std::string> > ConcreteTypeDescriptions;
63 static ManagedStatic<std::map<const Type*,
64                               std::string> > AbstractTypeDescriptions;
65
66 Type::Type(const char *Name, TypeID id)
67   : ID(id), Abstract(false),  RefCount(0), ForwardType(0) {
68   assert(Name && Name[0] && "Should use other ctor if no name!");
69   (*ConcreteTypeDescriptions)[this] = Name;
70 }
71
72
73 const Type *Type::getPrimitiveType(TypeID IDNumber) {
74   switch (IDNumber) {
75   case VoidTyID  : return VoidTy;
76   case BoolTyID  : return BoolTy;
77   case UByteTyID : return UByteTy;
78   case SByteTyID : return SByteTy;
79   case UShortTyID: return UShortTy;
80   case ShortTyID : return ShortTy;
81   case UIntTyID  : return UIntTy;
82   case IntTyID   : return IntTy;
83   case ULongTyID : return ULongTy;
84   case LongTyID  : return LongTy;
85   case FloatTyID : return FloatTy;
86   case DoubleTyID: return DoubleTy;
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   
99   // Packed type conversions are always bitwise.
100   if (isa<PackedType>(this) && isa<PackedType>(Ty))
101     return true;
102   
103   if ((!isPrimitiveType()    && !isa<PointerType>(this)) ||
104       (!isa<PointerType>(Ty) && !Ty->isPrimitiveType())) return false;
105
106   if (getTypeID() == Ty->getTypeID())
107     return true;  // Handles identity cast, and cast of differing pointer types
108
109   // Now we know that they are two differing primitive or pointer types
110   switch (getTypeID()) {
111   case Type::UByteTyID:   return Ty == Type::SByteTy;
112   case Type::SByteTyID:   return Ty == Type::UByteTy;
113   case Type::UShortTyID:  return Ty == Type::ShortTy;
114   case Type::ShortTyID:   return Ty == Type::UShortTy;
115   case Type::UIntTyID:    return Ty == Type::IntTy;
116   case Type::IntTyID:     return Ty == Type::UIntTy;
117   case Type::ULongTyID:   return Ty == Type::LongTy;
118   case Type::LongTyID:    return Ty == Type::ULongTy;
119   case Type::PointerTyID: return isa<PointerType>(Ty);
120   default:
121     return false;  // Other types have no identity values
122   }
123 }
124
125 /// getUnsignedVersion - If this is an integer type, return the unsigned
126 /// variant of this type.  For example int -> uint.
127 const Type *Type::getUnsignedVersion() const {
128   switch (getTypeID()) {
129   default:
130     assert(isInteger()&&"Type::getUnsignedVersion is only valid for integers!");
131   case Type::UByteTyID:
132   case Type::SByteTyID:   return Type::UByteTy;
133   case Type::UShortTyID:
134   case Type::ShortTyID:   return Type::UShortTy;
135   case Type::UIntTyID:
136   case Type::IntTyID:     return Type::UIntTy;
137   case Type::ULongTyID:
138   case Type::LongTyID:    return Type::ULongTy;
139   }
140 }
141
142 /// getSignedVersion - If this is an integer type, return the signed variant
143 /// of this type.  For example uint -> int.
144 const Type *Type::getSignedVersion() const {
145   switch (getTypeID()) {
146   default:
147     assert(isInteger() && "Type::getSignedVersion is only valid for integers!");
148   case Type::UByteTyID:
149   case Type::SByteTyID:   return Type::SByteTy;
150   case Type::UShortTyID:
151   case Type::ShortTyID:   return Type::ShortTy;
152   case Type::UIntTyID:
153   case Type::IntTyID:     return Type::IntTy;
154   case Type::ULongTyID:
155   case Type::LongTyID:    return Type::LongTy;
156   }
157 }
158
159
160 // getPrimitiveSize - Return the basic size of this type if it is a primitive
161 // type.  These are fixed by LLVM and are not target dependent.  This will
162 // return zero if the type does not have a size or is not a primitive type.
163 //
164 unsigned Type::getPrimitiveSize() const {
165   switch (getTypeID()) {
166   case Type::BoolTyID:
167   case Type::SByteTyID:
168   case Type::UByteTyID: return 1;
169   case Type::UShortTyID:
170   case Type::ShortTyID: return 2;
171   case Type::FloatTyID:
172   case Type::IntTyID:
173   case Type::UIntTyID: return 4;
174   case Type::LongTyID:
175   case Type::ULongTyID:
176   case Type::DoubleTyID: return 8;
177   default: return 0;
178   }
179 }
180
181 unsigned Type::getPrimitiveSizeInBits() const {
182   switch (getTypeID()) {
183   case Type::BoolTyID:  return 1;
184   case Type::SByteTyID:
185   case Type::UByteTyID: return 8;
186   case Type::UShortTyID:
187   case Type::ShortTyID: return 16;
188   case Type::FloatTyID:
189   case Type::IntTyID:
190   case Type::UIntTyID: return 32;
191   case Type::LongTyID:
192   case Type::ULongTyID:
193   case Type::DoubleTyID: return 64;
194   default: return 0;
195   }
196 }
197
198 /// isSizedDerivedType - Derived types like structures and arrays are sized
199 /// iff all of the members of the type are sized as well.  Since asking for
200 /// their size is relatively uncommon, move this operation out of line.
201 bool Type::isSizedDerivedType() const {
202   if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
203     return ATy->getElementType()->isSized();
204
205   if (const PackedType *PTy = dyn_cast<PackedType>(this))
206     return PTy->getElementType()->isSized();
207
208   if (!isa<StructType>(this)) return false;
209
210   // Okay, our struct is sized if all of the elements are...
211   for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
212     if (!(*I)->isSized()) return false;
213
214   return true;
215 }
216
217 /// getForwardedTypeInternal - This method is used to implement the union-find
218 /// algorithm for when a type is being forwarded to another type.
219 const Type *Type::getForwardedTypeInternal() const {
220   assert(ForwardType && "This type is not being forwarded to another type!");
221
222   // Check to see if the forwarded type has been forwarded on.  If so, collapse
223   // the forwarding links.
224   const Type *RealForwardedType = ForwardType->getForwardedType();
225   if (!RealForwardedType)
226     return ForwardType;  // No it's not forwarded again
227
228   // Yes, it is forwarded again.  First thing, add the reference to the new
229   // forward type.
230   if (RealForwardedType->isAbstract())
231     cast<DerivedType>(RealForwardedType)->addRef();
232
233   // Now drop the old reference.  This could cause ForwardType to get deleted.
234   cast<DerivedType>(ForwardType)->dropRef();
235
236   // Return the updated type.
237   ForwardType = RealForwardedType;
238   return ForwardType;
239 }
240
241 void Type::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
242   abort();
243 }
244 void Type::typeBecameConcrete(const DerivedType *AbsTy) {
245   abort();
246 }
247
248
249 // getTypeDescription - This is a recursive function that walks a type hierarchy
250 // calculating the description for a type.
251 //
252 static std::string getTypeDescription(const Type *Ty,
253                                       std::vector<const Type *> &TypeStack) {
254   if (isa<OpaqueType>(Ty)) {                     // Base case for the recursion
255     std::map<const Type*, std::string>::iterator I =
256       AbstractTypeDescriptions->lower_bound(Ty);
257     if (I != AbstractTypeDescriptions->end() && I->first == Ty)
258       return I->second;
259     std::string Desc = "opaque";
260     AbstractTypeDescriptions->insert(std::make_pair(Ty, Desc));
261     return Desc;
262   }
263
264   if (!Ty->isAbstract()) {                       // Base case for the recursion
265     std::map<const Type*, std::string>::iterator I =
266       ConcreteTypeDescriptions->find(Ty);
267     if (I != ConcreteTypeDescriptions->end()) return I->second;
268   }
269
270   // Check to see if the Type is already on the stack...
271   unsigned Slot = 0, CurSize = TypeStack.size();
272   while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
273
274   // This is another base case for the recursion.  In this case, we know
275   // that we have looped back to a type that we have previously visited.
276   // Generate the appropriate upreference to handle this.
277   //
278   if (Slot < CurSize)
279     return "\\" + utostr(CurSize-Slot);         // Here's the upreference
280
281   // Recursive case: derived types...
282   std::string Result;
283   TypeStack.push_back(Ty);    // Add us to the stack..
284
285   switch (Ty->getTypeID()) {
286   case Type::FunctionTyID: {
287     const FunctionType *FTy = cast<FunctionType>(Ty);
288     Result = getTypeDescription(FTy->getReturnType(), TypeStack) + " (";
289     for (FunctionType::param_iterator I = FTy->param_begin(),
290            E = FTy->param_end(); I != E; ++I) {
291       if (I != FTy->param_begin())
292         Result += ", ";
293       Result += getTypeDescription(*I, TypeStack);
294     }
295     if (FTy->isVarArg()) {
296       if (FTy->getNumParams()) Result += ", ";
297       Result += "...";
298     }
299     Result += ")";
300     break;
301   }
302   case Type::StructTyID: {
303     const StructType *STy = cast<StructType>(Ty);
304     Result = "{ ";
305     for (StructType::element_iterator I = STy->element_begin(),
306            E = STy->element_end(); I != E; ++I) {
307       if (I != STy->element_begin())
308         Result += ", ";
309       Result += getTypeDescription(*I, TypeStack);
310     }
311     Result += " }";
312     break;
313   }
314   case Type::PointerTyID: {
315     const PointerType *PTy = cast<PointerType>(Ty);
316     Result = getTypeDescription(PTy->getElementType(), TypeStack) + " *";
317     break;
318   }
319   case Type::ArrayTyID: {
320     const ArrayType *ATy = cast<ArrayType>(Ty);
321     unsigned NumElements = ATy->getNumElements();
322     Result = "[";
323     Result += utostr(NumElements) + " x ";
324     Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
325     break;
326   }
327   case Type::PackedTyID: {
328     const PackedType *PTy = cast<PackedType>(Ty);
329     unsigned NumElements = PTy->getNumElements();
330     Result = "<";
331     Result += utostr(NumElements) + " x ";
332     Result += getTypeDescription(PTy->getElementType(), TypeStack) + ">";
333     break;
334   }
335   default:
336     Result = "<error>";
337     assert(0 && "Unhandled type in getTypeDescription!");
338   }
339
340   TypeStack.pop_back();       // Remove self from stack...
341
342   return Result;
343 }
344
345
346
347 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
348                                           const Type *Ty) {
349   std::map<const Type*, std::string>::iterator I = Map.find(Ty);
350   if (I != Map.end()) return I->second;
351
352   std::vector<const Type *> TypeStack;
353   std::string Result = getTypeDescription(Ty, TypeStack);
354   return Map[Ty] = Result;
355 }
356
357
358 const std::string &Type::getDescription() const {
359   if (isAbstract())
360     return getOrCreateDesc(*AbstractTypeDescriptions, this);
361   else
362     return getOrCreateDesc(*ConcreteTypeDescriptions, this);
363 }
364
365
366 bool StructType::indexValid(const Value *V) const {
367   // Structure indexes require unsigned integer constants.
368   if (V->getType() == Type::UIntTy)
369     if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
370       return CU->getZExtValue() < ContainedTys.size();
371   return false;
372 }
373
374 // getTypeAtIndex - Given an index value into the type, return the type of the
375 // element.  For a structure type, this must be a constant value...
376 //
377 const Type *StructType::getTypeAtIndex(const Value *V) const {
378   assert(indexValid(V) && "Invalid structure index!");
379   unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
380   return ContainedTys[Idx];
381 }
382
383
384 //===----------------------------------------------------------------------===//
385 //                          Primitive 'Type' data
386 //===----------------------------------------------------------------------===//
387
388 #define DeclarePrimType(TY, Str)                       \
389   namespace {                                          \
390     struct VISIBILITY_HIDDEN TY##Type : public Type {  \
391       TY##Type() : Type(Str, Type::TY##TyID) {}        \
392     };                                                 \
393   }                                                    \
394   static ManagedStatic<TY##Type> The##TY##Ty;          \
395   Type *Type::TY##Ty = &*The##TY##Ty
396
397 DeclarePrimType(Void,   "void");
398 DeclarePrimType(Bool,   "bool");
399 DeclarePrimType(SByte,  "sbyte");
400 DeclarePrimType(UByte,  "ubyte");
401 DeclarePrimType(Short,  "short");
402 DeclarePrimType(UShort, "ushort");
403 DeclarePrimType(Int,    "int");
404 DeclarePrimType(UInt,   "uint");
405 DeclarePrimType(Long,   "long");
406 DeclarePrimType(ULong,  "ulong");
407 DeclarePrimType(Float,  "float");
408 DeclarePrimType(Double, "double");
409 DeclarePrimType(Label,  "label");
410 #undef DeclarePrimType
411
412
413 //===----------------------------------------------------------------------===//
414 //                          Derived Type Constructors
415 //===----------------------------------------------------------------------===//
416
417 FunctionType::FunctionType(const Type *Result,
418                            const std::vector<const Type*> &Params,
419                            bool IsVarArgs) : DerivedType(FunctionTyID),
420                                              isVarArgs(IsVarArgs) {
421   assert((Result->isFirstClassType() || Result == Type::VoidTy ||
422          isa<OpaqueType>(Result)) &&
423          "LLVM functions cannot return aggregates");
424   bool isAbstract = Result->isAbstract();
425   ContainedTys.reserve(Params.size()+1);
426   ContainedTys.push_back(PATypeHandle(Result, this));
427
428   for (unsigned i = 0; i != Params.size(); ++i) {
429     assert((Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])) &&
430            "Function arguments must be value types!");
431
432     ContainedTys.push_back(PATypeHandle(Params[i], this));
433     isAbstract |= Params[i]->isAbstract();
434   }
435
436   // Calculate whether or not this type is abstract
437   setAbstract(isAbstract);
438 }
439
440 StructType::StructType(const std::vector<const Type*> &Types)
441   : CompositeType(StructTyID) {
442   ContainedTys.reserve(Types.size());
443   bool isAbstract = false;
444   for (unsigned i = 0; i < Types.size(); ++i) {
445     assert(Types[i] != Type::VoidTy && "Void type for structure field!!");
446     ContainedTys.push_back(PATypeHandle(Types[i], this));
447     isAbstract |= Types[i]->isAbstract();
448   }
449
450   // Calculate whether or not this type is abstract
451   setAbstract(isAbstract);
452 }
453
454 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
455   : SequentialType(ArrayTyID, ElType) {
456   NumElements = NumEl;
457
458   // Calculate whether or not this type is abstract
459   setAbstract(ElType->isAbstract());
460 }
461
462 PackedType::PackedType(const Type *ElType, unsigned NumEl)
463   : SequentialType(PackedTyID, ElType) {
464   NumElements = NumEl;
465
466   assert(NumEl > 0 && "NumEl of a PackedType must be greater than 0");
467   assert((ElType->isIntegral() || ElType->isFloatingPoint()) &&
468          "Elements of a PackedType must be a primitive type");
469 }
470
471
472 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
473   // Calculate whether or not this type is abstract
474   setAbstract(E->isAbstract());
475 }
476
477 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
478   setAbstract(true);
479 #ifdef DEBUG_MERGE_TYPES
480   std::cerr << "Derived new type: " << *this << "\n";
481 #endif
482 }
483
484 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
485 // another (more concrete) type, we must eliminate all references to other
486 // types, to avoid some circular reference problems.
487 void DerivedType::dropAllTypeUses() {
488   if (!ContainedTys.empty()) {
489     // The type must stay abstract.  To do this, we insert a pointer to a type
490     // that will never get resolved, thus will always be abstract.
491     static Type *AlwaysOpaqueTy = OpaqueType::get();
492     static PATypeHolder Holder(AlwaysOpaqueTy);
493     ContainedTys[0] = AlwaysOpaqueTy;
494
495     // Change the rest of the types to be intty's.  It doesn't matter what we
496     // pick so long as it doesn't point back to this type.  We choose something
497     // concrete to avoid overhead for adding to AbstracTypeUser lists and stuff.
498     for (unsigned i = 1, e = ContainedTys.size(); i != e; ++i)
499       ContainedTys[i] = Type::IntTy;
500   }
501 }
502
503
504
505 /// TypePromotionGraph and graph traits - this is designed to allow us to do
506 /// efficient SCC processing of type graphs.  This is the exact same as
507 /// GraphTraits<Type*>, except that we pretend that concrete types have no
508 /// children to avoid processing them.
509 struct TypePromotionGraph {
510   Type *Ty;
511   TypePromotionGraph(Type *T) : Ty(T) {}
512 };
513
514 namespace llvm {
515   template <> struct GraphTraits<TypePromotionGraph> {
516     typedef Type NodeType;
517     typedef Type::subtype_iterator ChildIteratorType;
518
519     static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
520     static inline ChildIteratorType child_begin(NodeType *N) {
521       if (N->isAbstract())
522         return N->subtype_begin();
523       else           // No need to process children of concrete types.
524         return N->subtype_end();
525     }
526     static inline ChildIteratorType child_end(NodeType *N) {
527       return N->subtype_end();
528     }
529   };
530 }
531
532
533 // PromoteAbstractToConcrete - This is a recursive function that walks a type
534 // graph calculating whether or not a type is abstract.
535 //
536 void Type::PromoteAbstractToConcrete() {
537   if (!isAbstract()) return;
538
539   scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
540   scc_iterator<TypePromotionGraph> SE = scc_end  (TypePromotionGraph(this));
541
542   for (; SI != SE; ++SI) {
543     std::vector<Type*> &SCC = *SI;
544
545     // Concrete types are leaves in the tree.  Since an SCC will either be all
546     // abstract or all concrete, we only need to check one type.
547     if (SCC[0]->isAbstract()) {
548       if (isa<OpaqueType>(SCC[0]))
549         return;     // Not going to be concrete, sorry.
550
551       // If all of the children of all of the types in this SCC are concrete,
552       // then this SCC is now concrete as well.  If not, neither this SCC, nor
553       // any parent SCCs will be concrete, so we might as well just exit.
554       for (unsigned i = 0, e = SCC.size(); i != e; ++i)
555         for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
556                E = SCC[i]->subtype_end(); CI != E; ++CI)
557           if ((*CI)->isAbstract())
558             // If the child type is in our SCC, it doesn't make the entire SCC
559             // abstract unless there is a non-SCC abstract type.
560             if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
561               return;               // Not going to be concrete, sorry.
562
563       // Okay, we just discovered this whole SCC is now concrete, mark it as
564       // such!
565       for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
566         assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
567
568         SCC[i]->setAbstract(false);
569       }
570
571       for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
572         assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
573         // The type just became concrete, notify all users!
574         cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
575       }
576     }
577   }
578 }
579
580
581 //===----------------------------------------------------------------------===//
582 //                      Type Structural Equality Testing
583 //===----------------------------------------------------------------------===//
584
585 // TypesEqual - Two types are considered structurally equal if they have the
586 // same "shape": Every level and element of the types have identical primitive
587 // ID's, and the graphs have the same edges/nodes in them.  Nodes do not have to
588 // be pointer equals to be equivalent though.  This uses an optimistic algorithm
589 // that assumes that two graphs are the same until proven otherwise.
590 //
591 static bool TypesEqual(const Type *Ty, const Type *Ty2,
592                        std::map<const Type *, const Type *> &EqTypes) {
593   if (Ty == Ty2) return true;
594   if (Ty->getTypeID() != Ty2->getTypeID()) return false;
595   if (isa<OpaqueType>(Ty))
596     return false;  // Two unequal opaque types are never equal
597
598   std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
599   if (It != EqTypes.end() && It->first == Ty)
600     return It->second == Ty2;    // Looping back on a type, check for equality
601
602   // Otherwise, add the mapping to the table to make sure we don't get
603   // recursion on the types...
604   EqTypes.insert(It, std::make_pair(Ty, Ty2));
605
606   // Two really annoying special cases that breaks an otherwise nice simple
607   // algorithm is the fact that arraytypes have sizes that differentiates types,
608   // and that function types can be varargs or not.  Consider this now.
609   //
610   if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
611     return TypesEqual(PTy->getElementType(),
612                       cast<PointerType>(Ty2)->getElementType(), EqTypes);
613   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
614     const StructType *STy2 = cast<StructType>(Ty2);
615     if (STy->getNumElements() != STy2->getNumElements()) return false;
616     for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
617       if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
618         return false;
619     return true;
620   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
621     const ArrayType *ATy2 = cast<ArrayType>(Ty2);
622     return ATy->getNumElements() == ATy2->getNumElements() &&
623            TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
624   } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
625     const PackedType *PTy2 = cast<PackedType>(Ty2);
626     return PTy->getNumElements() == PTy2->getNumElements() &&
627            TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
628   } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
629     const FunctionType *FTy2 = cast<FunctionType>(Ty2);
630     if (FTy->isVarArg() != FTy2->isVarArg() ||
631         FTy->getNumParams() != FTy2->getNumParams() ||
632         !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
633       return false;
634     for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i)
635       if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
636         return false;
637     return true;
638   } else {
639     assert(0 && "Unknown derived type!");
640     return false;
641   }
642 }
643
644 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
645   std::map<const Type *, const Type *> EqTypes;
646   return TypesEqual(Ty, Ty2, EqTypes);
647 }
648
649 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
650 // TargetTy in the type graph.  We know that Ty is an abstract type, so if we
651 // ever reach a non-abstract type, we know that we don't need to search the
652 // subgraph.
653 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
654                                 std::set<const Type*> &VisitedTypes) {
655   if (TargetTy == CurTy) return true;
656   if (!CurTy->isAbstract()) return false;
657
658   if (!VisitedTypes.insert(CurTy).second)
659     return false;  // Already been here.
660
661   for (Type::subtype_iterator I = CurTy->subtype_begin(),
662        E = CurTy->subtype_end(); I != E; ++I)
663     if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
664       return true;
665   return false;
666 }
667
668 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
669                                         std::set<const Type*> &VisitedTypes) {
670   if (TargetTy == CurTy) return true;
671
672   if (!VisitedTypes.insert(CurTy).second)
673     return false;  // Already been here.
674
675   for (Type::subtype_iterator I = CurTy->subtype_begin(),
676        E = CurTy->subtype_end(); I != E; ++I)
677     if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
678       return true;
679   return false;
680 }
681
682 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
683 /// back to itself.
684 static bool TypeHasCycleThroughItself(const Type *Ty) {
685   std::set<const Type*> VisitedTypes;
686
687   if (Ty->isAbstract()) {  // Optimized case for abstract types.
688     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
689          I != E; ++I)
690       if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
691         return true;
692   } else {
693     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
694          I != E; ++I)
695       if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
696         return true;
697   }
698   return false;
699 }
700
701 /// getSubElementHash - Generate a hash value for all of the SubType's of this
702 /// type.  The hash value is guaranteed to be zero if any of the subtypes are 
703 /// an opaque type.  Otherwise we try to mix them in as well as possible, but do
704 /// not look at the subtype's subtype's.
705 static unsigned getSubElementHash(const Type *Ty) {
706   unsigned HashVal = 0;
707   for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
708        I != E; ++I) {
709     HashVal *= 32;
710     const Type *SubTy = I->get();
711     HashVal += SubTy->getTypeID();
712     switch (SubTy->getTypeID()) {
713     default: break;
714     case Type::OpaqueTyID: return 0;    // Opaque -> hash = 0 no matter what.
715     case Type::FunctionTyID:
716       HashVal ^= cast<FunctionType>(SubTy)->getNumParams()*2 + 
717                  cast<FunctionType>(SubTy)->isVarArg();
718       break;
719     case Type::ArrayTyID:
720       HashVal ^= cast<ArrayType>(SubTy)->getNumElements();
721       break;
722     case Type::PackedTyID:
723       HashVal ^= cast<PackedType>(SubTy)->getNumElements();
724       break;
725     case Type::StructTyID:
726       HashVal ^= cast<StructType>(SubTy)->getNumElements();
727       break;
728     }
729   }
730   return HashVal ? HashVal : 1;  // Do not return zero unless opaque subty.
731 }
732
733 //===----------------------------------------------------------------------===//
734 //                       Derived Type Factory Functions
735 //===----------------------------------------------------------------------===//
736
737 namespace llvm {
738 class TypeMapBase {
739 protected:
740   /// TypesByHash - Keep track of types by their structure hash value.  Note
741   /// that we only keep track of types that have cycles through themselves in
742   /// this map.
743   ///
744   std::multimap<unsigned, PATypeHolder> TypesByHash;
745
746 public:
747   void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
748     std::multimap<unsigned, PATypeHolder>::iterator I =
749       TypesByHash.lower_bound(Hash);
750     for (; I != TypesByHash.end() && I->first == Hash; ++I) {
751       if (I->second == Ty) {
752         TypesByHash.erase(I);
753         return;
754       }
755     }
756     
757     // This must be do to an opaque type that was resolved.  Switch down to hash
758     // code of zero.
759     assert(Hash && "Didn't find type entry!");
760     RemoveFromTypesByHash(0, Ty);
761   }
762   
763   /// TypeBecameConcrete - When Ty gets a notification that TheType just became
764   /// concrete, drop uses and make Ty non-abstract if we should.
765   void TypeBecameConcrete(DerivedType *Ty, const DerivedType *TheType) {
766     // If the element just became concrete, remove 'ty' from the abstract
767     // type user list for the type.  Do this for as many times as Ty uses
768     // OldType.
769     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
770          I != E; ++I)
771       if (I->get() == TheType)
772         TheType->removeAbstractTypeUser(Ty);
773     
774     // If the type is currently thought to be abstract, rescan all of our
775     // subtypes to see if the type has just become concrete!  Note that this
776     // may send out notifications to AbstractTypeUsers that types become
777     // concrete.
778     if (Ty->isAbstract())
779       Ty->PromoteAbstractToConcrete();
780   }
781 };
782 }
783
784
785 // TypeMap - Make sure that only one instance of a particular type may be
786 // created on any given run of the compiler... note that this involves updating
787 // our map if an abstract type gets refined somehow.
788 //
789 namespace llvm {
790 template<class ValType, class TypeClass>
791 class TypeMap : public TypeMapBase {
792   std::map<ValType, PATypeHolder> Map;
793 public:
794   typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
795   ~TypeMap() { print("ON EXIT"); }
796
797   inline TypeClass *get(const ValType &V) {
798     iterator I = Map.find(V);
799     return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
800   }
801
802   inline void add(const ValType &V, TypeClass *Ty) {
803     Map.insert(std::make_pair(V, Ty));
804
805     // If this type has a cycle, remember it.
806     TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
807     print("add");
808   }
809   
810   void clear(std::vector<Type *> &DerivedTypes) {
811     for (typename std::map<ValType, PATypeHolder>::iterator I = Map.begin(),
812          E = Map.end(); I != E; ++I)
813       DerivedTypes.push_back(I->second.get());
814     TypesByHash.clear();
815     Map.clear();
816   }
817
818  /// RefineAbstractType - This method is called after we have merged a type
819   /// with another one.  We must now either merge the type away with
820   /// some other type or reinstall it in the map with it's new configuration.
821   void RefineAbstractType(TypeClass *Ty, const DerivedType *OldType,
822                         const Type *NewType) {
823 #ifdef DEBUG_MERGE_TYPES
824     std::cerr << "RefineAbstractType(" << (void*)OldType << "[" << *OldType
825     << "], " << (void*)NewType << " [" << *NewType << "])\n";
826 #endif
827     
828     // Otherwise, we are changing one subelement type into another.  Clearly the
829     // OldType must have been abstract, making us abstract.
830     assert(Ty->isAbstract() && "Refining a non-abstract type!");
831     assert(OldType != NewType);
832
833     // Make a temporary type holder for the type so that it doesn't disappear on
834     // us when we erase the entry from the map.
835     PATypeHolder TyHolder = Ty;
836
837     // The old record is now out-of-date, because one of the children has been
838     // updated.  Remove the obsolete entry from the map.
839     unsigned NumErased = Map.erase(ValType::get(Ty));
840     assert(NumErased && "Element not found!");
841
842     // Remember the structural hash for the type before we start hacking on it,
843     // in case we need it later.
844     unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
845
846     // Find the type element we are refining... and change it now!
847     for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
848       if (Ty->ContainedTys[i] == OldType)
849         Ty->ContainedTys[i] = NewType;
850     unsigned NewTypeHash = ValType::hashTypeStructure(Ty);
851     
852     // If there are no cycles going through this node, we can do a simple,
853     // efficient lookup in the map, instead of an inefficient nasty linear
854     // lookup.
855     if (!TypeHasCycleThroughItself(Ty)) {
856       typename std::map<ValType, PATypeHolder>::iterator I;
857       bool Inserted;
858
859       tie(I, Inserted) = Map.insert(std::make_pair(ValType::get(Ty), Ty));
860       if (!Inserted) {
861         // Refined to a different type altogether?
862         RemoveFromTypesByHash(OldTypeHash, Ty);
863
864         // We already have this type in the table.  Get rid of the newly refined
865         // type.
866         TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
867         Ty->refineAbstractTypeTo(NewTy);
868         return;
869       }
870     } else {
871       // Now we check to see if there is an existing entry in the table which is
872       // structurally identical to the newly refined type.  If so, this type
873       // gets refined to the pre-existing type.
874       //
875       std::multimap<unsigned, PATypeHolder>::iterator I, E, Entry;
876       tie(I, E) = TypesByHash.equal_range(NewTypeHash);
877       Entry = E;
878       for (; I != E; ++I) {
879         if (I->second == Ty) {
880           // Remember the position of the old type if we see it in our scan.
881           Entry = I;
882         } else {
883           if (TypesEqual(Ty, I->second)) {
884             TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
885
886             // Remove the old entry form TypesByHash.  If the hash values differ
887             // now, remove it from the old place.  Otherwise, continue scanning
888             // withing this hashcode to reduce work.
889             if (NewTypeHash != OldTypeHash) {
890               RemoveFromTypesByHash(OldTypeHash, Ty);
891             } else {
892               if (Entry == E) {
893                 // Find the location of Ty in the TypesByHash structure if we
894                 // haven't seen it already.
895                 while (I->second != Ty) {
896                   ++I;
897                   assert(I != E && "Structure doesn't contain type??");
898                 }
899                 Entry = I;
900               }
901               TypesByHash.erase(Entry);
902             }
903             Ty->refineAbstractTypeTo(NewTy);
904             return;
905           }
906         }
907       }
908
909       // If there is no existing type of the same structure, we reinsert an
910       // updated record into the map.
911       Map.insert(std::make_pair(ValType::get(Ty), Ty));
912     }
913
914     // If the hash codes differ, update TypesByHash
915     if (NewTypeHash != OldTypeHash) {
916       RemoveFromTypesByHash(OldTypeHash, Ty);
917       TypesByHash.insert(std::make_pair(NewTypeHash, Ty));
918     }
919     
920     // If the type is currently thought to be abstract, rescan all of our
921     // subtypes to see if the type has just become concrete!  Note that this
922     // may send out notifications to AbstractTypeUsers that types become
923     // concrete.
924     if (Ty->isAbstract())
925       Ty->PromoteAbstractToConcrete();
926   }
927
928   void print(const char *Arg) const {
929 #ifdef DEBUG_MERGE_TYPES
930     std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
931     unsigned i = 0;
932     for (typename std::map<ValType, PATypeHolder>::const_iterator I
933            = Map.begin(), E = Map.end(); I != E; ++I)
934       std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " "
935                 << *I->second.get() << "\n";
936 #endif
937   }
938
939   void dump() const { print("dump output"); }
940 };
941 }
942
943
944 //===----------------------------------------------------------------------===//
945 // Function Type Factory and Value Class...
946 //
947
948 // FunctionValType - Define a class to hold the key that goes into the TypeMap
949 //
950 namespace llvm {
951 class FunctionValType {
952   const Type *RetTy;
953   std::vector<const Type*> ArgTypes;
954   bool isVarArg;
955 public:
956   FunctionValType(const Type *ret, const std::vector<const Type*> &args,
957                   bool IVA) : RetTy(ret), isVarArg(IVA) {
958     for (unsigned i = 0; i < args.size(); ++i)
959       ArgTypes.push_back(args[i]);
960   }
961
962   static FunctionValType get(const FunctionType *FT);
963
964   static unsigned hashTypeStructure(const FunctionType *FT) {
965     return FT->getNumParams()*2+FT->isVarArg();
966   }
967
968   // Subclass should override this... to update self as usual
969   void doRefinement(const DerivedType *OldType, const Type *NewType) {
970     if (RetTy == OldType) RetTy = NewType;
971     for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
972       if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
973   }
974
975   inline bool operator<(const FunctionValType &MTV) const {
976     if (RetTy < MTV.RetTy) return true;
977     if (RetTy > MTV.RetTy) return false;
978
979     if (ArgTypes < MTV.ArgTypes) return true;
980     return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
981   }
982 };
983 }
984
985 // Define the actual map itself now...
986 static ManagedStatic<TypeMap<FunctionValType, FunctionType> > FunctionTypes;
987
988 FunctionValType FunctionValType::get(const FunctionType *FT) {
989   // Build up a FunctionValType
990   std::vector<const Type *> ParamTypes;
991   ParamTypes.reserve(FT->getNumParams());
992   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
993     ParamTypes.push_back(FT->getParamType(i));
994   return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
995 }
996
997
998 // FunctionType::get - The factory function for the FunctionType class...
999 FunctionType *FunctionType::get(const Type *ReturnType,
1000                                 const std::vector<const Type*> &Params,
1001                                 bool isVarArg) {
1002   FunctionValType VT(ReturnType, Params, isVarArg);
1003   FunctionType *MT = FunctionTypes->get(VT);
1004   if (MT) return MT;
1005
1006   FunctionTypes->add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
1007
1008 #ifdef DEBUG_MERGE_TYPES
1009   std::cerr << "Derived new type: " << MT << "\n";
1010 #endif
1011   return MT;
1012 }
1013
1014 //===----------------------------------------------------------------------===//
1015 // Array Type Factory...
1016 //
1017 namespace llvm {
1018 class ArrayValType {
1019   const Type *ValTy;
1020   uint64_t Size;
1021 public:
1022   ArrayValType(const Type *val, uint64_t sz) : ValTy(val), Size(sz) {}
1023
1024   static ArrayValType get(const ArrayType *AT) {
1025     return ArrayValType(AT->getElementType(), AT->getNumElements());
1026   }
1027
1028   static unsigned hashTypeStructure(const ArrayType *AT) {
1029     return (unsigned)AT->getNumElements();
1030   }
1031
1032   // Subclass should override this... to update self as usual
1033   void doRefinement(const DerivedType *OldType, const Type *NewType) {
1034     assert(ValTy == OldType);
1035     ValTy = NewType;
1036   }
1037
1038   inline bool operator<(const ArrayValType &MTV) const {
1039     if (Size < MTV.Size) return true;
1040     return Size == MTV.Size && ValTy < MTV.ValTy;
1041   }
1042 };
1043 }
1044 static ManagedStatic<TypeMap<ArrayValType, ArrayType> > ArrayTypes;
1045
1046
1047 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
1048   assert(ElementType && "Can't get array of null types!");
1049
1050   ArrayValType AVT(ElementType, NumElements);
1051   ArrayType *AT = ArrayTypes->get(AVT);
1052   if (AT) return AT;           // Found a match, return it!
1053
1054   // Value not found.  Derive a new type!
1055   ArrayTypes->add(AVT, AT = new ArrayType(ElementType, NumElements));
1056
1057 #ifdef DEBUG_MERGE_TYPES
1058   std::cerr << "Derived new type: " << *AT << "\n";
1059 #endif
1060   return AT;
1061 }
1062
1063
1064 //===----------------------------------------------------------------------===//
1065 // Packed Type Factory...
1066 //
1067 namespace llvm {
1068 class PackedValType {
1069   const Type *ValTy;
1070   unsigned Size;
1071 public:
1072   PackedValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
1073
1074   static PackedValType get(const PackedType *PT) {
1075     return PackedValType(PT->getElementType(), PT->getNumElements());
1076   }
1077
1078   static unsigned hashTypeStructure(const PackedType *PT) {
1079     return PT->getNumElements();
1080   }
1081
1082   // Subclass should override this... to update self as usual
1083   void doRefinement(const DerivedType *OldType, const Type *NewType) {
1084     assert(ValTy == OldType);
1085     ValTy = NewType;
1086   }
1087
1088   inline bool operator<(const PackedValType &MTV) const {
1089     if (Size < MTV.Size) return true;
1090     return Size == MTV.Size && ValTy < MTV.ValTy;
1091   }
1092 };
1093 }
1094 static ManagedStatic<TypeMap<PackedValType, PackedType> > PackedTypes;
1095
1096
1097 PackedType *PackedType::get(const Type *ElementType, unsigned NumElements) {
1098   assert(ElementType && "Can't get packed of null types!");
1099   assert(isPowerOf2_32(NumElements) && "Vector length should be a power of 2!");
1100
1101   PackedValType PVT(ElementType, NumElements);
1102   PackedType *PT = PackedTypes->get(PVT);
1103   if (PT) return PT;           // Found a match, return it!
1104
1105   // Value not found.  Derive a new type!
1106   PackedTypes->add(PVT, PT = new PackedType(ElementType, NumElements));
1107
1108 #ifdef DEBUG_MERGE_TYPES
1109   std::cerr << "Derived new type: " << *PT << "\n";
1110 #endif
1111   return PT;
1112 }
1113
1114 //===----------------------------------------------------------------------===//
1115 // Struct Type Factory...
1116 //
1117
1118 namespace llvm {
1119 // StructValType - Define a class to hold the key that goes into the TypeMap
1120 //
1121 class StructValType {
1122   std::vector<const Type*> ElTypes;
1123 public:
1124   StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
1125
1126   static StructValType get(const StructType *ST) {
1127     std::vector<const Type *> ElTypes;
1128     ElTypes.reserve(ST->getNumElements());
1129     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
1130       ElTypes.push_back(ST->getElementType(i));
1131
1132     return StructValType(ElTypes);
1133   }
1134
1135   static unsigned hashTypeStructure(const StructType *ST) {
1136     return ST->getNumElements();
1137   }
1138
1139   // Subclass should override this... to update self as usual
1140   void doRefinement(const DerivedType *OldType, const Type *NewType) {
1141     for (unsigned i = 0; i < ElTypes.size(); ++i)
1142       if (ElTypes[i] == OldType) ElTypes[i] = NewType;
1143   }
1144
1145   inline bool operator<(const StructValType &STV) const {
1146     return ElTypes < STV.ElTypes;
1147   }
1148 };
1149 }
1150
1151 static ManagedStatic<TypeMap<StructValType, StructType> > StructTypes;
1152
1153 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
1154   StructValType STV(ETypes);
1155   StructType *ST = StructTypes->get(STV);
1156   if (ST) return ST;
1157
1158   // Value not found.  Derive a new type!
1159   StructTypes->add(STV, ST = new StructType(ETypes));
1160
1161 #ifdef DEBUG_MERGE_TYPES
1162   std::cerr << "Derived new type: " << *ST << "\n";
1163 #endif
1164   return ST;
1165 }
1166
1167
1168
1169 //===----------------------------------------------------------------------===//
1170 // Pointer Type Factory...
1171 //
1172
1173 // PointerValType - Define a class to hold the key that goes into the TypeMap
1174 //
1175 namespace llvm {
1176 class PointerValType {
1177   const Type *ValTy;
1178 public:
1179   PointerValType(const Type *val) : ValTy(val) {}
1180
1181   static PointerValType get(const PointerType *PT) {
1182     return PointerValType(PT->getElementType());
1183   }
1184
1185   static unsigned hashTypeStructure(const PointerType *PT) {
1186     return getSubElementHash(PT);
1187   }
1188
1189   // Subclass should override this... to update self as usual
1190   void doRefinement(const DerivedType *OldType, const Type *NewType) {
1191     assert(ValTy == OldType);
1192     ValTy = NewType;
1193   }
1194
1195   bool operator<(const PointerValType &MTV) const {
1196     return ValTy < MTV.ValTy;
1197   }
1198 };
1199 }
1200
1201 static ManagedStatic<TypeMap<PointerValType, PointerType> > PointerTypes;
1202
1203 PointerType *PointerType::get(const Type *ValueType) {
1204   assert(ValueType && "Can't get a pointer to <null> type!");
1205   assert(ValueType != Type::VoidTy &&
1206          "Pointer to void is not valid, use sbyte* instead!");
1207   assert(ValueType != Type::LabelTy && "Pointer to label is not valid!");
1208   PointerValType PVT(ValueType);
1209
1210   PointerType *PT = PointerTypes->get(PVT);
1211   if (PT) return PT;
1212
1213   // Value not found.  Derive a new type!
1214   PointerTypes->add(PVT, PT = new PointerType(ValueType));
1215
1216 #ifdef DEBUG_MERGE_TYPES
1217   std::cerr << "Derived new type: " << *PT << "\n";
1218 #endif
1219   return PT;
1220 }
1221
1222 //===----------------------------------------------------------------------===//
1223 //                     Derived Type Refinement Functions
1224 //===----------------------------------------------------------------------===//
1225
1226 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1227 // no longer has a handle to the type.  This function is called primarily by
1228 // the PATypeHandle class.  When there are no users of the abstract type, it
1229 // is annihilated, because there is no way to get a reference to it ever again.
1230 //
1231 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
1232   // Search from back to front because we will notify users from back to
1233   // front.  Also, it is likely that there will be a stack like behavior to
1234   // users that register and unregister users.
1235   //
1236   unsigned i;
1237   for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1238     assert(i != 0 && "AbstractTypeUser not in user list!");
1239
1240   --i;  // Convert to be in range 0 <= i < size()
1241   assert(i < AbstractTypeUsers.size() && "Index out of range!");  // Wraparound?
1242
1243   AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1244
1245 #ifdef DEBUG_MERGE_TYPES
1246   std::cerr << "  remAbstractTypeUser[" << (void*)this << ", "
1247             << *this << "][" << i << "] User = " << U << "\n";
1248 #endif
1249
1250   if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1251 #ifdef DEBUG_MERGE_TYPES
1252     std::cerr << "DELETEing unused abstract type: <" << *this
1253               << ">[" << (void*)this << "]" << "\n";
1254 #endif
1255     delete this;                  // No users of this abstract type!
1256   }
1257 }
1258
1259
1260 // refineAbstractTypeTo - This function is used when it is discovered that
1261 // the 'this' abstract type is actually equivalent to the NewType specified.
1262 // This causes all users of 'this' to switch to reference the more concrete type
1263 // NewType and for 'this' to be deleted.
1264 //
1265 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1266   assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1267   assert(this != NewType && "Can't refine to myself!");
1268   assert(ForwardType == 0 && "This type has already been refined!");
1269
1270   // The descriptions may be out of date.  Conservatively clear them all!
1271   AbstractTypeDescriptions->clear();
1272
1273 #ifdef DEBUG_MERGE_TYPES
1274   std::cerr << "REFINING abstract type [" << (void*)this << " "
1275             << *this << "] to [" << (void*)NewType << " "
1276             << *NewType << "]!\n";
1277 #endif
1278
1279   // Make sure to put the type to be refined to into a holder so that if IT gets
1280   // refined, that we will not continue using a dead reference...
1281   //
1282   PATypeHolder NewTy(NewType);
1283
1284   // Any PATypeHolders referring to this type will now automatically forward to
1285   // the type we are resolved to.
1286   ForwardType = NewType;
1287   if (NewType->isAbstract())
1288     cast<DerivedType>(NewType)->addRef();
1289
1290   // Add a self use of the current type so that we don't delete ourself until
1291   // after the function exits.
1292   //
1293   PATypeHolder CurrentTy(this);
1294
1295   // To make the situation simpler, we ask the subclass to remove this type from
1296   // the type map, and to replace any type uses with uses of non-abstract types.
1297   // This dramatically limits the amount of recursive type trouble we can find
1298   // ourselves in.
1299   dropAllTypeUses();
1300
1301   // Iterate over all of the uses of this type, invoking callback.  Each user
1302   // should remove itself from our use list automatically.  We have to check to
1303   // make sure that NewTy doesn't _become_ 'this'.  If it does, resolving types
1304   // will not cause users to drop off of the use list.  If we resolve to ourself
1305   // we succeed!
1306   //
1307   while (!AbstractTypeUsers.empty() && NewTy != this) {
1308     AbstractTypeUser *User = AbstractTypeUsers.back();
1309
1310     unsigned OldSize = AbstractTypeUsers.size();
1311 #ifdef DEBUG_MERGE_TYPES
1312     std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
1313               << "] of abstract type [" << (void*)this << " "
1314               << *this << "] to [" << (void*)NewTy.get() << " "
1315               << *NewTy << "]!\n";
1316 #endif
1317     User->refineAbstractType(this, NewTy);
1318
1319     assert(AbstractTypeUsers.size() != OldSize &&
1320            "AbsTyUser did not remove self from user list!");
1321   }
1322
1323   // If we were successful removing all users from the type, 'this' will be
1324   // deleted when the last PATypeHolder is destroyed or updated from this type.
1325   // This may occur on exit of this function, as the CurrentTy object is
1326   // destroyed.
1327 }
1328
1329 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1330 // the current type has transitioned from being abstract to being concrete.
1331 //
1332 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1333 #ifdef DEBUG_MERGE_TYPES
1334   std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1335 #endif
1336
1337   unsigned OldSize = AbstractTypeUsers.size();
1338   while (!AbstractTypeUsers.empty()) {
1339     AbstractTypeUser *ATU = AbstractTypeUsers.back();
1340     ATU->typeBecameConcrete(this);
1341
1342     assert(AbstractTypeUsers.size() < OldSize-- &&
1343            "AbstractTypeUser did not remove itself from the use list!");
1344   }
1345 }
1346
1347 // refineAbstractType - Called when a contained type is found to be more
1348 // concrete - this could potentially change us from an abstract type to a
1349 // concrete type.
1350 //
1351 void FunctionType::refineAbstractType(const DerivedType *OldType,
1352                                       const Type *NewType) {
1353   FunctionTypes->RefineAbstractType(this, OldType, NewType);
1354 }
1355
1356 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1357   FunctionTypes->TypeBecameConcrete(this, AbsTy);
1358 }
1359
1360
1361 // refineAbstractType - Called when a contained type is found to be more
1362 // concrete - this could potentially change us from an abstract type to a
1363 // concrete type.
1364 //
1365 void ArrayType::refineAbstractType(const DerivedType *OldType,
1366                                    const Type *NewType) {
1367   ArrayTypes->RefineAbstractType(this, OldType, NewType);
1368 }
1369
1370 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1371   ArrayTypes->TypeBecameConcrete(this, AbsTy);
1372 }
1373
1374 // refineAbstractType - Called when a contained type is found to be more
1375 // concrete - this could potentially change us from an abstract type to a
1376 // concrete type.
1377 //
1378 void PackedType::refineAbstractType(const DerivedType *OldType,
1379                                    const Type *NewType) {
1380   PackedTypes->RefineAbstractType(this, OldType, NewType);
1381 }
1382
1383 void PackedType::typeBecameConcrete(const DerivedType *AbsTy) {
1384   PackedTypes->TypeBecameConcrete(this, AbsTy);
1385 }
1386
1387 // refineAbstractType - Called when a contained type is found to be more
1388 // concrete - this could potentially change us from an abstract type to a
1389 // concrete type.
1390 //
1391 void StructType::refineAbstractType(const DerivedType *OldType,
1392                                     const Type *NewType) {
1393   StructTypes->RefineAbstractType(this, OldType, NewType);
1394 }
1395
1396 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1397   StructTypes->TypeBecameConcrete(this, AbsTy);
1398 }
1399
1400 // refineAbstractType - Called when a contained type is found to be more
1401 // concrete - this could potentially change us from an abstract type to a
1402 // concrete type.
1403 //
1404 void PointerType::refineAbstractType(const DerivedType *OldType,
1405                                      const Type *NewType) {
1406   PointerTypes->RefineAbstractType(this, OldType, NewType);
1407 }
1408
1409 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1410   PointerTypes->TypeBecameConcrete(this, AbsTy);
1411 }
1412
1413 bool SequentialType::indexValid(const Value *V) const {
1414   const Type *Ty = V->getType();
1415   switch (Ty->getTypeID()) {
1416   case Type::IntTyID:
1417   case Type::UIntTyID:
1418   case Type::LongTyID:
1419   case Type::ULongTyID:
1420     return true;
1421   default:
1422     return false;
1423   }
1424 }
1425
1426 namespace llvm {
1427 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1428   if (T == 0)
1429     OS << "<null> value!\n";
1430   else
1431     T->print(OS);
1432   return OS;
1433 }
1434
1435 std::ostream &operator<<(std::ostream &OS, const Type &T) {
1436   T.print(OS);
1437   return OS;
1438 }
1439 }