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