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