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