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