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