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