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