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