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