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