1 //===-- Type.cpp - Implement the Type class ----------------------*- C++ -*--=//
3 // This file implements the Type class for the VMCore library.
5 //===----------------------------------------------------------------------===//
7 #include "llvm/DerivedTypes.h"
8 #include "llvm/SymbolTable.h"
9 #include "Support/StringExtras.h"
10 #include "Support/STLExtras.h"
20 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
21 // created and later destroyed, all in an effort to make sure that there is only
22 // a single cannonical version of a type.
24 //#define DEBUG_MERGE_TYPES 1
28 //===----------------------------------------------------------------------===//
29 // Type Class Implementation
30 //===----------------------------------------------------------------------===//
32 static unsigned CurUID = 0;
33 static vector<const Type *> UIDMappings;
35 Type::Type(const string &name, PrimitiveID id)
36 : Value(Type::TypeTy, Value::TypeVal) {
39 Abstract = Recursive = false;
40 UID = CurUID++; // Assign types UID's as they are created
41 UIDMappings.push_back(this);
44 void Type::setName(const string &Name, SymbolTable *ST) {
45 assert(ST && "Type::setName - Must provide symbol table argument!");
47 if (Name.size()) ST->insert(Name, this);
51 const Type *Type::getUniqueIDType(unsigned UID) {
52 assert(UID < UIDMappings.size() &&
53 "Type::getPrimitiveType: UID out of range!");
54 return UIDMappings[UID];
57 const Type *Type::getPrimitiveType(PrimitiveID IDNumber) {
59 case VoidTyID : return VoidTy;
60 case BoolTyID : return BoolTy;
61 case UByteTyID : return UByteTy;
62 case SByteTyID : return SByteTy;
63 case UShortTyID: return UShortTy;
64 case ShortTyID : return ShortTy;
65 case UIntTyID : return UIntTy;
66 case IntTyID : return IntTy;
67 case ULongTyID : return ULongTy;
68 case LongTyID : return LongTy;
69 case FloatTyID : return FloatTy;
70 case DoubleTyID: return DoubleTy;
71 case TypeTyID : return TypeTy;
72 case LabelTyID : return LabelTy;
78 // isLosslesslyConvertableTo - Return true if this type can be converted to
79 // 'Ty' without any reinterpretation of bits. For example, uint to int.
81 bool Type::isLosslesslyConvertableTo(const Type *Ty) const {
82 if (this == Ty) return true;
83 if ((!isPrimitiveType() && !isPointerType()) ||
84 (!Ty->isPointerType() && !Ty->isPrimitiveType())) return false;
86 if (getPrimitiveID() == Ty->getPrimitiveID())
87 return true; // Handles identity cast, and cast of differing pointer types
89 // Now we know that they are two differing primitive or pointer types
90 switch (getPrimitiveID()) {
91 case Type::UByteTyID: return Ty == Type::SByteTy;
92 case Type::SByteTyID: return Ty == Type::UByteTy;
93 case Type::UShortTyID: return Ty == Type::ShortTy;
94 case Type::ShortTyID: return Ty == Type::UShortTy;
95 case Type::UIntTyID: return Ty == Type::IntTy;
96 case Type::IntTyID: return Ty == Type::UIntTy;
99 case Type::PointerTyID:
100 return Ty == Type::ULongTy || Ty == Type::LongTy ||
101 Ty->getPrimitiveID() == Type::PointerTyID;
103 return false; // Other types have no identity values
108 bool StructType::indexValid(const Value *V) const {
109 if (!isa<Constant>(V)) return false;
110 if (V->getType() != Type::UByteTy) return false;
111 unsigned Idx = cast<ConstantUInt>(V)->getValue();
112 return Idx < ETypes.size();
115 // getTypeAtIndex - Given an index value into the type, return the type of the
116 // element. For a structure type, this must be a constant value...
118 const Type *StructType::getTypeAtIndex(const Value *V) const {
119 assert(isa<Constant>(V) && "Structure index must be a constant!!");
120 assert(V->getType() == Type::UByteTy && "Structure index must be ubyte!");
121 unsigned Idx = cast<ConstantUInt>(V)->getValue();
122 assert(Idx < ETypes.size() && "Structure index out of range!");
123 assert(indexValid(V) && "Invalid structure index!"); // Duplicate check
129 //===----------------------------------------------------------------------===//
130 // Auxilliary classes
131 //===----------------------------------------------------------------------===//
133 // These classes are used to implement specialized behavior for each different
136 class SignedIntType : public Type {
139 SignedIntType(const string &Name, PrimitiveID id, int size) : Type(Name, id) {
143 // isSigned - Return whether a numeric type is signed.
144 virtual bool isSigned() const { return 1; }
146 // isIntegral - Equivalent to isSigned() || isUnsigned, but with only a single
147 // virtual function invocation.
149 virtual bool isIntegral() const { return 1; }
152 class UnsignedIntType : public Type {
155 UnsignedIntType(const string &N, PrimitiveID id, int size) : Type(N, id) {
159 // isUnsigned - Return whether a numeric type is signed.
160 virtual bool isUnsigned() const { return 1; }
162 // isIntegral - Equivalent to isSigned() || isUnsigned, but with only a single
163 // virtual function invocation.
165 virtual bool isIntegral() const { return 1; }
168 static struct TypeType : public Type {
169 TypeType() : Type("type", TypeTyID) {}
170 } TheTypeType; // Implement the type that is global.
173 //===----------------------------------------------------------------------===//
174 // Static 'Type' data
175 //===----------------------------------------------------------------------===//
177 Type *Type::VoidTy = new Type("void" , VoidTyID),
178 *Type::BoolTy = new Type("bool" , BoolTyID),
179 *Type::SByteTy = new SignedIntType("sbyte" , SByteTyID, 1),
180 *Type::UByteTy = new UnsignedIntType("ubyte" , UByteTyID, 1),
181 *Type::ShortTy = new SignedIntType("short" , ShortTyID, 2),
182 *Type::UShortTy = new UnsignedIntType("ushort", UShortTyID, 2),
183 *Type::IntTy = new SignedIntType("int" , IntTyID, 4),
184 *Type::UIntTy = new UnsignedIntType("uint" , UIntTyID, 4),
185 *Type::LongTy = new SignedIntType("long" , LongTyID, 8),
186 *Type::ULongTy = new UnsignedIntType("ulong" , ULongTyID, 8),
187 *Type::FloatTy = new Type("float" , FloatTyID),
188 *Type::DoubleTy = new Type("double", DoubleTyID),
189 *Type::TypeTy = &TheTypeType,
190 *Type::LabelTy = new Type("label" , LabelTyID);
193 //===----------------------------------------------------------------------===//
194 // Derived Type Constructors
195 //===----------------------------------------------------------------------===//
197 FunctionType::FunctionType(const Type *Result,
198 const vector<const Type*> &Params,
199 bool IsVarArgs) : DerivedType(FunctionTyID),
200 ResultType(PATypeHandle<Type>(Result, this)),
201 isVarArgs(IsVarArgs) {
202 ParamTys.reserve(Params.size());
203 for (unsigned i = 0; i < Params.size(); ++i)
204 ParamTys.push_back(PATypeHandle<Type>(Params[i], this));
206 setDerivedTypeProperties();
209 StructType::StructType(const vector<const Type*> &Types)
210 : CompositeType(StructTyID) {
211 ETypes.reserve(Types.size());
212 for (unsigned i = 0; i < Types.size(); ++i) {
213 assert(Types[i] != Type::VoidTy && "Void type in method prototype!!");
214 ETypes.push_back(PATypeHandle<Type>(Types[i], this));
216 setDerivedTypeProperties();
219 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
220 : SequentialType(ArrayTyID, ElType) {
222 setDerivedTypeProperties();
225 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
226 setDerivedTypeProperties();
229 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
231 setDescription("opaque"+utostr(getUniqueID()));
232 #ifdef DEBUG_MERGE_TYPES
233 cerr << "Derived new type: " << getDescription() << endl;
240 //===----------------------------------------------------------------------===//
241 // Derived Type setDerivedTypeProperties Function
242 //===----------------------------------------------------------------------===//
244 // getTypeProps - This is a recursive function that walks a type hierarchy
245 // calculating the description for a type and whether or not it is abstract or
246 // recursive. Worst case it will have to do a lot of traversing if you have
247 // some whacko opaque types, but in most cases, it will do some simple stuff
248 // when it hits non-abstract types that aren't recursive.
250 static string getTypeProps(const Type *Ty, vector<const Type *> &TypeStack,
251 bool &isAbstract, bool &isRecursive) {
253 if (!Ty->isAbstract() && !Ty->isRecursive() && // Base case for the recursion
254 Ty->getDescription().size()) {
255 Result = Ty->getDescription(); // Primitive = leaf type
256 } else if (isa<OpaqueType>(Ty)) { // Base case for the recursion
257 Result = Ty->getDescription(); // Opaque = leaf type
258 isAbstract = true; // This whole type is abstract!
260 // Check to see if the Type is already on the stack...
261 unsigned Slot = 0, CurSize = TypeStack.size();
262 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
264 // This is another base case for the recursion. In this case, we know
265 // that we have looped back to a type that we have previously visited.
266 // Generate the appropriate upreference to handle this.
268 if (Slot < CurSize) {
269 Result = "\\" + utostr(CurSize-Slot); // Here's the upreference
270 isRecursive = true; // We know we are recursive
271 } else { // Recursive case: abstract derived type...
272 TypeStack.push_back(Ty); // Add us to the stack..
274 switch (Ty->getPrimitiveID()) {
275 case Type::FunctionTyID: {
276 const FunctionType *MTy = cast<const FunctionType>(Ty);
277 Result = getTypeProps(MTy->getReturnType(), TypeStack,
278 isAbstract, isRecursive)+" (";
279 for (FunctionType::ParamTypes::const_iterator
280 I = MTy->getParamTypes().begin(),
281 E = MTy->getParamTypes().end(); I != E; ++I) {
282 if (I != MTy->getParamTypes().begin())
284 Result += getTypeProps(*I, TypeStack, isAbstract, isRecursive);
286 if (MTy->isVarArg()) {
287 if (!MTy->getParamTypes().empty()) Result += ", ";
293 case Type::StructTyID: {
294 const StructType *STy = cast<const StructType>(Ty);
296 for (StructType::ElementTypes::const_iterator
297 I = STy->getElementTypes().begin(),
298 E = STy->getElementTypes().end(); I != E; ++I) {
299 if (I != STy->getElementTypes().begin())
301 Result += getTypeProps(*I, TypeStack, isAbstract, isRecursive);
306 case Type::PointerTyID: {
307 const PointerType *PTy = cast<const PointerType>(Ty);
308 Result = getTypeProps(PTy->getElementType(), TypeStack,
309 isAbstract, isRecursive) + " *";
312 case Type::ArrayTyID: {
313 const ArrayType *ATy = cast<const ArrayType>(Ty);
314 unsigned NumElements = ATy->getNumElements();
316 Result += utostr(NumElements) + " x ";
317 Result += getTypeProps(ATy->getElementType(), TypeStack,
318 isAbstract, isRecursive) + "]";
322 assert(0 && "Unhandled case in getTypeProps!");
326 TypeStack.pop_back(); // Remove self from stack...
333 // setDerivedTypeProperties - This function is used to calculate the
334 // isAbstract, isRecursive, and the Description settings for a type. The
335 // getTypeProps function does all the dirty work.
337 void DerivedType::setDerivedTypeProperties() {
338 vector<const Type *> TypeStack;
339 bool isAbstract = false, isRecursive = false;
341 setDescription(getTypeProps(this, TypeStack, isAbstract, isRecursive));
342 setAbstract(isAbstract);
343 setRecursive(isRecursive);
347 //===----------------------------------------------------------------------===//
348 // Type Structural Equality Testing
349 //===----------------------------------------------------------------------===//
351 // TypesEqual - Two types are considered structurally equal if they have the
352 // same "shape": Every level and element of the types have identical primitive
353 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
354 // be pointer equals to be equivalent though. This uses an optimistic algorithm
355 // that assumes that two graphs are the same until proven otherwise.
357 static bool TypesEqual(const Type *Ty, const Type *Ty2,
358 map<const Type *, const Type *> &EqTypes) {
359 if (Ty == Ty2) return true;
360 if (Ty->getPrimitiveID() != Ty2->getPrimitiveID()) return false;
361 if (Ty->isPrimitiveType()) return true;
362 if (isa<OpaqueType>(Ty))
363 return false; // Two nonequal opaque types are never equal
365 map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
366 if (It != EqTypes.end())
367 return It->second == Ty2; // Looping back on a type, check for equality
369 // Otherwise, add the mapping to the table to make sure we don't get
370 // recursion on the types...
371 EqTypes.insert(make_pair(Ty, Ty2));
373 // Iterate over the types and make sure the the contents are equivalent...
374 Type::subtype_iterator I = Ty ->subtype_begin(), IE = Ty ->subtype_end();
375 Type::subtype_iterator I2 = Ty2->subtype_begin(), IE2 = Ty2->subtype_end();
376 for (; I != IE && I2 != IE2; ++I, ++I2)
377 if (!TypesEqual(*I, *I2, EqTypes)) return false;
379 // Two really annoying special cases that breaks an otherwise nice simple
380 // algorithm is the fact that arraytypes have sizes that differentiates types,
381 // and that method types can be varargs or not. Consider this now.
382 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
383 if (ATy->getNumElements() != cast<const ArrayType>(Ty2)->getNumElements())
385 } else if (const FunctionType *MTy = dyn_cast<FunctionType>(Ty)) {
386 if (MTy->isVarArg() != cast<const FunctionType>(Ty2)->isVarArg())
390 return I == IE && I2 == IE2; // Types equal if both iterators are done
393 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
394 map<const Type *, const Type *> EqTypes;
395 return TypesEqual(Ty, Ty2, EqTypes);
400 //===----------------------------------------------------------------------===//
401 // Derived Type Factory Functions
402 //===----------------------------------------------------------------------===//
404 // TypeMap - Make sure that only one instance of a particular type may be
405 // created on any given run of the compiler... note that this involves updating
406 // our map if an abstract type gets refined somehow...
408 template<class ValType, class TypeClass>
409 class TypeMap : public AbstractTypeUser {
410 typedef map<ValType, PATypeHandle<TypeClass> > MapTy;
414 ~TypeMap() { print("ON EXIT"); }
416 inline TypeClass *get(const ValType &V) {
417 map<ValType, PATypeHandle<TypeClass> >::iterator I = Map.find(V);
418 // TODO: FIXME: When Types are not CONST.
419 return (I != Map.end()) ? (TypeClass*)I->second.get() : 0;
422 inline void add(const ValType &V, TypeClass *T) {
423 Map.insert(make_pair(V, PATypeHandle<TypeClass>(T, this)));
427 // containsEquivalent - Return true if the typemap contains a type that is
428 // structurally equivalent to the specified type.
430 inline const TypeClass *containsEquivalent(const TypeClass *Ty) {
431 for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
432 if (I->second.get() != Ty && TypesEqual(Ty, I->second.get()))
433 return (TypeClass*)I->second.get(); // FIXME TODO when types not const
437 // refineAbstractType - This is called when one of the contained abstract
438 // types gets refined... this simply removes the abstract type from our table.
439 // We expect that whoever refined the type will add it back to the table,
442 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
443 if (OldTy == NewTy) {
444 if (!OldTy->isAbstract()) {
445 // Check to see if the type just became concrete.
446 // If so, remove self from user list.
447 for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
448 if (I->second == OldTy)
449 I->second.removeUserFromConcrete();
453 #ifdef DEBUG_MERGE_TYPES
454 cerr << "Removing Old type from Tab: " << (void*)OldTy << ", "
455 << OldTy->getDescription() << " replacement == " << (void*)NewTy
456 << ", " << NewTy->getDescription() << endl;
458 for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
459 if (I->second == OldTy) {
461 print("refineAbstractType after");
464 assert(0 && "Abstract type not found in table!");
467 void remove(const ValType &OldVal) {
468 MapTy::iterator I = Map.find(OldVal);
469 assert(I != Map.end() && "TypeMap::remove, element not found!");
473 void print(const char *Arg) {
474 #ifdef DEBUG_MERGE_TYPES
475 cerr << "TypeMap<>::" << Arg << " table contents:\n";
477 for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
478 cerr << " " << (++i) << ". " << I->second << " "
479 << I->second->getDescription() << endl;
485 // ValTypeBase - This is the base class that is used by the various
486 // instantiations of TypeMap. This class is an AbstractType user that notifies
487 // the underlying TypeMap when it gets modified.
489 template<class ValType, class TypeClass>
490 class ValTypeBase : public AbstractTypeUser {
491 TypeMap<ValType, TypeClass> &MyTable;
493 inline ValTypeBase(TypeMap<ValType, TypeClass> &tab) : MyTable(tab) {}
495 // Subclass should override this... to update self as usual
496 virtual void doRefinement(const DerivedType *OldTy, const Type *NewTy) = 0;
498 // typeBecameConcrete - This callback occurs when a contained type refines
499 // to itself, but becomes concrete in the process. Our subclass should remove
500 // itself from the ATU list of the specified type.
502 virtual void typeBecameConcrete(const DerivedType *Ty) = 0;
504 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
505 if (OldTy == NewTy) {
506 if (!OldTy->isAbstract())
507 typeBecameConcrete(OldTy);
510 TypeMap<ValType, TypeClass> &Table = MyTable; // Copy MyTable reference
511 ValType Tmp(*(ValType*)this); // Copy this.
512 PATypeHandle<TypeClass> OldType(Table.get(*(ValType*)this), this);
513 Table.remove(*(ValType*)this); // Destroy's this!
515 // Refine temporary to new state...
516 Tmp.doRefinement(OldTy, NewTy);
518 Table.add((ValType&)Tmp, (TypeClass*)OldType.get());
525 //===----------------------------------------------------------------------===//
526 // Function Type Factory and Value Class...
529 // FunctionValType - Define a class to hold the key that goes into the TypeMap
531 class FunctionValType : public ValTypeBase<FunctionValType, FunctionType> {
532 PATypeHandle<Type> RetTy;
533 vector<PATypeHandle<Type> > ArgTypes;
536 FunctionValType(const Type *ret, const vector<const Type*> &args,
537 bool IVA, TypeMap<FunctionValType, FunctionType> &Tab)
538 : ValTypeBase<FunctionValType, FunctionType>(Tab), RetTy(ret, this),
540 for (unsigned i = 0; i < args.size(); ++i)
541 ArgTypes.push_back(PATypeHandle<Type>(args[i], this));
544 // We *MUST* have an explicit copy ctor so that the TypeHandles think that
545 // this FunctionValType owns them, not the old one!
547 FunctionValType(const FunctionValType &MVT)
548 : ValTypeBase<FunctionValType, FunctionType>(MVT), RetTy(MVT.RetTy, this),
549 isVarArg(MVT.isVarArg) {
550 ArgTypes.reserve(MVT.ArgTypes.size());
551 for (unsigned i = 0; i < MVT.ArgTypes.size(); ++i)
552 ArgTypes.push_back(PATypeHandle<Type>(MVT.ArgTypes[i], this));
555 // Subclass should override this... to update self as usual
556 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
557 if (RetTy == OldType) RetTy = NewType;
558 for (unsigned i = 0; i < ArgTypes.size(); ++i)
559 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
562 virtual void typeBecameConcrete(const DerivedType *Ty) {
563 if (RetTy == Ty) RetTy.removeUserFromConcrete();
565 for (unsigned i = 0; i < ArgTypes.size(); ++i)
566 if (ArgTypes[i] == Ty) ArgTypes[i].removeUserFromConcrete();
569 inline bool operator<(const FunctionValType &MTV) const {
570 if (RetTy.get() < MTV.RetTy.get()) return true;
571 if (RetTy.get() > MTV.RetTy.get()) return false;
573 if (ArgTypes < MTV.ArgTypes) return true;
574 return (ArgTypes == MTV.ArgTypes) && isVarArg < MTV.isVarArg;
578 // Define the actual map itself now...
579 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
581 // FunctionType::get - The factory function for the FunctionType class...
582 FunctionType *FunctionType::get(const Type *ReturnType,
583 const vector<const Type*> &Params,
585 FunctionValType VT(ReturnType, Params, isVarArg, FunctionTypes);
586 FunctionType *MT = FunctionTypes.get(VT);
589 FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
591 #ifdef DEBUG_MERGE_TYPES
592 cerr << "Derived new type: " << MT << endl;
597 //===----------------------------------------------------------------------===//
598 // Array Type Factory...
600 class ArrayValType : public ValTypeBase<ArrayValType, ArrayType> {
601 PATypeHandle<Type> ValTy;
604 ArrayValType(const Type *val, int sz, TypeMap<ArrayValType, ArrayType> &Tab)
605 : ValTypeBase<ArrayValType, ArrayType>(Tab), ValTy(val, this), Size(sz) {}
607 // We *MUST* have an explicit copy ctor so that the ValTy thinks that this
608 // ArrayValType owns it, not the old one!
610 ArrayValType(const ArrayValType &AVT)
611 : ValTypeBase<ArrayValType, ArrayType>(AVT), ValTy(AVT.ValTy, this),
614 // Subclass should override this... to update self as usual
615 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
616 if (ValTy == OldType) ValTy = NewType;
619 virtual void typeBecameConcrete(const DerivedType *Ty) {
620 assert(ValTy == Ty &&
621 "Contained type became concrete but we're not using it!");
622 ValTy.removeUserFromConcrete();
625 inline bool operator<(const ArrayValType &MTV) const {
626 if (Size < MTV.Size) return true;
627 return Size == MTV.Size && ValTy.get() < MTV.ValTy.get();
631 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
633 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
634 assert(ElementType && "Can't get array of null types!");
636 ArrayValType AVT(ElementType, NumElements, ArrayTypes);
637 ArrayType *AT = ArrayTypes.get(AVT);
638 if (AT) return AT; // Found a match, return it!
640 // Value not found. Derive a new type!
641 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
643 #ifdef DEBUG_MERGE_TYPES
644 cerr << "Derived new type: " << AT->getDescription() << endl;
649 //===----------------------------------------------------------------------===//
650 // Struct Type Factory...
653 // StructValType - Define a class to hold the key that goes into the TypeMap
655 class StructValType : public ValTypeBase<StructValType, StructType> {
656 vector<PATypeHandle<Type> > ElTypes;
658 StructValType(const vector<const Type*> &args,
659 TypeMap<StructValType, StructType> &Tab)
660 : ValTypeBase<StructValType, StructType>(Tab) {
661 for (unsigned i = 0; i < args.size(); ++i)
662 ElTypes.push_back(PATypeHandle<Type>(args[i], this));
665 // We *MUST* have an explicit copy ctor so that the TypeHandles think that
666 // this StructValType owns them, not the old one!
668 StructValType(const StructValType &SVT)
669 : ValTypeBase<StructValType, StructType>(SVT){
670 ElTypes.reserve(SVT.ElTypes.size());
671 for (unsigned i = 0; i < SVT.ElTypes.size(); ++i)
672 ElTypes.push_back(PATypeHandle<Type>(SVT.ElTypes[i], this));
675 // Subclass should override this... to update self as usual
676 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
677 for (unsigned i = 0; i < ElTypes.size(); ++i)
678 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
681 virtual void typeBecameConcrete(const DerivedType *Ty) {
682 for (unsigned i = 0; i < ElTypes.size(); ++i)
683 if (ElTypes[i] == Ty) ElTypes[i].removeUserFromConcrete();
686 inline bool operator<(const StructValType &STV) const {
687 return ElTypes < STV.ElTypes;
691 static TypeMap<StructValType, StructType> StructTypes;
693 StructType *StructType::get(const vector<const Type*> &ETypes) {
694 StructValType STV(ETypes, StructTypes);
695 StructType *ST = StructTypes.get(STV);
698 // Value not found. Derive a new type!
699 StructTypes.add(STV, ST = new StructType(ETypes));
701 #ifdef DEBUG_MERGE_TYPES
702 cerr << "Derived new type: " << ST->getDescription() << endl;
707 //===----------------------------------------------------------------------===//
708 // Pointer Type Factory...
711 // PointerValType - Define a class to hold the key that goes into the TypeMap
713 class PointerValType : public ValTypeBase<PointerValType, PointerType> {
714 PATypeHandle<Type> ValTy;
716 PointerValType(const Type *val, TypeMap<PointerValType, PointerType> &Tab)
717 : ValTypeBase<PointerValType, PointerType>(Tab), ValTy(val, this) {}
719 // We *MUST* have an explicit copy ctor so that the ValTy thinks that this
720 // PointerValType owns it, not the old one!
722 PointerValType(const PointerValType &PVT)
723 : ValTypeBase<PointerValType, PointerType>(PVT), ValTy(PVT.ValTy, this) {}
725 // Subclass should override this... to update self as usual
726 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
727 if (ValTy == OldType) ValTy = NewType;
730 virtual void typeBecameConcrete(const DerivedType *Ty) {
731 assert(ValTy == Ty &&
732 "Contained type became concrete but we're not using it!");
733 ValTy.removeUserFromConcrete();
736 inline bool operator<(const PointerValType &MTV) const {
737 return ValTy.get() < MTV.ValTy.get();
741 static TypeMap<PointerValType, PointerType> PointerTypes;
743 PointerType *PointerType::get(const Type *ValueType) {
744 assert(ValueType && "Can't get a pointer to <null> type!");
745 PointerValType PVT(ValueType, PointerTypes);
747 PointerType *PT = PointerTypes.get(PVT);
750 // Value not found. Derive a new type!
751 PointerTypes.add(PVT, PT = new PointerType(ValueType));
753 #ifdef DEBUG_MERGE_TYPES
754 cerr << "Derived new type: " << PT->getDescription() << endl;
761 //===----------------------------------------------------------------------===//
762 // Derived Type Refinement Functions
763 //===----------------------------------------------------------------------===//
765 // removeAbstractTypeUser - Notify an abstract type that a user of the class
766 // no longer has a handle to the type. This function is called primarily by
767 // the PATypeHandle class. When there are no users of the abstract type, it
768 // is anihilated, because there is no way to get a reference to it ever again.
770 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
771 // Search from back to front because we will notify users from back to
772 // front. Also, it is likely that there will be a stack like behavior to
773 // users that register and unregister users.
775 for (unsigned i = AbstractTypeUsers.size(); i > 0; --i) {
776 if (AbstractTypeUsers[i-1] == U) {
777 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i-1);
779 #ifdef DEBUG_MERGE_TYPES
780 cerr << " removeAbstractTypeUser<" << (void*)this << ", "
781 << getDescription() << ">[" << i << "] User = " << U << endl;
784 if (AbstractTypeUsers.empty() && isAbstract()) {
785 #ifdef DEBUG_MERGE_TYPES
786 cerr << "DELETEing unused abstract type: <" << getDescription()
787 << ">[" << (void*)this << "]" << endl;
789 delete this; // No users of this abstract type!
794 assert(0 && "AbstractTypeUser not in user list!");
798 // refineAbstractTypeTo - This function is used to when it is discovered that
799 // the 'this' abstract type is actually equivalent to the NewType specified.
800 // This causes all users of 'this' to switch to reference the more concrete
801 // type NewType and for 'this' to be deleted.
803 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
804 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
805 assert(this != NewType && "Can't refine to myself!");
807 #ifdef DEBUG_MERGE_TYPES
808 cerr << "REFINING abstract type [" << (void*)this << " " << getDescription()
809 << "] to [" << (void*)NewType << " " << NewType->getDescription()
814 // Make sure to put the type to be refined to into a holder so that if IT gets
815 // refined, that we will not continue using a dead reference...
817 PATypeHolder<Type> NewTy(NewType);
819 // Add a self use of the current type so that we don't delete ourself until
820 // after this while loop. We are careful to never invoke refine on ourself,
821 // so this extra reference shouldn't be a problem. Note that we must only
822 // remove a single reference at the end, but we must tolerate multiple self
823 // references because we could be refineAbstractTypeTo'ing recursively on the
826 addAbstractTypeUser(this);
828 // Count the number of self uses. Stop looping when sizeof(list) == NSU.
829 unsigned NumSelfUses = 0;
831 // Iterate over all of the uses of this type, invoking callback. Each user
832 // should remove itself from our use list automatically.
834 while (AbstractTypeUsers.size() > NumSelfUses) {
835 AbstractTypeUser *User = AbstractTypeUsers.back();
838 // Move self use to the start of the list. Increment NSU.
839 swap(AbstractTypeUsers.back(), AbstractTypeUsers[NumSelfUses++]);
841 unsigned OldSize = AbstractTypeUsers.size();
842 #ifdef DEBUG_MERGE_TYPES
843 cerr << " REFINING user " << OldSize-1 << " of abstract type ["
844 << (void*)this << " " << getDescription() << "] to ["
845 << (void*)NewTy.get() << " " << NewTy->getDescription() << "]!\n";
847 User->refineAbstractType(this, NewTy);
849 if (AbstractTypeUsers.size() == OldSize) {
850 User->refineAbstractType(this, NewTy);
852 assert(AbstractTypeUsers.size() != OldSize &&
853 "AbsTyUser did not remove self from user list!");
857 // Remove a single self use, even though there may be several here. This will
858 // probably 'delete this', so no instance variables may be used after this
860 assert(AbstractTypeUsers.back() == this && "Only self uses should be left!");
861 removeAbstractTypeUser(this);
865 // typeIsRefined - Notify AbstractTypeUsers of this type that the current type
866 // has been refined a bit. The pointer is still valid and still should be
867 // used, but the subtypes have changed.
869 void DerivedType::typeIsRefined() {
870 assert(isRefining >= 0 && isRefining <= 2 && "isRefining out of bounds!");
871 if (isRefining == 1) return; // Kill recursion here...
874 #ifdef DEBUG_MERGE_TYPES
875 cerr << "typeIsREFINED type: " << (void*)this <<" "<<getDescription() << endl;
877 for (unsigned i = 0; i < AbstractTypeUsers.size(); ) {
878 AbstractTypeUser *ATU = AbstractTypeUsers[i];
879 #ifdef DEBUG_MERGE_TYPES
880 cerr << " typeIsREFINED user " << i << " of abstract type ["
881 << (void*)this << " " << getDescription() << "]\n";
883 ATU->refineAbstractType(this, this);
885 // If the user didn't remove itself from the list, continue...
886 if (AbstractTypeUsers.size() > i && AbstractTypeUsers[i] == ATU) {
894 if (!(isAbstract() || AbstractTypeUsers.empty()))
895 for (unsigned i = 0; i < AbstractTypeUsers.size(); ++i) {
896 if (AbstractTypeUsers[i] != this) {
898 cerr << "FOUND FAILURE\n";
899 AbstractTypeUsers[i]->refineAbstractType(this, this);
900 assert(0 && "Type became concrete,"
901 " but it still has abstract type users hanging around!");
910 // refineAbstractType - Called when a contained type is found to be more
911 // concrete - this could potentially change us from an abstract type to a
914 void FunctionType::refineAbstractType(const DerivedType *OldType,
915 const Type *NewType) {
916 #ifdef DEBUG_MERGE_TYPES
917 cerr << "FunctionTy::refineAbstractTy(" << (void*)OldType << "["
918 << OldType->getDescription() << "], " << (void*)NewType << " ["
919 << NewType->getDescription() << "])\n";
922 if (!OldType->isAbstract()) {
923 if (ResultType == OldType) ResultType.removeUserFromConcrete();
924 for (unsigned i = 0; i < ParamTys.size(); ++i)
925 if (ParamTys[i] == OldType) ParamTys[i].removeUserFromConcrete();
928 if (OldType != NewType) {
929 if (ResultType == OldType) ResultType = NewType;
931 for (unsigned i = 0; i < ParamTys.size(); ++i)
932 if (ParamTys[i] == OldType) ParamTys[i] = NewType;
935 const FunctionType *MT = FunctionTypes.containsEquivalent(this);
936 if (MT && MT != this) {
937 refineAbstractTypeTo(MT); // Different type altogether...
939 setDerivedTypeProperties(); // Update the name and isAbstract
940 typeIsRefined(); // Same type, different contents...
945 // refineAbstractType - Called when a contained type is found to be more
946 // concrete - this could potentially change us from an abstract type to a
949 void ArrayType::refineAbstractType(const DerivedType *OldType,
950 const Type *NewType) {
951 #ifdef DEBUG_MERGE_TYPES
952 cerr << "ArrayTy::refineAbstractTy(" << (void*)OldType << "["
953 << OldType->getDescription() << "], " << (void*)NewType << " ["
954 << NewType->getDescription() << "])\n";
957 if (!OldType->isAbstract()) {
958 assert(getElementType() == OldType);
959 ElementType.removeUserFromConcrete();
962 ElementType = NewType;
963 const ArrayType *AT = ArrayTypes.containsEquivalent(this);
964 if (AT && AT != this) {
965 refineAbstractTypeTo(AT); // Different type altogether...
967 setDerivedTypeProperties(); // Update the name and isAbstract
968 typeIsRefined(); // Same type, different contents...
973 // refineAbstractType - Called when a contained type is found to be more
974 // concrete - this could potentially change us from an abstract type to a
977 void StructType::refineAbstractType(const DerivedType *OldType,
978 const Type *NewType) {
979 #ifdef DEBUG_MERGE_TYPES
980 cerr << "StructTy::refineAbstractTy(" << (void*)OldType << "["
981 << OldType->getDescription() << "], " << (void*)NewType << " ["
982 << NewType->getDescription() << "])\n";
984 if (!OldType->isAbstract()) {
985 for (unsigned i = 0; i < ETypes.size(); ++i)
986 if (ETypes[i] == OldType)
987 ETypes[i].removeUserFromConcrete();
990 if (OldType != NewType) {
991 // Update old type to new type in the array...
992 for (unsigned i = 0; i < ETypes.size(); ++i)
993 if (ETypes[i] == OldType)
997 const StructType *ST = StructTypes.containsEquivalent(this);
998 if (ST && ST != this) {
999 refineAbstractTypeTo(ST); // Different type altogether...
1001 setDerivedTypeProperties(); // Update the name and isAbstract
1002 typeIsRefined(); // Same type, different contents...
1006 // refineAbstractType - Called when a contained type is found to be more
1007 // concrete - this could potentially change us from an abstract type to a
1010 void PointerType::refineAbstractType(const DerivedType *OldType,
1011 const Type *NewType) {
1012 #ifdef DEBUG_MERGE_TYPES
1013 cerr << "PointerTy::refineAbstractTy(" << (void*)OldType << "["
1014 << OldType->getDescription() << "], " << (void*)NewType << " ["
1015 << NewType->getDescription() << "])\n";
1018 if (!OldType->isAbstract()) {
1019 assert(ElementType == OldType);
1020 ElementType.removeUserFromConcrete();
1023 ElementType = NewType;
1024 const PointerType *PT = PointerTypes.containsEquivalent(this);
1026 if (PT && PT != this) {
1027 refineAbstractTypeTo(PT); // Different type altogether...
1029 setDerivedTypeProperties(); // Update the name and isAbstract
1030 typeIsRefined(); // Same type, different contents...