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