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