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