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