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 MethodType::MethodType(const Type *Result, const vector<const Type*> &Params,
198 bool IsVarArgs) : DerivedType(MethodTyID),
199 ResultType(PATypeHandle<Type>(Result, this)),
200 isVarArgs(IsVarArgs) {
201 ParamTys.reserve(Params.size());
202 for (unsigned i = 0; i < Params.size(); ++i)
203 ParamTys.push_back(PATypeHandle<Type>(Params[i], this));
205 setDerivedTypeProperties();
208 StructType::StructType(const vector<const Type*> &Types)
209 : CompositeType(StructTyID) {
210 ETypes.reserve(Types.size());
211 for (unsigned i = 0; i < Types.size(); ++i) {
212 assert(Types[i] != Type::VoidTy && "Void type in method prototype!!");
213 ETypes.push_back(PATypeHandle<Type>(Types[i], this));
215 setDerivedTypeProperties();
218 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
219 : SequentialType(ArrayTyID, ElType) {
221 setDerivedTypeProperties();
224 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
225 setDerivedTypeProperties();
228 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
230 setDescription("opaque"+utostr(getUniqueID()));
231 #ifdef DEBUG_MERGE_TYPES
232 cerr << "Derived new type: " << getDescription() << endl;
239 //===----------------------------------------------------------------------===//
240 // Derived Type setDerivedTypeProperties Function
241 //===----------------------------------------------------------------------===//
243 // getTypeProps - This is a recursive function that walks a type hierarchy
244 // calculating the description for a type and whether or not it is abstract or
245 // recursive. Worst case it will have to do a lot of traversing if you have
246 // some whacko opaque types, but in most cases, it will do some simple stuff
247 // when it hits non-abstract types that aren't recursive.
249 static string getTypeProps(const Type *Ty, vector<const Type *> &TypeStack,
250 bool &isAbstract, bool &isRecursive) {
252 if (!Ty->isAbstract() && !Ty->isRecursive() && // Base case for the recursion
253 Ty->getDescription().size()) {
254 Result = Ty->getDescription(); // Primitive = leaf type
255 } else if (isa<OpaqueType>(Ty)) { // Base case for the recursion
256 Result = Ty->getDescription(); // Opaque = leaf type
257 isAbstract = true; // This whole type is abstract!
259 // Check to see if the Type is already on the stack...
260 unsigned Slot = 0, CurSize = TypeStack.size();
261 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
263 // This is another base case for the recursion. In this case, we know
264 // that we have looped back to a type that we have previously visited.
265 // Generate the appropriate upreference to handle this.
267 if (Slot < CurSize) {
268 Result = "\\" + utostr(CurSize-Slot); // Here's the upreference
269 isRecursive = true; // We know we are recursive
270 } else { // Recursive case: abstract derived type...
271 TypeStack.push_back(Ty); // Add us to the stack..
273 switch (Ty->getPrimitiveID()) {
274 case Type::MethodTyID: {
275 const MethodType *MTy = cast<const MethodType>(Ty);
276 Result = getTypeProps(MTy->getReturnType(), TypeStack,
277 isAbstract, isRecursive)+" (";
278 for (MethodType::ParamTypes::const_iterator
279 I = MTy->getParamTypes().begin(),
280 E = MTy->getParamTypes().end(); I != E; ++I) {
281 if (I != MTy->getParamTypes().begin())
283 Result += getTypeProps(*I, TypeStack, isAbstract, isRecursive);
285 if (MTy->isVarArg()) {
286 if (!MTy->getParamTypes().empty()) Result += ", ";
292 case Type::StructTyID: {
293 const StructType *STy = cast<const StructType>(Ty);
295 for (StructType::ElementTypes::const_iterator
296 I = STy->getElementTypes().begin(),
297 E = STy->getElementTypes().end(); I != E; ++I) {
298 if (I != STy->getElementTypes().begin())
300 Result += getTypeProps(*I, TypeStack, isAbstract, isRecursive);
305 case Type::PointerTyID: {
306 const PointerType *PTy = cast<const PointerType>(Ty);
307 Result = getTypeProps(PTy->getElementType(), TypeStack,
308 isAbstract, isRecursive) + " *";
311 case Type::ArrayTyID: {
312 const ArrayType *ATy = cast<const ArrayType>(Ty);
313 unsigned NumElements = ATy->getNumElements();
315 Result += utostr(NumElements) + " x ";
316 Result += getTypeProps(ATy->getElementType(), TypeStack,
317 isAbstract, isRecursive) + "]";
321 assert(0 && "Unhandled case in getTypeProps!");
325 TypeStack.pop_back(); // Remove self from stack...
332 // setDerivedTypeProperties - This function is used to calculate the
333 // isAbstract, isRecursive, and the Description settings for a type. The
334 // getTypeProps function does all the dirty work.
336 void DerivedType::setDerivedTypeProperties() {
337 vector<const Type *> TypeStack;
338 bool isAbstract = false, isRecursive = false;
340 setDescription(getTypeProps(this, TypeStack, isAbstract, isRecursive));
341 setAbstract(isAbstract);
342 setRecursive(isRecursive);
346 //===----------------------------------------------------------------------===//
347 // Type Structural Equality Testing
348 //===----------------------------------------------------------------------===//
350 // TypesEqual - Two types are considered structurally equal if they have the
351 // same "shape": Every level and element of the types have identical primitive
352 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
353 // be pointer equals to be equivalent though. This uses an optimistic algorithm
354 // that assumes that two graphs are the same until proven otherwise.
356 static bool TypesEqual(const Type *Ty, const Type *Ty2,
357 map<const Type *, const Type *> &EqTypes) {
358 if (Ty == Ty2) return true;
359 if (Ty->getPrimitiveID() != Ty2->getPrimitiveID()) return false;
360 if (Ty->isPrimitiveType()) return true;
361 if (isa<OpaqueType>(Ty))
362 return false; // Two nonequal opaque types are never equal
364 map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
365 if (It != EqTypes.end())
366 return It->second == Ty2; // Looping back on a type, check for equality
368 // Otherwise, add the mapping to the table to make sure we don't get
369 // recursion on the types...
370 EqTypes.insert(make_pair(Ty, Ty2));
372 // Iterate over the types and make sure the the contents are equivalent...
373 Type::subtype_iterator I = Ty ->subtype_begin(), IE = Ty ->subtype_end();
374 Type::subtype_iterator I2 = Ty2->subtype_begin(), IE2 = Ty2->subtype_end();
375 for (; I != IE && I2 != IE2; ++I, ++I2)
376 if (!TypesEqual(*I, *I2, EqTypes)) return false;
378 // Two really annoying special cases that breaks an otherwise nice simple
379 // algorithm is the fact that arraytypes have sizes that differentiates types,
380 // and that method types can be varargs or not. Consider this now.
381 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
382 if (ATy->getNumElements() != cast<const ArrayType>(Ty2)->getNumElements())
384 } else if (const MethodType *MTy = dyn_cast<MethodType>(Ty)) {
385 if (MTy->isVarArg() != cast<const MethodType>(Ty2)->isVarArg())
389 return I == IE && I2 == IE2; // Types equal if both iterators are done
392 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
393 map<const Type *, const Type *> EqTypes;
394 return TypesEqual(Ty, Ty2, EqTypes);
399 //===----------------------------------------------------------------------===//
400 // Derived Type Factory Functions
401 //===----------------------------------------------------------------------===//
403 // TypeMap - Make sure that only one instance of a particular type may be
404 // created on any given run of the compiler... note that this involves updating
405 // our map if an abstract type gets refined somehow...
407 template<class ValType, class TypeClass>
408 class TypeMap : public AbstractTypeUser {
409 typedef map<ValType, PATypeHandle<TypeClass> > MapTy;
413 ~TypeMap() { print("ON EXIT"); }
415 inline TypeClass *get(const ValType &V) {
416 map<ValType, PATypeHandle<TypeClass> >::iterator I = Map.find(V);
417 // TODO: FIXME: When Types are not CONST.
418 return (I != Map.end()) ? (TypeClass*)I->second.get() : 0;
421 inline void add(const ValType &V, TypeClass *T) {
422 Map.insert(make_pair(V, PATypeHandle<TypeClass>(T, this)));
426 // containsEquivalent - Return true if the typemap contains a type that is
427 // structurally equivalent to the specified type.
429 inline const TypeClass *containsEquivalent(const TypeClass *Ty) {
430 for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
431 if (I->second.get() != Ty && TypesEqual(Ty, I->second.get()))
432 return (TypeClass*)I->second.get(); // FIXME TODO when types not const
436 // refineAbstractType - This is called when one of the contained abstract
437 // types gets refined... this simply removes the abstract type from our table.
438 // We expect that whoever refined the type will add it back to the table,
441 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
442 if (OldTy == NewTy) {
443 if (!OldTy->isAbstract()) {
444 // Check to see if the type just became concrete.
445 // If so, remove self from user list.
446 for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
447 if (I->second == OldTy)
448 I->second.removeUserFromConcrete();
452 #ifdef DEBUG_MERGE_TYPES
453 cerr << "Removing Old type from Tab: " << (void*)OldTy << ", "
454 << OldTy->getDescription() << " replacement == " << (void*)NewTy
455 << ", " << NewTy->getDescription() << endl;
457 for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
458 if (I->second == OldTy) {
460 print("refineAbstractType after");
463 assert(0 && "Abstract type not found in table!");
466 void remove(const ValType &OldVal) {
467 MapTy::iterator I = Map.find(OldVal);
468 assert(I != Map.end() && "TypeMap::remove, element not found!");
472 void print(const char *Arg) {
473 #ifdef DEBUG_MERGE_TYPES
474 cerr << "TypeMap<>::" << Arg << " table contents:\n";
476 for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
477 cerr << " " << (++i) << ". " << I->second << " "
478 << I->second->getDescription() << endl;
484 // ValTypeBase - This is the base class that is used by the various
485 // instantiations of TypeMap. This class is an AbstractType user that notifies
486 // the underlying TypeMap when it gets modified.
488 template<class ValType, class TypeClass>
489 class ValTypeBase : public AbstractTypeUser {
490 TypeMap<ValType, TypeClass> &MyTable;
492 inline ValTypeBase(TypeMap<ValType, TypeClass> &tab) : MyTable(tab) {}
494 // Subclass should override this... to update self as usual
495 virtual void doRefinement(const DerivedType *OldTy, const Type *NewTy) = 0;
497 // typeBecameConcrete - This callback occurs when a contained type refines
498 // to itself, but becomes concrete in the process. Our subclass should remove
499 // itself from the ATU list of the specified type.
501 virtual void typeBecameConcrete(const DerivedType *Ty) = 0;
503 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
504 if (OldTy == NewTy) {
505 if (!OldTy->isAbstract())
506 typeBecameConcrete(OldTy);
509 TypeMap<ValType, TypeClass> &Table = MyTable; // Copy MyTable reference
510 ValType Tmp(*(ValType*)this); // Copy this.
511 PATypeHandle<TypeClass> OldType(Table.get(*(ValType*)this), this);
512 Table.remove(*(ValType*)this); // Destroy's this!
514 // Refine temporary to new state...
515 Tmp.doRefinement(OldTy, NewTy);
517 Table.add((ValType&)Tmp, (TypeClass*)OldType.get());
524 //===----------------------------------------------------------------------===//
525 // Method Type Factory and Value Class...
528 // MethodValType - Define a class to hold the key that goes into the TypeMap
530 class MethodValType : public ValTypeBase<MethodValType, MethodType> {
531 PATypeHandle<Type> RetTy;
532 vector<PATypeHandle<Type> > ArgTypes;
535 MethodValType(const Type *ret, const vector<const Type*> &args,
536 bool IVA, TypeMap<MethodValType, MethodType> &Tab)
537 : ValTypeBase<MethodValType, MethodType>(Tab), RetTy(ret, this),
539 for (unsigned i = 0; i < args.size(); ++i)
540 ArgTypes.push_back(PATypeHandle<Type>(args[i], this));
543 // We *MUST* have an explicit copy ctor so that the TypeHandles think that
544 // this MethodValType owns them, not the old one!
546 MethodValType(const MethodValType &MVT)
547 : ValTypeBase<MethodValType, MethodType>(MVT), RetTy(MVT.RetTy, this),
548 isVarArg(MVT.isVarArg) {
549 ArgTypes.reserve(MVT.ArgTypes.size());
550 for (unsigned i = 0; i < MVT.ArgTypes.size(); ++i)
551 ArgTypes.push_back(PATypeHandle<Type>(MVT.ArgTypes[i], this));
554 // Subclass should override this... to update self as usual
555 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
556 if (RetTy == OldType) RetTy = NewType;
557 for (unsigned i = 0; i < ArgTypes.size(); ++i)
558 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
561 virtual void typeBecameConcrete(const DerivedType *Ty) {
562 if (RetTy == Ty) RetTy.removeUserFromConcrete();
564 for (unsigned i = 0; i < ArgTypes.size(); ++i)
565 if (ArgTypes[i] == Ty) ArgTypes[i].removeUserFromConcrete();
568 inline bool operator<(const MethodValType &MTV) const {
569 if (RetTy.get() < MTV.RetTy.get()) return true;
570 if (RetTy.get() > MTV.RetTy.get()) return false;
572 if (ArgTypes < MTV.ArgTypes) return true;
573 return (ArgTypes == MTV.ArgTypes) && isVarArg < MTV.isVarArg;
577 // Define the actual map itself now...
578 static TypeMap<MethodValType, MethodType> MethodTypes;
580 // MethodType::get - The factory function for the MethodType class...
581 MethodType *MethodType::get(const Type *ReturnType,
582 const vector<const Type*> &Params,
584 MethodValType VT(ReturnType, Params, isVarArg, MethodTypes);
585 MethodType *MT = MethodTypes.get(VT);
588 MethodTypes.add(VT, MT = new MethodType(ReturnType, Params, isVarArg));
590 #ifdef DEBUG_MERGE_TYPES
591 cerr << "Derived new type: " << MT << endl;
596 //===----------------------------------------------------------------------===//
597 // Array Type Factory...
599 class ArrayValType : public ValTypeBase<ArrayValType, ArrayType> {
600 PATypeHandle<Type> ValTy;
603 ArrayValType(const Type *val, int sz, TypeMap<ArrayValType, ArrayType> &Tab)
604 : ValTypeBase<ArrayValType, ArrayType>(Tab), ValTy(val, this), Size(sz) {}
606 // We *MUST* have an explicit copy ctor so that the ValTy thinks that this
607 // ArrayValType owns it, not the old one!
609 ArrayValType(const ArrayValType &AVT)
610 : ValTypeBase<ArrayValType, ArrayType>(AVT), ValTy(AVT.ValTy, this),
613 // Subclass should override this... to update self as usual
614 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
615 if (ValTy == OldType) ValTy = NewType;
618 virtual void typeBecameConcrete(const DerivedType *Ty) {
619 assert(ValTy == Ty &&
620 "Contained type became concrete but we're not using it!");
621 ValTy.removeUserFromConcrete();
624 inline bool operator<(const ArrayValType &MTV) const {
625 if (Size < MTV.Size) return true;
626 return Size == MTV.Size && ValTy.get() < MTV.ValTy.get();
630 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
632 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
633 assert(ElementType && "Can't get array of null types!");
635 ArrayValType AVT(ElementType, NumElements, ArrayTypes);
636 ArrayType *AT = ArrayTypes.get(AVT);
637 if (AT) return AT; // Found a match, return it!
639 // Value not found. Derive a new type!
640 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
642 #ifdef DEBUG_MERGE_TYPES
643 cerr << "Derived new type: " << AT->getDescription() << endl;
648 //===----------------------------------------------------------------------===//
649 // Struct Type Factory...
652 // StructValType - Define a class to hold the key that goes into the TypeMap
654 class StructValType : public ValTypeBase<StructValType, StructType> {
655 vector<PATypeHandle<Type> > ElTypes;
657 StructValType(const vector<const Type*> &args,
658 TypeMap<StructValType, StructType> &Tab)
659 : ValTypeBase<StructValType, StructType>(Tab) {
660 for (unsigned i = 0; i < args.size(); ++i)
661 ElTypes.push_back(PATypeHandle<Type>(args[i], this));
664 // We *MUST* have an explicit copy ctor so that the TypeHandles think that
665 // this StructValType owns them, not the old one!
667 StructValType(const StructValType &SVT)
668 : ValTypeBase<StructValType, StructType>(SVT){
669 ElTypes.reserve(SVT.ElTypes.size());
670 for (unsigned i = 0; i < SVT.ElTypes.size(); ++i)
671 ElTypes.push_back(PATypeHandle<Type>(SVT.ElTypes[i], this));
674 // Subclass should override this... to update self as usual
675 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
676 for (unsigned i = 0; i < ElTypes.size(); ++i)
677 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
680 virtual void typeBecameConcrete(const DerivedType *Ty) {
681 for (unsigned i = 0; i < ElTypes.size(); ++i)
682 if (ElTypes[i] == Ty) ElTypes[i].removeUserFromConcrete();
685 inline bool operator<(const StructValType &STV) const {
686 return ElTypes < STV.ElTypes;
690 static TypeMap<StructValType, StructType> StructTypes;
692 StructType *StructType::get(const vector<const Type*> &ETypes) {
693 StructValType STV(ETypes, StructTypes);
694 StructType *ST = StructTypes.get(STV);
697 // Value not found. Derive a new type!
698 StructTypes.add(STV, ST = new StructType(ETypes));
700 #ifdef DEBUG_MERGE_TYPES
701 cerr << "Derived new type: " << ST->getDescription() << endl;
706 //===----------------------------------------------------------------------===//
707 // Pointer Type Factory...
710 // PointerValType - Define a class to hold the key that goes into the TypeMap
712 class PointerValType : public ValTypeBase<PointerValType, PointerType> {
713 PATypeHandle<Type> ValTy;
715 PointerValType(const Type *val, TypeMap<PointerValType, PointerType> &Tab)
716 : ValTypeBase<PointerValType, PointerType>(Tab), ValTy(val, this) {}
718 // We *MUST* have an explicit copy ctor so that the ValTy thinks that this
719 // PointerValType owns it, not the old one!
721 PointerValType(const PointerValType &PVT)
722 : ValTypeBase<PointerValType, PointerType>(PVT), ValTy(PVT.ValTy, this) {}
724 // Subclass should override this... to update self as usual
725 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
726 if (ValTy == OldType) ValTy = NewType;
729 virtual void typeBecameConcrete(const DerivedType *Ty) {
730 assert(ValTy == Ty &&
731 "Contained type became concrete but we're not using it!");
732 ValTy.removeUserFromConcrete();
735 inline bool operator<(const PointerValType &MTV) const {
736 return ValTy.get() < MTV.ValTy.get();
740 static TypeMap<PointerValType, PointerType> PointerTypes;
742 PointerType *PointerType::get(const Type *ValueType) {
743 assert(ValueType && "Can't get a pointer to <null> type!");
744 PointerValType PVT(ValueType, PointerTypes);
746 PointerType *PT = PointerTypes.get(PVT);
749 // Value not found. Derive a new type!
750 PointerTypes.add(PVT, PT = new PointerType(ValueType));
752 #ifdef DEBUG_MERGE_TYPES
753 cerr << "Derived new type: " << PT->getDescription() << endl;
760 //===----------------------------------------------------------------------===//
761 // Derived Type Refinement Functions
762 //===----------------------------------------------------------------------===//
764 // removeAbstractTypeUser - Notify an abstract type that a user of the class
765 // no longer has a handle to the type. This function is called primarily by
766 // the PATypeHandle class. When there are no users of the abstract type, it
767 // is anihilated, because there is no way to get a reference to it ever again.
769 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
770 // Search from back to front because we will notify users from back to
771 // front. Also, it is likely that there will be a stack like behavior to
772 // users that register and unregister users.
774 for (unsigned i = AbstractTypeUsers.size(); i > 0; --i) {
775 if (AbstractTypeUsers[i-1] == U) {
776 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i-1);
778 #ifdef DEBUG_MERGE_TYPES
779 cerr << " removeAbstractTypeUser<" << (void*)this << ", "
780 << getDescription() << ">[" << i << "] User = " << U << endl;
783 if (AbstractTypeUsers.empty() && isAbstract()) {
784 #ifdef DEBUG_MERGE_TYPES
785 cerr << "DELETEing unused abstract type: <" << getDescription()
786 << ">[" << (void*)this << "]" << endl;
788 delete this; // No users of this abstract type!
793 assert(0 && "AbstractTypeUser not in user list!");
797 // refineAbstractTypeTo - This function is used to when it is discovered that
798 // the 'this' abstract type is actually equivalent to the NewType specified.
799 // This causes all users of 'this' to switch to reference the more concrete
800 // type NewType and for 'this' to be deleted.
802 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
803 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
804 assert(this != NewType && "Can't refine to myself!");
806 #ifdef DEBUG_MERGE_TYPES
807 cerr << "REFINING abstract type [" << (void*)this << " " << getDescription()
808 << "] to [" << (void*)NewType << " " << NewType->getDescription()
813 // Make sure to put the type to be refined to into a holder so that if IT gets
814 // refined, that we will not continue using a dead reference...
816 PATypeHolder<Type> NewTy(NewType);
818 // Add a self use of the current type so that we don't delete ourself until
819 // after this while loop. We are careful to never invoke refine on ourself,
820 // so this extra reference shouldn't be a problem. Note that we must only
821 // remove a single reference at the end, but we must tolerate multiple self
822 // references because we could be refineAbstractTypeTo'ing recursively on the
825 addAbstractTypeUser(this);
827 // Count the number of self uses. Stop looping when sizeof(list) == NSU.
828 unsigned NumSelfUses = 0;
830 // Iterate over all of the uses of this type, invoking callback. Each user
831 // should remove itself from our use list automatically.
833 while (AbstractTypeUsers.size() > NumSelfUses) {
834 AbstractTypeUser *User = AbstractTypeUsers.back();
837 // Move self use to the start of the list. Increment NSU.
838 swap(AbstractTypeUsers.back(), AbstractTypeUsers[NumSelfUses++]);
840 unsigned OldSize = AbstractTypeUsers.size();
841 #ifdef DEBUG_MERGE_TYPES
842 cerr << " REFINING user " << OldSize-1 << " of abstract type ["
843 << (void*)this << " " << getDescription() << "] to ["
844 << (void*)NewTy.get() << " " << NewTy->getDescription() << "]!\n";
846 User->refineAbstractType(this, NewTy);
848 if (AbstractTypeUsers.size() == OldSize) {
849 User->refineAbstractType(this, NewTy);
851 assert(AbstractTypeUsers.size() != OldSize &&
852 "AbsTyUser did not remove self from user list!");
856 // Remove a single self use, even though there may be several here. This will
857 // probably 'delete this', so no instance variables may be used after this
859 assert(AbstractTypeUsers.back() == this && "Only self uses should be left!");
860 removeAbstractTypeUser(this);
864 // typeIsRefined - Notify AbstractTypeUsers of this type that the current type
865 // has been refined a bit. The pointer is still valid and still should be
866 // used, but the subtypes have changed.
868 void DerivedType::typeIsRefined() {
869 assert(isRefining >= 0 && isRefining <= 2 && "isRefining out of bounds!");
870 if (isRefining == 1) return; // Kill recursion here...
873 #ifdef DEBUG_MERGE_TYPES
874 cerr << "typeIsREFINED type: " << (void*)this <<" "<<getDescription() << endl;
876 for (unsigned i = 0; i < AbstractTypeUsers.size(); ) {
877 AbstractTypeUser *ATU = AbstractTypeUsers[i];
878 #ifdef DEBUG_MERGE_TYPES
879 cerr << " typeIsREFINED user " << i << " of abstract type ["
880 << (void*)this << " " << getDescription() << "]\n";
882 ATU->refineAbstractType(this, this);
884 // If the user didn't remove itself from the list, continue...
885 if (AbstractTypeUsers.size() > i && AbstractTypeUsers[i] == ATU) {
893 if (!(isAbstract() || AbstractTypeUsers.empty()))
894 for (unsigned i = 0; i < AbstractTypeUsers.size(); ++i) {
895 if (AbstractTypeUsers[i] != this) {
897 cerr << "FOUND FAILURE\n";
898 AbstractTypeUsers[i]->refineAbstractType(this, this);
899 assert(0 && "Type became concrete,"
900 " but it still has abstract type users hanging around!");
909 // refineAbstractType - Called when a contained type is found to be more
910 // concrete - this could potentially change us from an abstract type to a
913 void MethodType::refineAbstractType(const DerivedType *OldType,
914 const Type *NewType) {
915 #ifdef DEBUG_MERGE_TYPES
916 cerr << "MethodTy::refineAbstractTy(" << (void*)OldType << "["
917 << OldType->getDescription() << "], " << (void*)NewType << " ["
918 << NewType->getDescription() << "])\n";
921 if (!OldType->isAbstract()) {
922 if (ResultType == OldType) ResultType.removeUserFromConcrete();
923 for (unsigned i = 0; i < ParamTys.size(); ++i)
924 if (ParamTys[i] == OldType) ParamTys[i].removeUserFromConcrete();
927 if (OldType != NewType) {
928 if (ResultType == OldType) ResultType = NewType;
930 for (unsigned i = 0; i < ParamTys.size(); ++i)
931 if (ParamTys[i] == OldType) ParamTys[i] = NewType;
934 const MethodType *MT = MethodTypes.containsEquivalent(this);
935 if (MT && MT != this) {
936 refineAbstractTypeTo(MT); // Different type altogether...
938 setDerivedTypeProperties(); // Update the name and isAbstract
939 typeIsRefined(); // Same type, different contents...
944 // refineAbstractType - Called when a contained type is found to be more
945 // concrete - this could potentially change us from an abstract type to a
948 void ArrayType::refineAbstractType(const DerivedType *OldType,
949 const Type *NewType) {
950 #ifdef DEBUG_MERGE_TYPES
951 cerr << "ArrayTy::refineAbstractTy(" << (void*)OldType << "["
952 << OldType->getDescription() << "], " << (void*)NewType << " ["
953 << NewType->getDescription() << "])\n";
956 if (!OldType->isAbstract()) {
957 assert(getElementType() == OldType);
958 ElementType.removeUserFromConcrete();
961 ElementType = NewType;
962 const ArrayType *AT = ArrayTypes.containsEquivalent(this);
963 if (AT && AT != this) {
964 refineAbstractTypeTo(AT); // Different type altogether...
966 setDerivedTypeProperties(); // Update the name and isAbstract
967 typeIsRefined(); // Same type, different contents...
972 // refineAbstractType - Called when a contained type is found to be more
973 // concrete - this could potentially change us from an abstract type to a
976 void StructType::refineAbstractType(const DerivedType *OldType,
977 const Type *NewType) {
978 #ifdef DEBUG_MERGE_TYPES
979 cerr << "StructTy::refineAbstractTy(" << (void*)OldType << "["
980 << OldType->getDescription() << "], " << (void*)NewType << " ["
981 << NewType->getDescription() << "])\n";
983 if (!OldType->isAbstract()) {
984 for (unsigned i = 0; i < ETypes.size(); ++i)
985 if (ETypes[i] == OldType)
986 ETypes[i].removeUserFromConcrete();
989 if (OldType != NewType) {
990 // Update old type to new type in the array...
991 for (unsigned i = 0; i < ETypes.size(); ++i)
992 if (ETypes[i] == OldType)
996 const StructType *ST = StructTypes.containsEquivalent(this);
997 if (ST && ST != this) {
998 refineAbstractTypeTo(ST); // Different type altogether...
1000 setDerivedTypeProperties(); // Update the name and isAbstract
1001 typeIsRefined(); // Same type, different contents...
1005 // refineAbstractType - Called when a contained type is found to be more
1006 // concrete - this could potentially change us from an abstract type to a
1009 void PointerType::refineAbstractType(const DerivedType *OldType,
1010 const Type *NewType) {
1011 #ifdef DEBUG_MERGE_TYPES
1012 cerr << "PointerTy::refineAbstractTy(" << (void*)OldType << "["
1013 << OldType->getDescription() << "], " << (void*)NewType << " ["
1014 << NewType->getDescription() << "])\n";
1017 if (!OldType->isAbstract()) {
1018 assert(ElementType == OldType);
1019 ElementType.removeUserFromConcrete();
1022 ElementType = NewType;
1023 const PointerType *PT = PointerTypes.containsEquivalent(this);
1025 if (PT && PT != this) {
1026 refineAbstractTypeTo(PT); // Different type altogether...
1028 setDerivedTypeProperties(); // Update the name and isAbstract
1029 typeIsRefined(); // Same type, different contents...