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