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