Moving this function to a permanent home to prevent a dependency cycle created
[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/Visibility.h"
24 #include <algorithm>
25 #include <iostream>
26 using namespace llvm;
27
28 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
29 // created and later destroyed, all in an effort to make sure that there is only
30 // a single canonical version of a type.
31 //
32 //#define DEBUG_MERGE_TYPES 1
33
34 AbstractTypeUser::~AbstractTypeUser() {}
35
36
37 //===----------------------------------------------------------------------===//
38 //                         Type PATypeHolder Implementation
39 //===----------------------------------------------------------------------===//
40
41 // This routine was moved here to resolve a cyclic dependency caused by
42 // inline heuristics.
43
44 /// get - This implements the forwarding part of the union-find algorithm for
45 /// abstract types.  Before every access to the Type*, we check to see if the
46 /// type we are pointing to is forwarding to a new type.  If so, we drop our
47 /// reference to the type.
48 ///
49 Type* PATypeHolder::get() const {
50   const Type *NewTy = Ty->getForwardedType();
51   if (!NewTy) return const_cast<Type*>(Ty);
52   return *const_cast<PATypeHolder*>(this) = NewTy;
53 }
54
55 //===----------------------------------------------------------------------===//
56 //                         Type Class Implementation
57 //===----------------------------------------------------------------------===//
58
59 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
60 // for types as they are needed.  Because resolution of types must invalidate
61 // all of the abstract type descriptions, we keep them in a seperate map to make
62 // this easy.
63 static std::map<const Type*, std::string> ConcreteTypeDescriptions;
64 static std::map<const Type*, 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 ConstantUInt *CU = dyn_cast<ConstantUInt>(V))
370       return CU->getValue() < 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<ConstantUInt>(V)->getValue();
380   return ContainedTys[Idx];
381 }
382
383
384 //===----------------------------------------------------------------------===//
385 //                           Static 'Type' data
386 //===----------------------------------------------------------------------===//
387
388 namespace {
389   struct VISIBILITY_HIDDEN PrimType : public Type {
390     PrimType(const char *S, TypeID ID) : Type(S, ID) {}
391   };
392 }
393
394 static PrimType TheVoidTy  ("void"  , Type::VoidTyID);
395 static PrimType TheBoolTy  ("bool"  , Type::BoolTyID);
396 static PrimType TheSByteTy ("sbyte" , Type::SByteTyID);
397 static PrimType TheUByteTy ("ubyte" , Type::UByteTyID);
398 static PrimType TheShortTy ("short" , Type::ShortTyID);
399 static PrimType TheUShortTy("ushort", Type::UShortTyID);
400 static PrimType TheIntTy   ("int"   , Type::IntTyID);
401 static PrimType TheUIntTy  ("uint"  , Type::UIntTyID);
402 static PrimType TheLongTy  ("long"  , Type::LongTyID);
403 static PrimType TheULongTy ("ulong" , Type::ULongTyID);
404 static PrimType TheFloatTy ("float" , Type::FloatTyID);
405 static PrimType TheDoubleTy("double", Type::DoubleTyID);
406 static PrimType TheLabelTy ("label" , Type::LabelTyID);
407
408 Type *Type::VoidTy   = &TheVoidTy;
409 Type *Type::BoolTy   = &TheBoolTy;
410 Type *Type::SByteTy  = &TheSByteTy;
411 Type *Type::UByteTy  = &TheUByteTy;
412 Type *Type::ShortTy  = &TheShortTy;
413 Type *Type::UShortTy = &TheUShortTy;
414 Type *Type::IntTy    = &TheIntTy;
415 Type *Type::UIntTy   = &TheUIntTy;
416 Type *Type::LongTy   = &TheLongTy;
417 Type *Type::ULongTy  = &TheULongTy;
418 Type *Type::FloatTy  = &TheFloatTy;
419 Type *Type::DoubleTy = &TheDoubleTy;
420 Type *Type::LabelTy  = &TheLabelTy;
421
422
423 //===----------------------------------------------------------------------===//
424 //                          Derived Type Constructors
425 //===----------------------------------------------------------------------===//
426
427 FunctionType::FunctionType(const Type *Result,
428                            const std::vector<const Type*> &Params,
429                            bool IsVarArgs) : DerivedType(FunctionTyID),
430                                              isVarArgs(IsVarArgs) {
431   assert((Result->isFirstClassType() || Result == Type::VoidTy ||
432          isa<OpaqueType>(Result)) &&
433          "LLVM functions cannot return aggregates");
434   bool isAbstract = Result->isAbstract();
435   ContainedTys.reserve(Params.size()+1);
436   ContainedTys.push_back(PATypeHandle(Result, this));
437
438   for (unsigned i = 0; i != Params.size(); ++i) {
439     assert((Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])) &&
440            "Function arguments must be value types!");
441
442     ContainedTys.push_back(PATypeHandle(Params[i], this));
443     isAbstract |= Params[i]->isAbstract();
444   }
445
446   // Calculate whether or not this type is abstract
447   setAbstract(isAbstract);
448 }
449
450 StructType::StructType(const std::vector<const Type*> &Types)
451   : CompositeType(StructTyID) {
452   ContainedTys.reserve(Types.size());
453   bool isAbstract = false;
454   for (unsigned i = 0; i < Types.size(); ++i) {
455     assert(Types[i] != Type::VoidTy && "Void type for structure field!!");
456     ContainedTys.push_back(PATypeHandle(Types[i], this));
457     isAbstract |= Types[i]->isAbstract();
458   }
459
460   // Calculate whether or not this type is abstract
461   setAbstract(isAbstract);
462 }
463
464 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
465   : SequentialType(ArrayTyID, ElType) {
466   NumElements = NumEl;
467
468   // Calculate whether or not this type is abstract
469   setAbstract(ElType->isAbstract());
470 }
471
472 PackedType::PackedType(const Type *ElType, unsigned NumEl)
473   : SequentialType(PackedTyID, ElType) {
474   NumElements = NumEl;
475
476   assert(NumEl > 0 && "NumEl of a PackedType must be greater than 0");
477   assert((ElType->isIntegral() || ElType->isFloatingPoint()) &&
478          "Elements of a PackedType must be a primitive type");
479 }
480
481
482 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
483   // Calculate whether or not this type is abstract
484   setAbstract(E->isAbstract());
485 }
486
487 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
488   setAbstract(true);
489 #ifdef DEBUG_MERGE_TYPES
490   std::cerr << "Derived new type: " << *this << "\n";
491 #endif
492 }
493
494 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
495 // another (more concrete) type, we must eliminate all references to other
496 // types, to avoid some circular reference problems.
497 void DerivedType::dropAllTypeUses() {
498   if (!ContainedTys.empty()) {
499     // The type must stay abstract.  To do this, we insert a pointer to a type
500     // that will never get resolved, thus will always be abstract.
501     static Type *AlwaysOpaqueTy = OpaqueType::get();
502     static PATypeHolder Holder(AlwaysOpaqueTy);
503     ContainedTys[0] = AlwaysOpaqueTy;
504
505     // Change the rest of the types to be intty's.  It doesn't matter what we
506     // pick so long as it doesn't point back to this type.  We choose something
507     // concrete to avoid overhead for adding to AbstracTypeUser lists and stuff.
508     for (unsigned i = 1, e = ContainedTys.size(); i != e; ++i)
509       ContainedTys[i] = Type::IntTy;
510   }
511 }
512
513
514
515 /// TypePromotionGraph and graph traits - this is designed to allow us to do
516 /// efficient SCC processing of type graphs.  This is the exact same as
517 /// GraphTraits<Type*>, except that we pretend that concrete types have no
518 /// children to avoid processing them.
519 struct TypePromotionGraph {
520   Type *Ty;
521   TypePromotionGraph(Type *T) : Ty(T) {}
522 };
523
524 namespace llvm {
525   template <> struct GraphTraits<TypePromotionGraph> {
526     typedef Type NodeType;
527     typedef Type::subtype_iterator ChildIteratorType;
528
529     static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
530     static inline ChildIteratorType child_begin(NodeType *N) {
531       if (N->isAbstract())
532         return N->subtype_begin();
533       else           // No need to process children of concrete types.
534         return N->subtype_end();
535     }
536     static inline ChildIteratorType child_end(NodeType *N) {
537       return N->subtype_end();
538     }
539   };
540 }
541
542
543 // PromoteAbstractToConcrete - This is a recursive function that walks a type
544 // graph calculating whether or not a type is abstract.
545 //
546 void Type::PromoteAbstractToConcrete() {
547   if (!isAbstract()) return;
548
549   scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
550   scc_iterator<TypePromotionGraph> SE = scc_end  (TypePromotionGraph(this));
551
552   for (; SI != SE; ++SI) {
553     std::vector<Type*> &SCC = *SI;
554
555     // Concrete types are leaves in the tree.  Since an SCC will either be all
556     // abstract or all concrete, we only need to check one type.
557     if (SCC[0]->isAbstract()) {
558       if (isa<OpaqueType>(SCC[0]))
559         return;     // Not going to be concrete, sorry.
560
561       // If all of the children of all of the types in this SCC are concrete,
562       // then this SCC is now concrete as well.  If not, neither this SCC, nor
563       // any parent SCCs will be concrete, so we might as well just exit.
564       for (unsigned i = 0, e = SCC.size(); i != e; ++i)
565         for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
566                E = SCC[i]->subtype_end(); CI != E; ++CI)
567           if ((*CI)->isAbstract())
568             // If the child type is in our SCC, it doesn't make the entire SCC
569             // abstract unless there is a non-SCC abstract type.
570             if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
571               return;               // Not going to be concrete, sorry.
572
573       // Okay, we just discovered this whole SCC is now concrete, mark it as
574       // such!
575       for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
576         assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
577
578         SCC[i]->setAbstract(false);
579       }
580
581       for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
582         assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
583         // The type just became concrete, notify all users!
584         cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
585       }
586     }
587   }
588 }
589
590
591 //===----------------------------------------------------------------------===//
592 //                      Type Structural Equality Testing
593 //===----------------------------------------------------------------------===//
594
595 // TypesEqual - Two types are considered structurally equal if they have the
596 // same "shape": Every level and element of the types have identical primitive
597 // ID's, and the graphs have the same edges/nodes in them.  Nodes do not have to
598 // be pointer equals to be equivalent though.  This uses an optimistic algorithm
599 // that assumes that two graphs are the same until proven otherwise.
600 //
601 static bool TypesEqual(const Type *Ty, const Type *Ty2,
602                        std::map<const Type *, const Type *> &EqTypes) {
603   if (Ty == Ty2) return true;
604   if (Ty->getTypeID() != Ty2->getTypeID()) return false;
605   if (isa<OpaqueType>(Ty))
606     return false;  // Two unequal opaque types are never equal
607
608   std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
609   if (It != EqTypes.end() && It->first == Ty)
610     return It->second == Ty2;    // Looping back on a type, check for equality
611
612   // Otherwise, add the mapping to the table to make sure we don't get
613   // recursion on the types...
614   EqTypes.insert(It, std::make_pair(Ty, Ty2));
615
616   // Two really annoying special cases that breaks an otherwise nice simple
617   // algorithm is the fact that arraytypes have sizes that differentiates types,
618   // and that function types can be varargs or not.  Consider this now.
619   //
620   if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
621     return TypesEqual(PTy->getElementType(),
622                       cast<PointerType>(Ty2)->getElementType(), EqTypes);
623   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
624     const StructType *STy2 = cast<StructType>(Ty2);
625     if (STy->getNumElements() != STy2->getNumElements()) return false;
626     for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
627       if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
628         return false;
629     return true;
630   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
631     const ArrayType *ATy2 = cast<ArrayType>(Ty2);
632     return ATy->getNumElements() == ATy2->getNumElements() &&
633            TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
634   } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
635     const PackedType *PTy2 = cast<PackedType>(Ty2);
636     return PTy->getNumElements() == PTy2->getNumElements() &&
637            TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
638   } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
639     const FunctionType *FTy2 = cast<FunctionType>(Ty2);
640     if (FTy->isVarArg() != FTy2->isVarArg() ||
641         FTy->getNumParams() != FTy2->getNumParams() ||
642         !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
643       return false;
644     for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i)
645       if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
646         return false;
647     return true;
648   } else {
649     assert(0 && "Unknown derived type!");
650     return false;
651   }
652 }
653
654 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
655   std::map<const Type *, const Type *> EqTypes;
656   return TypesEqual(Ty, Ty2, EqTypes);
657 }
658
659 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
660 // TargetTy in the type graph.  We know that Ty is an abstract type, so if we
661 // ever reach a non-abstract type, we know that we don't need to search the
662 // subgraph.
663 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
664                                 std::set<const Type*> &VisitedTypes) {
665   if (TargetTy == CurTy) return true;
666   if (!CurTy->isAbstract()) return false;
667
668   if (!VisitedTypes.insert(CurTy).second)
669     return false;  // Already been here.
670
671   for (Type::subtype_iterator I = CurTy->subtype_begin(),
672        E = CurTy->subtype_end(); I != E; ++I)
673     if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
674       return true;
675   return false;
676 }
677
678 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
679                                         std::set<const Type*> &VisitedTypes) {
680   if (TargetTy == CurTy) return true;
681
682   if (!VisitedTypes.insert(CurTy).second)
683     return false;  // Already been here.
684
685   for (Type::subtype_iterator I = CurTy->subtype_begin(),
686        E = CurTy->subtype_end(); I != E; ++I)
687     if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
688       return true;
689   return false;
690 }
691
692 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
693 /// back to itself.
694 static bool TypeHasCycleThroughItself(const Type *Ty) {
695   std::set<const Type*> VisitedTypes;
696
697   if (Ty->isAbstract()) {  // Optimized case for abstract types.
698     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
699          I != E; ++I)
700       if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
701         return true;
702   } else {
703     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
704          I != E; ++I)
705       if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
706         return true;
707   }
708   return false;
709 }
710
711 /// getSubElementHash - Generate a hash value for all of the SubType's of this
712 /// type.  The hash value is guaranteed to be zero if any of the subtypes are 
713 /// an opaque type.  Otherwise we try to mix them in as well as possible, but do
714 /// not look at the subtype's subtype's.
715 static unsigned getSubElementHash(const Type *Ty) {
716   unsigned HashVal = 0;
717   for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
718        I != E; ++I) {
719     HashVal *= 32;
720     const Type *SubTy = I->get();
721     HashVal += SubTy->getTypeID();
722     switch (SubTy->getTypeID()) {
723     default: break;
724     case Type::OpaqueTyID: return 0;    // Opaque -> hash = 0 no matter what.
725     case Type::FunctionTyID:
726       HashVal ^= cast<FunctionType>(SubTy)->getNumParams()*2 + 
727                  cast<FunctionType>(SubTy)->isVarArg();
728       break;
729     case Type::ArrayTyID:
730       HashVal ^= cast<ArrayType>(SubTy)->getNumElements();
731       break;
732     case Type::PackedTyID:
733       HashVal ^= cast<PackedType>(SubTy)->getNumElements();
734       break;
735     case Type::StructTyID:
736       HashVal ^= cast<StructType>(SubTy)->getNumElements();
737       break;
738     }
739   }
740   return HashVal ? HashVal : 1;  // Do not return zero unless opaque subty.
741 }
742
743 //===----------------------------------------------------------------------===//
744 //                       Derived Type Factory Functions
745 //===----------------------------------------------------------------------===//
746
747 namespace llvm {
748 class TypeMapBase {
749 protected:
750   /// TypesByHash - Keep track of types by their structure hash value.  Note
751   /// that we only keep track of types that have cycles through themselves in
752   /// this map.
753   ///
754   std::multimap<unsigned, PATypeHolder> TypesByHash;
755
756 public:
757   void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
758     std::multimap<unsigned, PATypeHolder>::iterator I =
759       TypesByHash.lower_bound(Hash);
760     for (; I != TypesByHash.end() && I->first == Hash; ++I) {
761       if (I->second == Ty) {
762         TypesByHash.erase(I);
763         return;
764       }
765     }
766     
767     // This must be do to an opaque type that was resolved.  Switch down to hash
768     // code of zero.
769     assert(Hash && "Didn't find type entry!");
770     RemoveFromTypesByHash(0, Ty);
771   }
772   
773   /// TypeBecameConcrete - When Ty gets a notification that TheType just became
774   /// concrete, drop uses and make Ty non-abstract if we should.
775   void TypeBecameConcrete(DerivedType *Ty, const DerivedType *TheType) {
776     // If the element just became concrete, remove 'ty' from the abstract
777     // type user list for the type.  Do this for as many times as Ty uses
778     // OldType.
779     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
780          I != E; ++I)
781       if (I->get() == TheType)
782         TheType->removeAbstractTypeUser(Ty);
783     
784     // If the type is currently thought to be abstract, rescan all of our
785     // subtypes to see if the type has just become concrete!  Note that this
786     // may send out notifications to AbstractTypeUsers that types become
787     // concrete.
788     if (Ty->isAbstract())
789       Ty->PromoteAbstractToConcrete();
790   }
791 };
792 }
793
794
795 // TypeMap - Make sure that only one instance of a particular type may be
796 // created on any given run of the compiler... note that this involves updating
797 // our map if an abstract type gets refined somehow.
798 //
799 namespace llvm {
800 template<class ValType, class TypeClass>
801 class TypeMap : public TypeMapBase {
802   std::map<ValType, PATypeHolder> Map;
803 public:
804   typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
805   ~TypeMap() { print("ON EXIT"); }
806
807   inline TypeClass *get(const ValType &V) {
808     iterator I = Map.find(V);
809     return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
810   }
811
812   inline void add(const ValType &V, TypeClass *Ty) {
813     Map.insert(std::make_pair(V, Ty));
814
815     // If this type has a cycle, remember it.
816     TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
817     print("add");
818   }
819   
820   void clear(std::vector<Type *> &DerivedTypes) {
821     for (typename std::map<ValType, PATypeHolder>::iterator I = Map.begin(),
822          E = Map.end(); I != E; ++I)
823       DerivedTypes.push_back(I->second.get());
824     TypesByHash.clear();
825     Map.clear();
826   }
827
828  /// RefineAbstractType - This method is called after we have merged a type
829   /// with another one.  We must now either merge the type away with
830   /// some other type or reinstall it in the map with it's new configuration.
831   void RefineAbstractType(TypeClass *Ty, const DerivedType *OldType,
832                         const Type *NewType) {
833 #ifdef DEBUG_MERGE_TYPES
834     std::cerr << "RefineAbstractType(" << (void*)OldType << "[" << *OldType
835     << "], " << (void*)NewType << " [" << *NewType << "])\n";
836 #endif
837     
838     // Otherwise, we are changing one subelement type into another.  Clearly the
839     // OldType must have been abstract, making us abstract.
840     assert(Ty->isAbstract() && "Refining a non-abstract type!");
841     assert(OldType != NewType);
842
843     // Make a temporary type holder for the type so that it doesn't disappear on
844     // us when we erase the entry from the map.
845     PATypeHolder TyHolder = Ty;
846
847     // The old record is now out-of-date, because one of the children has been
848     // updated.  Remove the obsolete entry from the map.
849     unsigned NumErased = Map.erase(ValType::get(Ty));
850     assert(NumErased && "Element not found!");
851
852     // Remember the structural hash for the type before we start hacking on it,
853     // in case we need it later.
854     unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
855
856     // Find the type element we are refining... and change it now!
857     for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
858       if (Ty->ContainedTys[i] == OldType)
859         Ty->ContainedTys[i] = NewType;
860     unsigned NewTypeHash = ValType::hashTypeStructure(Ty);
861     
862     // If there are no cycles going through this node, we can do a simple,
863     // efficient lookup in the map, instead of an inefficient nasty linear
864     // lookup.
865     if (!TypeHasCycleThroughItself(Ty)) {
866       typename std::map<ValType, PATypeHolder>::iterator I;
867       bool Inserted;
868
869       tie(I, Inserted) = Map.insert(std::make_pair(ValType::get(Ty), Ty));
870       if (!Inserted) {
871         // Refined to a different type altogether?
872         RemoveFromTypesByHash(OldTypeHash, Ty);
873
874         // We already have this type in the table.  Get rid of the newly refined
875         // type.
876         TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
877         Ty->refineAbstractTypeTo(NewTy);
878         return;
879       }
880     } else {
881       // Now we check to see if there is an existing entry in the table which is
882       // structurally identical to the newly refined type.  If so, this type
883       // gets refined to the pre-existing type.
884       //
885       std::multimap<unsigned, PATypeHolder>::iterator I, E, Entry;
886       tie(I, E) = TypesByHash.equal_range(NewTypeHash);
887       Entry = E;
888       for (; I != E; ++I) {
889         if (I->second == Ty) {
890           // Remember the position of the old type if we see it in our scan.
891           Entry = I;
892         } else {
893           if (TypesEqual(Ty, I->second)) {
894             TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
895
896             // Remove the old entry form TypesByHash.  If the hash values differ
897             // now, remove it from the old place.  Otherwise, continue scanning
898             // withing this hashcode to reduce work.
899             if (NewTypeHash != OldTypeHash) {
900               RemoveFromTypesByHash(OldTypeHash, Ty);
901             } else {
902               if (Entry == E) {
903                 // Find the location of Ty in the TypesByHash structure if we
904                 // haven't seen it already.
905                 while (I->second != Ty) {
906                   ++I;
907                   assert(I != E && "Structure doesn't contain type??");
908                 }
909                 Entry = I;
910               }
911               TypesByHash.erase(Entry);
912             }
913             Ty->refineAbstractTypeTo(NewTy);
914             return;
915           }
916         }
917       }
918
919       // If there is no existing type of the same structure, we reinsert an
920       // updated record into the map.
921       Map.insert(std::make_pair(ValType::get(Ty), Ty));
922     }
923
924     // If the hash codes differ, update TypesByHash
925     if (NewTypeHash != OldTypeHash) {
926       RemoveFromTypesByHash(OldTypeHash, Ty);
927       TypesByHash.insert(std::make_pair(NewTypeHash, Ty));
928     }
929     
930     // If the type is currently thought to be abstract, rescan all of our
931     // subtypes to see if the type has just become concrete!  Note that this
932     // may send out notifications to AbstractTypeUsers that types become
933     // concrete.
934     if (Ty->isAbstract())
935       Ty->PromoteAbstractToConcrete();
936   }
937
938   void print(const char *Arg) const {
939 #ifdef DEBUG_MERGE_TYPES
940     std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
941     unsigned i = 0;
942     for (typename std::map<ValType, PATypeHolder>::const_iterator I
943            = Map.begin(), E = Map.end(); I != E; ++I)
944       std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " "
945                 << *I->second.get() << "\n";
946 #endif
947   }
948
949   void dump() const { print("dump output"); }
950 };
951 }
952
953
954 //===----------------------------------------------------------------------===//
955 // Function Type Factory and Value Class...
956 //
957
958 // FunctionValType - Define a class to hold the key that goes into the TypeMap
959 //
960 namespace llvm {
961 class FunctionValType {
962   const Type *RetTy;
963   std::vector<const Type*> ArgTypes;
964   bool isVarArg;
965 public:
966   FunctionValType(const Type *ret, const std::vector<const Type*> &args,
967                   bool IVA) : RetTy(ret), isVarArg(IVA) {
968     for (unsigned i = 0; i < args.size(); ++i)
969       ArgTypes.push_back(args[i]);
970   }
971
972   static FunctionValType get(const FunctionType *FT);
973
974   static unsigned hashTypeStructure(const FunctionType *FT) {
975     return FT->getNumParams()*2+FT->isVarArg();
976   }
977
978   // Subclass should override this... to update self as usual
979   void doRefinement(const DerivedType *OldType, const Type *NewType) {
980     if (RetTy == OldType) RetTy = NewType;
981     for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
982       if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
983   }
984
985   inline bool operator<(const FunctionValType &MTV) const {
986     if (RetTy < MTV.RetTy) return true;
987     if (RetTy > MTV.RetTy) return false;
988
989     if (ArgTypes < MTV.ArgTypes) return true;
990     return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
991   }
992 };
993 }
994
995 // Define the actual map itself now...
996 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
997
998 FunctionValType FunctionValType::get(const FunctionType *FT) {
999   // Build up a FunctionValType
1000   std::vector<const Type *> ParamTypes;
1001   ParamTypes.reserve(FT->getNumParams());
1002   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1003     ParamTypes.push_back(FT->getParamType(i));
1004   return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
1005 }
1006
1007
1008 // FunctionType::get - The factory function for the FunctionType class...
1009 FunctionType *FunctionType::get(const Type *ReturnType,
1010                                 const std::vector<const Type*> &Params,
1011                                 bool isVarArg) {
1012   FunctionValType VT(ReturnType, Params, isVarArg);
1013   FunctionType *MT = FunctionTypes.get(VT);
1014   if (MT) return MT;
1015
1016   FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
1017
1018 #ifdef DEBUG_MERGE_TYPES
1019   std::cerr << "Derived new type: " << MT << "\n";
1020 #endif
1021   return MT;
1022 }
1023
1024 //===----------------------------------------------------------------------===//
1025 // Array Type Factory...
1026 //
1027 namespace llvm {
1028 class ArrayValType {
1029   const Type *ValTy;
1030   uint64_t Size;
1031 public:
1032   ArrayValType(const Type *val, uint64_t sz) : ValTy(val), Size(sz) {}
1033
1034   static ArrayValType get(const ArrayType *AT) {
1035     return ArrayValType(AT->getElementType(), AT->getNumElements());
1036   }
1037
1038   static unsigned hashTypeStructure(const ArrayType *AT) {
1039     return (unsigned)AT->getNumElements();
1040   }
1041
1042   // Subclass should override this... to update self as usual
1043   void doRefinement(const DerivedType *OldType, const Type *NewType) {
1044     assert(ValTy == OldType);
1045     ValTy = NewType;
1046   }
1047
1048   inline bool operator<(const ArrayValType &MTV) const {
1049     if (Size < MTV.Size) return true;
1050     return Size == MTV.Size && ValTy < MTV.ValTy;
1051   }
1052 };
1053 }
1054 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
1055
1056
1057 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
1058   assert(ElementType && "Can't get array of null types!");
1059
1060   ArrayValType AVT(ElementType, NumElements);
1061   ArrayType *AT = ArrayTypes.get(AVT);
1062   if (AT) return AT;           // Found a match, return it!
1063
1064   // Value not found.  Derive a new type!
1065   ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
1066
1067 #ifdef DEBUG_MERGE_TYPES
1068   std::cerr << "Derived new type: " << *AT << "\n";
1069 #endif
1070   return AT;
1071 }
1072
1073
1074 //===----------------------------------------------------------------------===//
1075 // Packed Type Factory...
1076 //
1077 namespace llvm {
1078 class PackedValType {
1079   const Type *ValTy;
1080   unsigned Size;
1081 public:
1082   PackedValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
1083
1084   static PackedValType get(const PackedType *PT) {
1085     return PackedValType(PT->getElementType(), PT->getNumElements());
1086   }
1087
1088   static unsigned hashTypeStructure(const PackedType *PT) {
1089     return PT->getNumElements();
1090   }
1091
1092   // Subclass should override this... to update self as usual
1093   void doRefinement(const DerivedType *OldType, const Type *NewType) {
1094     assert(ValTy == OldType);
1095     ValTy = NewType;
1096   }
1097
1098   inline bool operator<(const PackedValType &MTV) const {
1099     if (Size < MTV.Size) return true;
1100     return Size == MTV.Size && ValTy < MTV.ValTy;
1101   }
1102 };
1103 }
1104 static TypeMap<PackedValType, PackedType> PackedTypes;
1105
1106
1107 PackedType *PackedType::get(const Type *ElementType, unsigned NumElements) {
1108   assert(ElementType && "Can't get packed of null types!");
1109   assert(isPowerOf2_32(NumElements) && "Vector length should be a power of 2!");
1110
1111   PackedValType PVT(ElementType, NumElements);
1112   PackedType *PT = PackedTypes.get(PVT);
1113   if (PT) return PT;           // Found a match, return it!
1114
1115   // Value not found.  Derive a new type!
1116   PackedTypes.add(PVT, PT = new PackedType(ElementType, NumElements));
1117
1118 #ifdef DEBUG_MERGE_TYPES
1119   std::cerr << "Derived new type: " << *PT << "\n";
1120 #endif
1121   return PT;
1122 }
1123
1124 //===----------------------------------------------------------------------===//
1125 // Struct Type Factory...
1126 //
1127
1128 namespace llvm {
1129 // StructValType - Define a class to hold the key that goes into the TypeMap
1130 //
1131 class StructValType {
1132   std::vector<const Type*> ElTypes;
1133 public:
1134   StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
1135
1136   static StructValType get(const StructType *ST) {
1137     std::vector<const Type *> ElTypes;
1138     ElTypes.reserve(ST->getNumElements());
1139     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
1140       ElTypes.push_back(ST->getElementType(i));
1141
1142     return StructValType(ElTypes);
1143   }
1144
1145   static unsigned hashTypeStructure(const StructType *ST) {
1146     return ST->getNumElements();
1147   }
1148
1149   // Subclass should override this... to update self as usual
1150   void doRefinement(const DerivedType *OldType, const Type *NewType) {
1151     for (unsigned i = 0; i < ElTypes.size(); ++i)
1152       if (ElTypes[i] == OldType) ElTypes[i] = NewType;
1153   }
1154
1155   inline bool operator<(const StructValType &STV) const {
1156     return ElTypes < STV.ElTypes;
1157   }
1158 };
1159 }
1160
1161 static TypeMap<StructValType, StructType> StructTypes;
1162
1163 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
1164   StructValType STV(ETypes);
1165   StructType *ST = StructTypes.get(STV);
1166   if (ST) return ST;
1167
1168   // Value not found.  Derive a new type!
1169   StructTypes.add(STV, ST = new StructType(ETypes));
1170
1171 #ifdef DEBUG_MERGE_TYPES
1172   std::cerr << "Derived new type: " << *ST << "\n";
1173 #endif
1174   return ST;
1175 }
1176
1177
1178
1179 //===----------------------------------------------------------------------===//
1180 // Pointer Type Factory...
1181 //
1182
1183 // PointerValType - Define a class to hold the key that goes into the TypeMap
1184 //
1185 namespace llvm {
1186 class PointerValType {
1187   const Type *ValTy;
1188 public:
1189   PointerValType(const Type *val) : ValTy(val) {}
1190
1191   static PointerValType get(const PointerType *PT) {
1192     return PointerValType(PT->getElementType());
1193   }
1194
1195   static unsigned hashTypeStructure(const PointerType *PT) {
1196     return getSubElementHash(PT);
1197   }
1198
1199   // Subclass should override this... to update self as usual
1200   void doRefinement(const DerivedType *OldType, const Type *NewType) {
1201     assert(ValTy == OldType);
1202     ValTy = NewType;
1203   }
1204
1205   bool operator<(const PointerValType &MTV) const {
1206     return ValTy < MTV.ValTy;
1207   }
1208 };
1209 }
1210
1211 static TypeMap<PointerValType, PointerType> PointerTypes;
1212
1213 PointerType *PointerType::get(const Type *ValueType) {
1214   assert(ValueType && "Can't get a pointer to <null> type!");
1215   assert(ValueType != Type::VoidTy &&
1216          "Pointer to void is not valid, use sbyte* instead!");
1217   PointerValType PVT(ValueType);
1218
1219   PointerType *PT = PointerTypes.get(PVT);
1220   if (PT) return PT;
1221
1222   // Value not found.  Derive a new type!
1223   PointerTypes.add(PVT, PT = new PointerType(ValueType));
1224
1225 #ifdef DEBUG_MERGE_TYPES
1226   std::cerr << "Derived new type: " << *PT << "\n";
1227 #endif
1228   return PT;
1229 }
1230
1231 //===----------------------------------------------------------------------===//
1232 //                     Derived Type Refinement Functions
1233 //===----------------------------------------------------------------------===//
1234
1235 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1236 // no longer has a handle to the type.  This function is called primarily by
1237 // the PATypeHandle class.  When there are no users of the abstract type, it
1238 // is annihilated, because there is no way to get a reference to it ever again.
1239 //
1240 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
1241   // Search from back to front because we will notify users from back to
1242   // front.  Also, it is likely that there will be a stack like behavior to
1243   // users that register and unregister users.
1244   //
1245   unsigned i;
1246   for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1247     assert(i != 0 && "AbstractTypeUser not in user list!");
1248
1249   --i;  // Convert to be in range 0 <= i < size()
1250   assert(i < AbstractTypeUsers.size() && "Index out of range!");  // Wraparound?
1251
1252   AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1253
1254 #ifdef DEBUG_MERGE_TYPES
1255   std::cerr << "  remAbstractTypeUser[" << (void*)this << ", "
1256             << *this << "][" << i << "] User = " << U << "\n";
1257 #endif
1258
1259   if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1260 #ifdef DEBUG_MERGE_TYPES
1261     std::cerr << "DELETEing unused abstract type: <" << *this
1262               << ">[" << (void*)this << "]" << "\n";
1263 #endif
1264     delete this;                  // No users of this abstract type!
1265   }
1266 }
1267
1268
1269 // refineAbstractTypeTo - This function is used when it is discovered that
1270 // the 'this' abstract type is actually equivalent to the NewType specified.
1271 // This causes all users of 'this' to switch to reference the more concrete type
1272 // NewType and for 'this' to be deleted.
1273 //
1274 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1275   assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1276   assert(this != NewType && "Can't refine to myself!");
1277   assert(ForwardType == 0 && "This type has already been refined!");
1278
1279   // The descriptions may be out of date.  Conservatively clear them all!
1280   AbstractTypeDescriptions.clear();
1281
1282 #ifdef DEBUG_MERGE_TYPES
1283   std::cerr << "REFINING abstract type [" << (void*)this << " "
1284             << *this << "] to [" << (void*)NewType << " "
1285             << *NewType << "]!\n";
1286 #endif
1287
1288   // Make sure to put the type to be refined to into a holder so that if IT gets
1289   // refined, that we will not continue using a dead reference...
1290   //
1291   PATypeHolder NewTy(NewType);
1292
1293   // Any PATypeHolders referring to this type will now automatically forward to
1294   // the type we are resolved to.
1295   ForwardType = NewType;
1296   if (NewType->isAbstract())
1297     cast<DerivedType>(NewType)->addRef();
1298
1299   // Add a self use of the current type so that we don't delete ourself until
1300   // after the function exits.
1301   //
1302   PATypeHolder CurrentTy(this);
1303
1304   // To make the situation simpler, we ask the subclass to remove this type from
1305   // the type map, and to replace any type uses with uses of non-abstract types.
1306   // This dramatically limits the amount of recursive type trouble we can find
1307   // ourselves in.
1308   dropAllTypeUses();
1309
1310   // Iterate over all of the uses of this type, invoking callback.  Each user
1311   // should remove itself from our use list automatically.  We have to check to
1312   // make sure that NewTy doesn't _become_ 'this'.  If it does, resolving types
1313   // will not cause users to drop off of the use list.  If we resolve to ourself
1314   // we succeed!
1315   //
1316   while (!AbstractTypeUsers.empty() && NewTy != this) {
1317     AbstractTypeUser *User = AbstractTypeUsers.back();
1318
1319     unsigned OldSize = AbstractTypeUsers.size();
1320 #ifdef DEBUG_MERGE_TYPES
1321     std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
1322               << "] of abstract type [" << (void*)this << " "
1323               << *this << "] to [" << (void*)NewTy.get() << " "
1324               << *NewTy << "]!\n";
1325 #endif
1326     User->refineAbstractType(this, NewTy);
1327
1328     assert(AbstractTypeUsers.size() != OldSize &&
1329            "AbsTyUser did not remove self from user list!");
1330   }
1331
1332   // If we were successful removing all users from the type, 'this' will be
1333   // deleted when the last PATypeHolder is destroyed or updated from this type.
1334   // This may occur on exit of this function, as the CurrentTy object is
1335   // destroyed.
1336 }
1337
1338 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1339 // the current type has transitioned from being abstract to being concrete.
1340 //
1341 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1342 #ifdef DEBUG_MERGE_TYPES
1343   std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1344 #endif
1345
1346   unsigned OldSize = AbstractTypeUsers.size();
1347   while (!AbstractTypeUsers.empty()) {
1348     AbstractTypeUser *ATU = AbstractTypeUsers.back();
1349     ATU->typeBecameConcrete(this);
1350
1351     assert(AbstractTypeUsers.size() < OldSize-- &&
1352            "AbstractTypeUser did not remove itself from the use list!");
1353   }
1354 }
1355
1356 // refineAbstractType - Called when a contained type is found to be more
1357 // concrete - this could potentially change us from an abstract type to a
1358 // concrete type.
1359 //
1360 void FunctionType::refineAbstractType(const DerivedType *OldType,
1361                                       const Type *NewType) {
1362   FunctionTypes.RefineAbstractType(this, OldType, NewType);
1363 }
1364
1365 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1366   FunctionTypes.TypeBecameConcrete(this, AbsTy);
1367 }
1368
1369
1370 // refineAbstractType - Called when a contained type is found to be more
1371 // concrete - this could potentially change us from an abstract type to a
1372 // concrete type.
1373 //
1374 void ArrayType::refineAbstractType(const DerivedType *OldType,
1375                                    const Type *NewType) {
1376   ArrayTypes.RefineAbstractType(this, OldType, NewType);
1377 }
1378
1379 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1380   ArrayTypes.TypeBecameConcrete(this, AbsTy);
1381 }
1382
1383 // refineAbstractType - Called when a contained type is found to be more
1384 // concrete - this could potentially change us from an abstract type to a
1385 // concrete type.
1386 //
1387 void PackedType::refineAbstractType(const DerivedType *OldType,
1388                                    const Type *NewType) {
1389   PackedTypes.RefineAbstractType(this, OldType, NewType);
1390 }
1391
1392 void PackedType::typeBecameConcrete(const DerivedType *AbsTy) {
1393   PackedTypes.TypeBecameConcrete(this, AbsTy);
1394 }
1395
1396 // refineAbstractType - Called when a contained type is found to be more
1397 // concrete - this could potentially change us from an abstract type to a
1398 // concrete type.
1399 //
1400 void StructType::refineAbstractType(const DerivedType *OldType,
1401                                     const Type *NewType) {
1402   StructTypes.RefineAbstractType(this, OldType, NewType);
1403 }
1404
1405 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1406   StructTypes.TypeBecameConcrete(this, AbsTy);
1407 }
1408
1409 // refineAbstractType - Called when a contained type is found to be more
1410 // concrete - this could potentially change us from an abstract type to a
1411 // concrete type.
1412 //
1413 void PointerType::refineAbstractType(const DerivedType *OldType,
1414                                      const Type *NewType) {
1415   PointerTypes.RefineAbstractType(this, OldType, NewType);
1416 }
1417
1418 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1419   PointerTypes.TypeBecameConcrete(this, AbsTy);
1420 }
1421
1422 bool SequentialType::indexValid(const Value *V) const {
1423   const Type *Ty = V->getType();
1424   switch (Ty->getTypeID()) {
1425   case Type::IntTyID:
1426   case Type::UIntTyID:
1427   case Type::LongTyID:
1428   case Type::ULongTyID:
1429     return true;
1430   default:
1431     return false;
1432   }
1433 }
1434
1435 namespace llvm {
1436 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1437   if (T == 0)
1438     OS << "<null> value!\n";
1439   else
1440     T->print(OS);
1441   return OS;
1442 }
1443
1444 std::ostream &operator<<(std::ostream &OS, const Type &T) {
1445   T.print(OS);
1446   return OS;
1447 }
1448 }
1449
1450 /// clearAllTypeMaps - This method frees all internal memory used by the
1451 /// type subsystem, which can be used in environments where this memory is
1452 /// otherwise reported as a leak.
1453 void Type::clearAllTypeMaps() {
1454   std::vector<Type *> DerivedTypes;
1455
1456   FunctionTypes.clear(DerivedTypes);
1457   PointerTypes.clear(DerivedTypes);
1458   StructTypes.clear(DerivedTypes);
1459   ArrayTypes.clear(DerivedTypes);
1460   PackedTypes.clear(DerivedTypes);
1461
1462   for(std::vector<Type *>::iterator I = DerivedTypes.begin(),
1463       E = DerivedTypes.end(); I != E; ++I)
1464     (*I)->ContainedTys.clear();
1465   for(std::vector<Type *>::iterator I = DerivedTypes.begin(),
1466       E = DerivedTypes.end(); I != E; ++I)
1467     delete *I;
1468   DerivedTypes.clear();
1469 }
1470
1471 // vim: sw=2