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