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