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 void PATypeHolder::dump() const {
36 cerr << "PATypeHolder(" << (void*)this << ")\n";
39 Type::Type(const string &name, PrimitiveID id)
40 : Value(Type::TypeTy, Value::TypeVal) {
43 Abstract = Recursive = false;
44 UID = CurUID++; // Assign types UID's as they are created
45 UIDMappings.push_back(this);
48 void Type::setName(const string &Name, SymbolTable *ST) {
49 assert(ST && "Type::setName - Must provide symbol table argument!");
51 if (Name.size()) ST->insert(Name, this);
55 const Type *Type::getUniqueIDType(unsigned UID) {
56 assert(UID < UIDMappings.size() &&
57 "Type::getPrimitiveType: UID out of range!");
58 return UIDMappings[UID];
61 const Type *Type::getPrimitiveType(PrimitiveID IDNumber) {
63 case VoidTyID : return VoidTy;
64 case BoolTyID : return BoolTy;
65 case UByteTyID : return UByteTy;
66 case SByteTyID : return SByteTy;
67 case UShortTyID: return UShortTy;
68 case ShortTyID : return ShortTy;
69 case UIntTyID : return UIntTy;
70 case IntTyID : return IntTy;
71 case ULongTyID : return ULongTy;
72 case LongTyID : return LongTy;
73 case FloatTyID : return FloatTy;
74 case DoubleTyID: return DoubleTy;
75 case TypeTyID : return TypeTy;
76 case LabelTyID : return LabelTy;
82 // isLosslesslyConvertableTo - Return true if this type can be converted to
83 // 'Ty' without any reinterpretation of bits. For example, uint to int.
85 bool Type::isLosslesslyConvertableTo(const Type *Ty) const {
86 if (this == Ty) return true;
87 if ((!isPrimitiveType() && !isPointerType()) ||
88 (!Ty->isPointerType() && !Ty->isPrimitiveType())) return false;
90 if (getPrimitiveID() == Ty->getPrimitiveID())
91 return true; // Handles identity cast, and cast of differing pointer types
93 // Now we know that they are two differing primitive or pointer types
94 switch (getPrimitiveID()) {
95 case Type::UByteTyID: return Ty == Type::SByteTy;
96 case Type::SByteTyID: return Ty == Type::UByteTy;
97 case Type::UShortTyID: return Ty == Type::ShortTy;
98 case Type::ShortTyID: return Ty == Type::UShortTy;
99 case Type::UIntTyID: return Ty == Type::IntTy;
100 case Type::IntTyID: return Ty == Type::UIntTy;
101 case Type::ULongTyID:
103 case Type::PointerTyID:
104 return Ty == Type::ULongTy || Ty == Type::LongTy ||
105 Ty->getPrimitiveID() == Type::PointerTyID;
107 return false; // Other types have no identity values
112 bool StructType::indexValid(const Value *V) const {
113 if (!isa<Constant>(V)) return false;
114 if (V->getType() != Type::UByteTy) return false;
115 unsigned Idx = cast<ConstantUInt>(V)->getValue();
116 return Idx < ETypes.size();
119 // getTypeAtIndex - Given an index value into the type, return the type of the
120 // element. For a structure type, this must be a constant value...
122 const Type *StructType::getTypeAtIndex(const Value *V) const {
123 assert(isa<Constant>(V) && "Structure index must be a constant!!");
124 assert(V->getType() == Type::UByteTy && "Structure index must be ubyte!");
125 unsigned Idx = cast<ConstantUInt>(V)->getValue();
126 assert(Idx < ETypes.size() && "Structure index out of range!");
127 assert(indexValid(V) && "Invalid structure index!"); // Duplicate check
133 //===----------------------------------------------------------------------===//
134 // Auxilliary classes
135 //===----------------------------------------------------------------------===//
137 // These classes are used to implement specialized behavior for each different
140 class SignedIntType : public Type {
143 SignedIntType(const string &Name, PrimitiveID id, int size) : Type(Name, id) {
147 // isSigned - Return whether a numeric type is signed.
148 virtual bool isSigned() const { return 1; }
150 // isIntegral - Equivalent to isSigned() || isUnsigned, but with only a single
151 // virtual function invocation.
153 virtual bool isIntegral() const { return 1; }
156 class UnsignedIntType : public Type {
159 UnsignedIntType(const string &N, PrimitiveID id, int size) : Type(N, id) {
163 // isUnsigned - Return whether a numeric type is signed.
164 virtual bool isUnsigned() const { return 1; }
166 // isIntegral - Equivalent to isSigned() || isUnsigned, but with only a single
167 // virtual function invocation.
169 virtual bool isIntegral() const { return 1; }
172 static struct TypeType : public Type {
173 TypeType() : Type("type", TypeTyID) {}
174 } TheTypeType; // Implement the type that is global.
177 //===----------------------------------------------------------------------===//
178 // Static 'Type' data
179 //===----------------------------------------------------------------------===//
181 Type *Type::VoidTy = new Type("void" , VoidTyID),
182 *Type::BoolTy = new Type("bool" , BoolTyID),
183 *Type::SByteTy = new SignedIntType("sbyte" , SByteTyID, 1),
184 *Type::UByteTy = new UnsignedIntType("ubyte" , UByteTyID, 1),
185 *Type::ShortTy = new SignedIntType("short" , ShortTyID, 2),
186 *Type::UShortTy = new UnsignedIntType("ushort", UShortTyID, 2),
187 *Type::IntTy = new SignedIntType("int" , IntTyID, 4),
188 *Type::UIntTy = new UnsignedIntType("uint" , UIntTyID, 4),
189 *Type::LongTy = new SignedIntType("long" , LongTyID, 8),
190 *Type::ULongTy = new UnsignedIntType("ulong" , ULongTyID, 8),
191 *Type::FloatTy = new Type("float" , FloatTyID),
192 *Type::DoubleTy = new Type("double", DoubleTyID),
193 *Type::TypeTy = &TheTypeType,
194 *Type::LabelTy = new Type("label" , LabelTyID);
197 //===----------------------------------------------------------------------===//
198 // Derived Type Constructors
199 //===----------------------------------------------------------------------===//
201 FunctionType::FunctionType(const Type *Result,
202 const vector<const Type*> &Params,
203 bool IsVarArgs) : DerivedType(FunctionTyID),
204 ResultType(PATypeHandle<Type>(Result, this)),
205 isVarArgs(IsVarArgs) {
206 ParamTys.reserve(Params.size());
207 for (unsigned i = 0; i < Params.size(); ++i)
208 ParamTys.push_back(PATypeHandle<Type>(Params[i], this));
210 setDerivedTypeProperties();
213 StructType::StructType(const vector<const Type*> &Types)
214 : CompositeType(StructTyID) {
215 ETypes.reserve(Types.size());
216 for (unsigned i = 0; i < Types.size(); ++i) {
217 assert(Types[i] != Type::VoidTy && "Void type in method prototype!!");
218 ETypes.push_back(PATypeHandle<Type>(Types[i], this));
220 setDerivedTypeProperties();
223 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
224 : SequentialType(ArrayTyID, ElType) {
226 setDerivedTypeProperties();
229 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
230 setDerivedTypeProperties();
233 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
235 setDescription("opaque"+utostr(getUniqueID()));
236 #ifdef DEBUG_MERGE_TYPES
237 cerr << "Derived new type: " << getDescription() << endl;
244 //===----------------------------------------------------------------------===//
245 // Derived Type setDerivedTypeProperties Function
246 //===----------------------------------------------------------------------===//
248 // getTypeProps - This is a recursive function that walks a type hierarchy
249 // calculating the description for a type and whether or not it is abstract or
250 // recursive. Worst case it will have to do a lot of traversing if you have
251 // some whacko opaque types, but in most cases, it will do some simple stuff
252 // when it hits non-abstract types that aren't recursive.
254 static string getTypeProps(const Type *Ty, vector<const Type *> &TypeStack,
255 bool &isAbstract, bool &isRecursive) {
257 if (!Ty->isAbstract() && !Ty->isRecursive() && // Base case for the recursion
258 Ty->getDescription().size()) {
259 Result = Ty->getDescription(); // Primitive = leaf type
260 } else if (isa<OpaqueType>(Ty)) { // Base case for the recursion
261 Result = Ty->getDescription(); // Opaque = leaf type
262 isAbstract = true; // This whole type is abstract!
264 // Check to see if the Type is already on the stack...
265 unsigned Slot = 0, CurSize = TypeStack.size();
266 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
268 // This is another base case for the recursion. In this case, we know
269 // that we have looped back to a type that we have previously visited.
270 // Generate the appropriate upreference to handle this.
272 if (Slot < CurSize) {
273 Result = "\\" + utostr(CurSize-Slot); // Here's the upreference
274 isRecursive = true; // We know we are recursive
275 } else { // Recursive case: abstract derived type...
276 TypeStack.push_back(Ty); // Add us to the stack..
278 switch (Ty->getPrimitiveID()) {
279 case Type::FunctionTyID: {
280 const FunctionType *MTy = cast<const FunctionType>(Ty);
281 Result = getTypeProps(MTy->getReturnType(), TypeStack,
282 isAbstract, isRecursive)+" (";
283 for (FunctionType::ParamTypes::const_iterator
284 I = MTy->getParamTypes().begin(),
285 E = MTy->getParamTypes().end(); I != E; ++I) {
286 if (I != MTy->getParamTypes().begin())
288 Result += getTypeProps(*I, TypeStack, isAbstract, isRecursive);
290 if (MTy->isVarArg()) {
291 if (!MTy->getParamTypes().empty()) Result += ", ";
297 case Type::StructTyID: {
298 const StructType *STy = cast<const StructType>(Ty);
300 for (StructType::ElementTypes::const_iterator
301 I = STy->getElementTypes().begin(),
302 E = STy->getElementTypes().end(); I != E; ++I) {
303 if (I != STy->getElementTypes().begin())
305 Result += getTypeProps(*I, TypeStack, isAbstract, isRecursive);
310 case Type::PointerTyID: {
311 const PointerType *PTy = cast<const PointerType>(Ty);
312 Result = getTypeProps(PTy->getElementType(), TypeStack,
313 isAbstract, isRecursive) + " *";
316 case Type::ArrayTyID: {
317 const ArrayType *ATy = cast<const ArrayType>(Ty);
318 unsigned NumElements = ATy->getNumElements();
320 Result += utostr(NumElements) + " x ";
321 Result += getTypeProps(ATy->getElementType(), TypeStack,
322 isAbstract, isRecursive) + "]";
326 assert(0 && "Unhandled case in getTypeProps!");
330 TypeStack.pop_back(); // Remove self from stack...
337 // setDerivedTypeProperties - This function is used to calculate the
338 // isAbstract, isRecursive, and the Description settings for a type. The
339 // getTypeProps function does all the dirty work.
341 void DerivedType::setDerivedTypeProperties() {
342 vector<const Type *> TypeStack;
343 bool isAbstract = false, isRecursive = false;
345 setDescription(getTypeProps(this, TypeStack, isAbstract, isRecursive));
346 setAbstract(isAbstract);
347 setRecursive(isRecursive);
351 //===----------------------------------------------------------------------===//
352 // Type Structural Equality Testing
353 //===----------------------------------------------------------------------===//
355 // TypesEqual - Two types are considered structurally equal if they have the
356 // same "shape": Every level and element of the types have identical primitive
357 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
358 // be pointer equals to be equivalent though. This uses an optimistic algorithm
359 // that assumes that two graphs are the same until proven otherwise.
361 static bool TypesEqual(const Type *Ty, const Type *Ty2,
362 map<const Type *, const Type *> &EqTypes) {
363 if (Ty == Ty2) return true;
364 if (Ty->getPrimitiveID() != Ty2->getPrimitiveID()) return false;
365 if (Ty->isPrimitiveType()) return true;
366 if (isa<OpaqueType>(Ty))
367 return false; // Two nonequal opaque types are never equal
369 map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
370 if (It != EqTypes.end())
371 return It->second == Ty2; // Looping back on a type, check for equality
373 // Otherwise, add the mapping to the table to make sure we don't get
374 // recursion on the types...
375 EqTypes.insert(make_pair(Ty, Ty2));
377 // Iterate over the types and make sure the the contents are equivalent...
378 Type::subtype_iterator I = Ty ->subtype_begin(), IE = Ty ->subtype_end();
379 Type::subtype_iterator I2 = Ty2->subtype_begin(), IE2 = Ty2->subtype_end();
380 for (; I != IE && I2 != IE2; ++I, ++I2)
381 if (!TypesEqual(*I, *I2, EqTypes)) return false;
383 // Two really annoying special cases that breaks an otherwise nice simple
384 // algorithm is the fact that arraytypes have sizes that differentiates types,
385 // and that method types can be varargs or not. Consider this now.
386 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
387 if (ATy->getNumElements() != cast<const ArrayType>(Ty2)->getNumElements())
389 } else if (const FunctionType *MTy = dyn_cast<FunctionType>(Ty)) {
390 if (MTy->isVarArg() != cast<const FunctionType>(Ty2)->isVarArg())
394 return I == IE && I2 == IE2; // Types equal if both iterators are done
397 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
398 map<const Type *, const Type *> EqTypes;
399 return TypesEqual(Ty, Ty2, EqTypes);
404 //===----------------------------------------------------------------------===//
405 // Derived Type Factory Functions
406 //===----------------------------------------------------------------------===//
408 // TypeMap - Make sure that only one instance of a particular type may be
409 // created on any given run of the compiler... note that this involves updating
410 // our map if an abstract type gets refined somehow...
412 template<class ValType, class TypeClass>
413 class TypeMap : public AbstractTypeUser {
414 typedef map<ValType, PATypeHandle<TypeClass> > MapTy;
418 ~TypeMap() { print("ON EXIT"); }
420 inline TypeClass *get(const ValType &V) {
421 map<ValType, PATypeHandle<TypeClass> >::iterator I = Map.find(V);
422 // TODO: FIXME: When Types are not CONST.
423 return (I != Map.end()) ? (TypeClass*)I->second.get() : 0;
426 inline void add(const ValType &V, TypeClass *T) {
427 Map.insert(make_pair(V, PATypeHandle<TypeClass>(T, this)));
431 // containsEquivalent - Return true if the typemap contains a type that is
432 // structurally equivalent to the specified type.
434 inline const TypeClass *containsEquivalent(const TypeClass *Ty) {
435 for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
436 if (I->second.get() != Ty && TypesEqual(Ty, I->second.get()))
437 return (TypeClass*)I->second.get(); // FIXME TODO when types not const
441 // refineAbstractType - This is called when one of the contained abstract
442 // types gets refined... this simply removes the abstract type from our table.
443 // We expect that whoever refined the type will add it back to the table,
446 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
447 if (OldTy == NewTy) {
448 if (!OldTy->isAbstract()) {
449 // Check to see if the type just became concrete.
450 // If so, remove self from user list.
451 for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
452 if (I->second == OldTy)
453 I->second.removeUserFromConcrete();
457 #ifdef DEBUG_MERGE_TYPES
458 cerr << "Removing Old type from Tab: " << (void*)OldTy << ", "
459 << OldTy->getDescription() << " replacement == " << (void*)NewTy
460 << ", " << NewTy->getDescription() << endl;
462 for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
463 if (I->second == OldTy) {
465 print("refineAbstractType after");
468 assert(0 && "Abstract type not found in table!");
471 void remove(const ValType &OldVal) {
472 MapTy::iterator I = Map.find(OldVal);
473 assert(I != Map.end() && "TypeMap::remove, element not found!");
477 void print(const char *Arg) const {
478 #ifdef DEBUG_MERGE_TYPES
479 cerr << "TypeMap<>::" << Arg << " table contents:\n";
481 for (MapTy::const_iterator I = Map.begin(), E = Map.end(); I != E; ++I)
482 cerr << " " << (++i) << ". " << I->second << " "
483 << I->second->getDescription() << endl;
487 void dump() const { print("dump output"); }
491 // ValTypeBase - This is the base class that is used by the various
492 // instantiations of TypeMap. This class is an AbstractType user that notifies
493 // the underlying TypeMap when it gets modified.
495 template<class ValType, class TypeClass>
496 class ValTypeBase : public AbstractTypeUser {
497 TypeMap<ValType, TypeClass> &MyTable;
499 inline ValTypeBase(TypeMap<ValType, TypeClass> &tab) : MyTable(tab) {}
501 // Subclass should override this... to update self as usual
502 virtual void doRefinement(const DerivedType *OldTy, const Type *NewTy) = 0;
504 // typeBecameConcrete - This callback occurs when a contained type refines
505 // to itself, but becomes concrete in the process. Our subclass should remove
506 // itself from the ATU list of the specified type.
508 virtual void typeBecameConcrete(const DerivedType *Ty) = 0;
510 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
511 if (OldTy == NewTy) {
512 if (!OldTy->isAbstract())
513 typeBecameConcrete(OldTy);
516 TypeMap<ValType, TypeClass> &Table = MyTable; // Copy MyTable reference
517 ValType Tmp(*(ValType*)this); // Copy this.
518 PATypeHandle<TypeClass> OldType(Table.get(*(ValType*)this), this);
519 Table.remove(*(ValType*)this); // Destroy's this!
521 // Refine temporary to new state...
522 Tmp.doRefinement(OldTy, NewTy);
524 Table.add((ValType&)Tmp, (TypeClass*)OldType.get());
529 cerr << "ValTypeBase instance!\n";
535 //===----------------------------------------------------------------------===//
536 // Function Type Factory and Value Class...
539 // FunctionValType - Define a class to hold the key that goes into the TypeMap
541 class FunctionValType : public ValTypeBase<FunctionValType, FunctionType> {
542 PATypeHandle<Type> RetTy;
543 vector<PATypeHandle<Type> > ArgTypes;
546 FunctionValType(const Type *ret, const vector<const Type*> &args,
547 bool IVA, TypeMap<FunctionValType, FunctionType> &Tab)
548 : ValTypeBase<FunctionValType, FunctionType>(Tab), RetTy(ret, this),
550 for (unsigned i = 0; i < args.size(); ++i)
551 ArgTypes.push_back(PATypeHandle<Type>(args[i], this));
554 // We *MUST* have an explicit copy ctor so that the TypeHandles think that
555 // this FunctionValType owns them, not the old one!
557 FunctionValType(const FunctionValType &MVT)
558 : ValTypeBase<FunctionValType, FunctionType>(MVT), RetTy(MVT.RetTy, this),
559 isVarArg(MVT.isVarArg) {
560 ArgTypes.reserve(MVT.ArgTypes.size());
561 for (unsigned i = 0; i < MVT.ArgTypes.size(); ++i)
562 ArgTypes.push_back(PATypeHandle<Type>(MVT.ArgTypes[i], this));
565 // Subclass should override this... to update self as usual
566 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
567 if (RetTy == OldType) RetTy = NewType;
568 for (unsigned i = 0; i < ArgTypes.size(); ++i)
569 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
572 virtual void typeBecameConcrete(const DerivedType *Ty) {
573 if (RetTy == Ty) RetTy.removeUserFromConcrete();
575 for (unsigned i = 0; i < ArgTypes.size(); ++i)
576 if (ArgTypes[i] == Ty) ArgTypes[i].removeUserFromConcrete();
579 inline bool operator<(const FunctionValType &MTV) const {
580 if (RetTy.get() < MTV.RetTy.get()) return true;
581 if (RetTy.get() > MTV.RetTy.get()) return false;
583 if (ArgTypes < MTV.ArgTypes) return true;
584 return (ArgTypes == MTV.ArgTypes) && isVarArg < MTV.isVarArg;
588 // Define the actual map itself now...
589 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
591 // FunctionType::get - The factory function for the FunctionType class...
592 FunctionType *FunctionType::get(const Type *ReturnType,
593 const vector<const Type*> &Params,
595 FunctionValType VT(ReturnType, Params, isVarArg, FunctionTypes);
596 FunctionType *MT = FunctionTypes.get(VT);
599 FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
601 #ifdef DEBUG_MERGE_TYPES
602 cerr << "Derived new type: " << MT << endl;
607 //===----------------------------------------------------------------------===//
608 // Array Type Factory...
610 class ArrayValType : public ValTypeBase<ArrayValType, ArrayType> {
611 PATypeHandle<Type> ValTy;
614 ArrayValType(const Type *val, int sz, TypeMap<ArrayValType, ArrayType> &Tab)
615 : ValTypeBase<ArrayValType, ArrayType>(Tab), ValTy(val, this), Size(sz) {}
617 // We *MUST* have an explicit copy ctor so that the ValTy thinks that this
618 // ArrayValType owns it, not the old one!
620 ArrayValType(const ArrayValType &AVT)
621 : ValTypeBase<ArrayValType, ArrayType>(AVT), ValTy(AVT.ValTy, this),
624 // Subclass should override this... to update self as usual
625 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
626 if (ValTy == OldType) ValTy = NewType;
629 virtual void typeBecameConcrete(const DerivedType *Ty) {
630 assert(ValTy == Ty &&
631 "Contained type became concrete but we're not using it!");
632 ValTy.removeUserFromConcrete();
635 inline bool operator<(const ArrayValType &MTV) const {
636 if (Size < MTV.Size) return true;
637 return Size == MTV.Size && ValTy.get() < MTV.ValTy.get();
641 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
643 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
644 assert(ElementType && "Can't get array of null types!");
646 ArrayValType AVT(ElementType, NumElements, ArrayTypes);
647 ArrayType *AT = ArrayTypes.get(AVT);
648 if (AT) return AT; // Found a match, return it!
650 // Value not found. Derive a new type!
651 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
653 #ifdef DEBUG_MERGE_TYPES
654 cerr << "Derived new type: " << AT->getDescription() << endl;
659 //===----------------------------------------------------------------------===//
660 // Struct Type Factory...
663 // StructValType - Define a class to hold the key that goes into the TypeMap
665 class StructValType : public ValTypeBase<StructValType, StructType> {
666 vector<PATypeHandle<Type> > ElTypes;
668 StructValType(const vector<const Type*> &args,
669 TypeMap<StructValType, StructType> &Tab)
670 : ValTypeBase<StructValType, StructType>(Tab) {
671 for (unsigned i = 0; i < args.size(); ++i)
672 ElTypes.push_back(PATypeHandle<Type>(args[i], this));
675 // We *MUST* have an explicit copy ctor so that the TypeHandles think that
676 // this StructValType owns them, not the old one!
678 StructValType(const StructValType &SVT)
679 : ValTypeBase<StructValType, StructType>(SVT){
680 ElTypes.reserve(SVT.ElTypes.size());
681 for (unsigned i = 0; i < SVT.ElTypes.size(); ++i)
682 ElTypes.push_back(PATypeHandle<Type>(SVT.ElTypes[i], this));
685 // Subclass should override this... to update self as usual
686 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
687 for (unsigned i = 0; i < ElTypes.size(); ++i)
688 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
691 virtual void typeBecameConcrete(const DerivedType *Ty) {
692 for (unsigned i = 0; i < ElTypes.size(); ++i)
693 if (ElTypes[i] == Ty) ElTypes[i].removeUserFromConcrete();
696 inline bool operator<(const StructValType &STV) const {
697 return ElTypes < STV.ElTypes;
701 static TypeMap<StructValType, StructType> StructTypes;
703 StructType *StructType::get(const vector<const Type*> &ETypes) {
704 StructValType STV(ETypes, StructTypes);
705 StructType *ST = StructTypes.get(STV);
708 // Value not found. Derive a new type!
709 StructTypes.add(STV, ST = new StructType(ETypes));
711 #ifdef DEBUG_MERGE_TYPES
712 cerr << "Derived new type: " << ST->getDescription() << endl;
717 //===----------------------------------------------------------------------===//
718 // Pointer Type Factory...
721 // PointerValType - Define a class to hold the key that goes into the TypeMap
723 class PointerValType : public ValTypeBase<PointerValType, PointerType> {
724 PATypeHandle<Type> ValTy;
726 PointerValType(const Type *val, TypeMap<PointerValType, PointerType> &Tab)
727 : ValTypeBase<PointerValType, PointerType>(Tab), ValTy(val, this) {}
729 // We *MUST* have an explicit copy ctor so that the ValTy thinks that this
730 // PointerValType owns it, not the old one!
732 PointerValType(const PointerValType &PVT)
733 : ValTypeBase<PointerValType, PointerType>(PVT), ValTy(PVT.ValTy, this) {}
735 // Subclass should override this... to update self as usual
736 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
737 if (ValTy == OldType) ValTy = NewType;
740 virtual void typeBecameConcrete(const DerivedType *Ty) {
741 assert(ValTy == Ty &&
742 "Contained type became concrete but we're not using it!");
743 ValTy.removeUserFromConcrete();
746 inline bool operator<(const PointerValType &MTV) const {
747 return ValTy.get() < MTV.ValTy.get();
751 static TypeMap<PointerValType, PointerType> PointerTypes;
753 PointerType *PointerType::get(const Type *ValueType) {
754 assert(ValueType && "Can't get a pointer to <null> type!");
755 PointerValType PVT(ValueType, PointerTypes);
757 PointerType *PT = PointerTypes.get(PVT);
760 // Value not found. Derive a new type!
761 PointerTypes.add(PVT, PT = new PointerType(ValueType));
763 #ifdef DEBUG_MERGE_TYPES
764 cerr << "Derived new type: " << PT->getDescription() << endl;
771 //===----------------------------------------------------------------------===//
772 // Derived Type Refinement Functions
773 //===----------------------------------------------------------------------===//
775 // removeAbstractTypeUser - Notify an abstract type that a user of the class
776 // no longer has a handle to the type. This function is called primarily by
777 // the PATypeHandle class. When there are no users of the abstract type, it
778 // is anihilated, because there is no way to get a reference to it ever again.
780 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
781 // Search from back to front because we will notify users from back to
782 // front. Also, it is likely that there will be a stack like behavior to
783 // users that register and unregister users.
786 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
787 assert(i != 0 && "AbstractTypeUser not in user list!");
789 --i; // Convert to be in range 0 <= i < size()
790 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
792 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
794 #ifdef DEBUG_MERGE_TYPES
795 cerr << " remAbstractTypeUser[" << (void*)this << ", "
796 << getDescription() << "][" << i << "] User = " << U << endl;
799 if (AbstractTypeUsers.empty() && isAbstract()) {
800 #ifdef DEBUG_MERGE_TYPES
801 cerr << "DELETEing unused abstract type: <" << getDescription()
802 << ">[" << (void*)this << "]" << endl;
804 delete this; // No users of this abstract type!
809 // refineAbstractTypeTo - This function is used to when it is discovered that
810 // the 'this' abstract type is actually equivalent to the NewType specified.
811 // This causes all users of 'this' to switch to reference the more concrete
812 // type NewType and for 'this' to be deleted.
814 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
815 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
816 assert(this != NewType && "Can't refine to myself!");
818 #ifdef DEBUG_MERGE_TYPES
819 cerr << "REFINING abstract type [" << (void*)this << " " << getDescription()
820 << "] to [" << (void*)NewType << " " << NewType->getDescription()
825 // Make sure to put the type to be refined to into a holder so that if IT gets
826 // refined, that we will not continue using a dead reference...
828 PATypeHolder NewTy(NewType);
830 // Add a self use of the current type so that we don't delete ourself until
831 // after this while loop. We are careful to never invoke refine on ourself,
832 // so this extra reference shouldn't be a problem. Note that we must only
833 // remove a single reference at the end, but we must tolerate multiple self
834 // references because we could be refineAbstractTypeTo'ing recursively on the
837 addAbstractTypeUser(this);
839 // Count the number of self uses. Stop looping when sizeof(list) == NSU.
840 unsigned NumSelfUses = 0;
842 // Iterate over all of the uses of this type, invoking callback. Each user
843 // should remove itself from our use list automatically. We have to check to
844 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
845 // will not cause users to drop off of the use list. If we resolve to ourself
848 while (AbstractTypeUsers.size() > NumSelfUses && NewTy != this) {
849 AbstractTypeUser *User = AbstractTypeUsers.back();
852 // Move self use to the start of the list. Increment NSU.
853 swap(AbstractTypeUsers.back(), AbstractTypeUsers[NumSelfUses++]);
855 unsigned OldSize = AbstractTypeUsers.size();
856 #ifdef DEBUG_MERGE_TYPES
857 cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
858 << "] of abstract type ["
859 << (void*)this << " " << getDescription() << "] to ["
860 << (void*)NewTy.get() << " " << NewTy->getDescription() << "]!\n";
862 User->refineAbstractType(this, NewTy);
864 #ifdef DEBUG_MERGE_TYPES
865 if (AbstractTypeUsers.size() == OldSize) {
866 User->refineAbstractType(this, NewTy);
867 if (AbstractTypeUsers.back() != User)
868 cerr << "User changed!\n";
869 cerr << "Top of user list is:\n";
870 AbstractTypeUsers.back()->dump();
872 cerr <<"\nOld User=\n";
876 assert(AbstractTypeUsers.size() != OldSize &&
877 "AbsTyUser did not remove self from user list!");
881 // Remove a single self use, even though there may be several here. This will
882 // probably 'delete this', so no instance variables may be used after this
885 assert((NewTy == this || AbstractTypeUsers.back() == this) &&
886 "Only self uses should be left!");
887 removeAbstractTypeUser(this);
890 // typeIsRefined - Notify AbstractTypeUsers of this type that the current type
891 // has been refined a bit. The pointer is still valid and still should be
892 // used, but the subtypes have changed.
894 void DerivedType::typeIsRefined() {
895 assert(isRefining >= 0 && isRefining <= 2 && "isRefining out of bounds!");
896 if (isRefining == 1) return; // Kill recursion here...
899 #ifdef DEBUG_MERGE_TYPES
900 cerr << "typeIsREFINED type: " << (void*)this <<" "<<getDescription() << endl;
902 for (unsigned i = 0; i < AbstractTypeUsers.size(); ) {
903 AbstractTypeUser *ATU = AbstractTypeUsers[i];
904 #ifdef DEBUG_MERGE_TYPES
905 cerr << " typeIsREFINED user " << i << " of abstract type ["
906 << (void*)this << " " << getDescription() << "]\n";
908 ATU->refineAbstractType(this, this);
910 // If the user didn't remove itself from the list, continue...
911 if (AbstractTypeUsers.size() > i && AbstractTypeUsers[i] == ATU) {
919 if (!(isAbstract() || AbstractTypeUsers.empty()))
920 for (unsigned i = 0; i < AbstractTypeUsers.size(); ++i) {
921 if (AbstractTypeUsers[i] != this) {
923 cerr << "FOUND FAILURE\n";
924 AbstractTypeUsers[i]->dump();
925 AbstractTypeUsers[i]->refineAbstractType(this, this);
926 assert(0 && "Type became concrete,"
927 " but it still has abstract type users hanging around!");
936 // refineAbstractType - Called when a contained type is found to be more
937 // concrete - this could potentially change us from an abstract type to a
940 void FunctionType::refineAbstractType(const DerivedType *OldType,
941 const Type *NewType) {
942 #ifdef DEBUG_MERGE_TYPES
943 cerr << "FunctionTy::refineAbstractTy(" << (void*)OldType << "["
944 << OldType->getDescription() << "], " << (void*)NewType << " ["
945 << NewType->getDescription() << "])\n";
948 if (!OldType->isAbstract()) {
949 if (ResultType == OldType) ResultType.removeUserFromConcrete();
950 for (unsigned i = 0; i < ParamTys.size(); ++i)
951 if (ParamTys[i] == OldType) ParamTys[i].removeUserFromConcrete();
954 if (OldType != NewType) {
955 if (ResultType == OldType) ResultType = NewType;
957 for (unsigned i = 0; i < ParamTys.size(); ++i)
958 if (ParamTys[i] == OldType) ParamTys[i] = NewType;
961 const FunctionType *MT = FunctionTypes.containsEquivalent(this);
962 if (MT && MT != this) {
963 refineAbstractTypeTo(MT); // Different type altogether...
965 setDerivedTypeProperties(); // Update the name and isAbstract
966 typeIsRefined(); // Same type, different contents...
971 // refineAbstractType - Called when a contained type is found to be more
972 // concrete - this could potentially change us from an abstract type to a
975 void ArrayType::refineAbstractType(const DerivedType *OldType,
976 const Type *NewType) {
977 #ifdef DEBUG_MERGE_TYPES
978 cerr << "ArrayTy::refineAbstractTy(" << (void*)OldType << "["
979 << OldType->getDescription() << "], " << (void*)NewType << " ["
980 << NewType->getDescription() << "])\n";
983 if (!OldType->isAbstract()) {
984 assert(getElementType() == OldType);
985 ElementType.removeUserFromConcrete();
988 ElementType = NewType;
989 const ArrayType *AT = ArrayTypes.containsEquivalent(this);
990 if (AT && AT != this) {
991 refineAbstractTypeTo(AT); // Different type altogether...
993 setDerivedTypeProperties(); // Update the name and isAbstract
994 typeIsRefined(); // Same type, different contents...
999 // refineAbstractType - Called when a contained type is found to be more
1000 // concrete - this could potentially change us from an abstract type to a
1003 void StructType::refineAbstractType(const DerivedType *OldType,
1004 const Type *NewType) {
1005 #ifdef DEBUG_MERGE_TYPES
1006 cerr << "StructTy::refineAbstractTy(" << (void*)OldType << "["
1007 << OldType->getDescription() << "], " << (void*)NewType << " ["
1008 << NewType->getDescription() << "])\n";
1010 if (!OldType->isAbstract()) {
1011 for (unsigned i = 0; i < ETypes.size(); ++i)
1012 if (ETypes[i] == OldType)
1013 ETypes[i].removeUserFromConcrete();
1016 if (OldType != NewType) {
1017 // Update old type to new type in the array...
1018 for (unsigned i = 0; i < ETypes.size(); ++i)
1019 if (ETypes[i] == OldType)
1020 ETypes[i] = NewType;
1023 const StructType *ST = StructTypes.containsEquivalent(this);
1024 if (ST && ST != this) {
1025 refineAbstractTypeTo(ST); // Different type altogether...
1027 setDerivedTypeProperties(); // Update the name and isAbstract
1028 typeIsRefined(); // Same type, different contents...
1032 // refineAbstractType - Called when a contained type is found to be more
1033 // concrete - this could potentially change us from an abstract type to a
1036 void PointerType::refineAbstractType(const DerivedType *OldType,
1037 const Type *NewType) {
1038 #ifdef DEBUG_MERGE_TYPES
1039 cerr << "PointerTy::refineAbstractTy(" << (void*)OldType << "["
1040 << OldType->getDescription() << "], " << (void*)NewType << " ["
1041 << NewType->getDescription() << "])\n";
1044 if (!OldType->isAbstract()) {
1045 assert(ElementType == OldType);
1046 ElementType.removeUserFromConcrete();
1049 ElementType = NewType;
1050 const PointerType *PT = PointerTypes.containsEquivalent(this);
1052 if (PT && PT != this) {
1053 refineAbstractTypeTo(PT); // Different type altogether...
1055 setDerivedTypeProperties(); // Update the name and isAbstract
1056 typeIsRefined(); // Same type, different contents...