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 "llvm/Constants.h"
10 #include "Support/StringExtras.h"
11 #include "Support/STLExtras.h"
14 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
15 // created and later destroyed, all in an effort to make sure that there is only
16 // a single cannonical version of a type.
18 //#define DEBUG_MERGE_TYPES 1
21 //===----------------------------------------------------------------------===//
22 // Type Class Implementation
23 //===----------------------------------------------------------------------===//
25 static unsigned CurUID = 0;
26 static std::vector<const Type *> UIDMappings;
28 void PATypeHolder::dump() const {
29 std::cerr << "PATypeHolder(" << (void*)this << ")\n";
33 Type::Type(const std::string &name, PrimitiveID id)
34 : Value(Type::TypeTy, Value::TypeVal) {
37 Abstract = Recursive = false;
38 UID = CurUID++; // Assign types UID's as they are created
39 UIDMappings.push_back(this);
42 void Type::setName(const std::string &Name, SymbolTable *ST) {
43 assert(ST && "Type::setName - Must provide symbol table argument!");
45 if (Name.size()) ST->insert(Name, this);
49 const Type *Type::getUniqueIDType(unsigned UID) {
50 assert(UID < UIDMappings.size() &&
51 "Type::getPrimitiveType: UID out of range!");
52 return UIDMappings[UID];
55 const Type *Type::getPrimitiveType(PrimitiveID IDNumber) {
57 case VoidTyID : return VoidTy;
58 case BoolTyID : return BoolTy;
59 case UByteTyID : return UByteTy;
60 case SByteTyID : return SByteTy;
61 case UShortTyID: return UShortTy;
62 case ShortTyID : return ShortTy;
63 case UIntTyID : return UIntTy;
64 case IntTyID : return IntTy;
65 case ULongTyID : return ULongTy;
66 case LongTyID : return LongTy;
67 case FloatTyID : return FloatTy;
68 case DoubleTyID: return DoubleTy;
69 case TypeTyID : return TypeTy;
70 case LabelTyID : return LabelTy;
76 // isLosslesslyConvertibleTo - Return true if this type can be converted to
77 // 'Ty' without any reinterpretation of bits. For example, uint to int.
79 bool Type::isLosslesslyConvertibleTo(const Type *Ty) const {
80 if (this == Ty) return true;
81 if ((!isPrimitiveType() && !isa<PointerType>(this)) ||
82 (!isa<PointerType>(Ty) && !Ty->isPrimitiveType())) return false;
84 if (getPrimitiveID() == Ty->getPrimitiveID())
85 return true; // Handles identity cast, and cast of differing pointer types
87 // Now we know that they are two differing primitive or pointer types
88 switch (getPrimitiveID()) {
89 case Type::UByteTyID: return Ty == Type::SByteTy;
90 case Type::SByteTyID: return Ty == Type::UByteTy;
91 case Type::UShortTyID: return Ty == Type::ShortTy;
92 case Type::ShortTyID: return Ty == Type::UShortTy;
93 case Type::UIntTyID: return Ty == Type::IntTy;
94 case Type::IntTyID: return Ty == Type::UIntTy;
97 case Type::PointerTyID:
98 return Ty == Type::ULongTy || Ty == Type::LongTy || isa<PointerType>(Ty);
100 return false; // Other types have no identity values
104 // getPrimitiveSize - Return the basic size of this type if it is a primative
105 // type. These are fixed by LLVM and are not target dependant. This will
106 // return zero if the type does not have a size or is not a primitive type.
108 unsigned Type::getPrimitiveSize() const {
109 switch (getPrimitiveID()) {
110 #define HANDLE_PRIM_TYPE(TY,SIZE) case TY##TyID: return SIZE;
111 #include "llvm/Type.def"
117 bool StructType::indexValid(const Value *V) const {
118 if (!isa<Constant>(V)) return false;
119 if (V->getType() != Type::UByteTy) return false;
120 unsigned Idx = cast<ConstantUInt>(V)->getValue();
121 return Idx < ETypes.size();
124 // getTypeAtIndex - Given an index value into the type, return the type of the
125 // element. For a structure type, this must be a constant value...
127 const Type *StructType::getTypeAtIndex(const Value *V) const {
128 assert(isa<Constant>(V) && "Structure index must be a constant!!");
129 assert(V->getType() == Type::UByteTy && "Structure index must be ubyte!");
130 unsigned Idx = cast<ConstantUInt>(V)->getValue();
131 assert(Idx < ETypes.size() && "Structure index out of range!");
132 assert(indexValid(V) && "Invalid structure index!"); // Duplicate check
138 //===----------------------------------------------------------------------===//
139 // Auxilliary classes
140 //===----------------------------------------------------------------------===//
142 // These classes are used to implement specialized behavior for each different
145 struct SignedIntType : public Type {
146 SignedIntType(const std::string &Name, PrimitiveID id) : Type(Name, id) {}
148 // isSigned - Return whether a numeric type is signed.
149 virtual bool isSigned() const { return 1; }
151 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
152 // virtual function invocation.
154 virtual bool isInteger() const { return 1; }
157 struct UnsignedIntType : public Type {
158 UnsignedIntType(const std::string &N, PrimitiveID id) : Type(N, id) {}
160 // isUnsigned - Return whether a numeric type is signed.
161 virtual bool isUnsigned() const { return 1; }
163 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
164 // virtual function invocation.
166 virtual bool isInteger() const { return 1; }
169 struct OtherType : public Type {
170 OtherType(const std::string &N, PrimitiveID id) : Type(N, id) {}
173 static struct TypeType : public Type {
174 TypeType() : Type("type", TypeTyID) {}
175 } TheTypeTy; // Implement the type that is global.
178 //===----------------------------------------------------------------------===//
179 // Static 'Type' data
180 //===----------------------------------------------------------------------===//
182 static OtherType TheVoidTy ("void" , Type::VoidTyID);
183 static OtherType TheBoolTy ("bool" , Type::BoolTyID);
184 static SignedIntType TheSByteTy ("sbyte" , Type::SByteTyID);
185 static UnsignedIntType TheUByteTy ("ubyte" , Type::UByteTyID);
186 static SignedIntType TheShortTy ("short" , Type::ShortTyID);
187 static UnsignedIntType TheUShortTy("ushort", Type::UShortTyID);
188 static SignedIntType TheIntTy ("int" , Type::IntTyID);
189 static UnsignedIntType TheUIntTy ("uint" , Type::UIntTyID);
190 static SignedIntType TheLongTy ("long" , Type::LongTyID);
191 static UnsignedIntType TheULongTy ("ulong" , Type::ULongTyID);
192 static OtherType TheFloatTy ("float" , Type::FloatTyID);
193 static OtherType TheDoubleTy("double", Type::DoubleTyID);
194 static OtherType TheLabelTy ("label" , Type::LabelTyID);
196 Type *Type::VoidTy = &TheVoidTy;
197 Type *Type::BoolTy = &TheBoolTy;
198 Type *Type::SByteTy = &TheSByteTy;
199 Type *Type::UByteTy = &TheUByteTy;
200 Type *Type::ShortTy = &TheShortTy;
201 Type *Type::UShortTy = &TheUShortTy;
202 Type *Type::IntTy = &TheIntTy;
203 Type *Type::UIntTy = &TheUIntTy;
204 Type *Type::LongTy = &TheLongTy;
205 Type *Type::ULongTy = &TheULongTy;
206 Type *Type::FloatTy = &TheFloatTy;
207 Type *Type::DoubleTy = &TheDoubleTy;
208 Type *Type::TypeTy = &TheTypeTy;
209 Type *Type::LabelTy = &TheLabelTy;
212 //===----------------------------------------------------------------------===//
213 // Derived Type Constructors
214 //===----------------------------------------------------------------------===//
216 FunctionType::FunctionType(const Type *Result,
217 const std::vector<const Type*> &Params,
218 bool IsVarArgs) : DerivedType(FunctionTyID),
219 ResultType(PATypeHandle(Result, this)),
220 isVarArgs(IsVarArgs) {
221 ParamTys.reserve(Params.size());
222 for (unsigned i = 0; i < Params.size(); ++i)
223 ParamTys.push_back(PATypeHandle(Params[i], this));
225 setDerivedTypeProperties();
228 StructType::StructType(const std::vector<const Type*> &Types)
229 : CompositeType(StructTyID) {
230 ETypes.reserve(Types.size());
231 for (unsigned i = 0; i < Types.size(); ++i) {
232 assert(Types[i] != Type::VoidTy && "Void type in method prototype!!");
233 ETypes.push_back(PATypeHandle(Types[i], this));
235 setDerivedTypeProperties();
238 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
239 : SequentialType(ArrayTyID, ElType) {
241 setDerivedTypeProperties();
244 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
245 setDerivedTypeProperties();
248 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
250 setDescription("opaque"+utostr(getUniqueID()));
251 #ifdef DEBUG_MERGE_TYPES
252 std::cerr << "Derived new type: " << getDescription() << "\n";
259 //===----------------------------------------------------------------------===//
260 // Derived Type setDerivedTypeProperties Function
261 //===----------------------------------------------------------------------===//
263 // getTypeProps - This is a recursive function that walks a type hierarchy
264 // calculating the description for a type and whether or not it is abstract or
265 // recursive. Worst case it will have to do a lot of traversing if you have
266 // some whacko opaque types, but in most cases, it will do some simple stuff
267 // when it hits non-abstract types that aren't recursive.
269 static std::string getTypeProps(const Type *Ty,
270 std::vector<const Type *> &TypeStack,
271 bool &isAbstract, bool &isRecursive) {
272 if (!Ty->isAbstract() && !Ty->isRecursive() && // Base case for the recursion
273 Ty->getDescription().size()) {
274 return Ty->getDescription(); // Primitive = leaf type
275 } else if (isa<OpaqueType>(Ty)) { // Base case for the recursion
276 isAbstract = true; // This whole type is abstract!
277 return Ty->getDescription(); // Opaque = leaf type
279 // Check to see if the Type is already on the stack...
280 unsigned Slot = 0, CurSize = TypeStack.size();
281 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
283 // This is another base case for the recursion. In this case, we know
284 // that we have looped back to a type that we have previously visited.
285 // Generate the appropriate upreference to handle this.
287 if (Slot < CurSize) {
288 isRecursive = true; // We know we are recursive
289 return "\\" + utostr(CurSize-Slot); // Here's the upreference
290 } else { // Recursive case: abstract derived type...
292 TypeStack.push_back(Ty); // Add us to the stack..
294 switch (Ty->getPrimitiveID()) {
295 case Type::FunctionTyID: {
296 const FunctionType *MTy = cast<FunctionType>(Ty);
297 Result = getTypeProps(MTy->getReturnType(), TypeStack,
298 isAbstract, isRecursive)+" (";
299 for (FunctionType::ParamTypes::const_iterator
300 I = MTy->getParamTypes().begin(),
301 E = MTy->getParamTypes().end(); I != E; ++I) {
302 if (I != MTy->getParamTypes().begin())
304 Result += getTypeProps(*I, TypeStack, isAbstract, isRecursive);
306 if (MTy->isVarArg()) {
307 if (!MTy->getParamTypes().empty()) Result += ", ";
313 case Type::StructTyID: {
314 const StructType *STy = cast<StructType>(Ty);
316 for (StructType::ElementTypes::const_iterator
317 I = STy->getElementTypes().begin(),
318 E = STy->getElementTypes().end(); I != E; ++I) {
319 if (I != STy->getElementTypes().begin())
321 Result += getTypeProps(*I, TypeStack, isAbstract, isRecursive);
326 case Type::PointerTyID: {
327 const PointerType *PTy = cast<PointerType>(Ty);
328 Result = getTypeProps(PTy->getElementType(), TypeStack,
329 isAbstract, isRecursive) + " *";
332 case Type::ArrayTyID: {
333 const ArrayType *ATy = cast<ArrayType>(Ty);
334 unsigned NumElements = ATy->getNumElements();
336 Result += utostr(NumElements) + " x ";
337 Result += getTypeProps(ATy->getElementType(), TypeStack,
338 isAbstract, isRecursive) + "]";
342 assert(0 && "Unhandled case in getTypeProps!");
346 TypeStack.pop_back(); // Remove self from stack...
353 // setDerivedTypeProperties - This function is used to calculate the
354 // isAbstract, isRecursive, and the Description settings for a type. The
355 // getTypeProps function does all the dirty work.
357 void DerivedType::setDerivedTypeProperties() {
358 std::vector<const Type *> TypeStack;
359 bool isAbstract = false, isRecursive = false;
361 setDescription(getTypeProps(this, TypeStack, isAbstract, isRecursive));
362 setAbstract(isAbstract);
363 setRecursive(isRecursive);
367 //===----------------------------------------------------------------------===//
368 // Type Structural Equality Testing
369 //===----------------------------------------------------------------------===//
371 // TypesEqual - Two types are considered structurally equal if they have the
372 // same "shape": Every level and element of the types have identical primitive
373 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
374 // be pointer equals to be equivalent though. This uses an optimistic algorithm
375 // that assumes that two graphs are the same until proven otherwise.
377 static bool TypesEqual(const Type *Ty, const Type *Ty2,
378 std::map<const Type *, const Type *> &EqTypes) {
379 if (Ty == Ty2) return true;
380 if (Ty->getPrimitiveID() != Ty2->getPrimitiveID()) return false;
381 if (Ty->isPrimitiveType()) return true;
382 if (isa<OpaqueType>(Ty))
383 return false; // Two nonequal opaque types are never equal
385 std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
386 if (It != EqTypes.end())
387 return It->second == Ty2; // Looping back on a type, check for equality
389 // Otherwise, add the mapping to the table to make sure we don't get
390 // recursion on the types...
391 EqTypes.insert(std::make_pair(Ty, Ty2));
393 // Iterate over the types and make sure the the contents are equivalent...
394 Type::subtype_iterator I = Ty ->subtype_begin(), IE = Ty ->subtype_end();
395 Type::subtype_iterator I2 = Ty2->subtype_begin(), IE2 = Ty2->subtype_end();
396 for (; I != IE && I2 != IE2; ++I, ++I2)
397 if (!TypesEqual(*I, *I2, EqTypes)) return false;
399 // Two really annoying special cases that breaks an otherwise nice simple
400 // algorithm is the fact that arraytypes have sizes that differentiates types,
401 // and that method types can be varargs or not. Consider this now.
402 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
403 if (ATy->getNumElements() != cast<ArrayType>(Ty2)->getNumElements())
405 } else if (const FunctionType *MTy = dyn_cast<FunctionType>(Ty)) {
406 if (MTy->isVarArg() != cast<FunctionType>(Ty2)->isVarArg())
410 return I == IE && I2 == IE2; // Types equal if both iterators are done
413 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
414 std::map<const Type *, const Type *> EqTypes;
415 return TypesEqual(Ty, Ty2, EqTypes);
420 //===----------------------------------------------------------------------===//
421 // Derived Type Factory Functions
422 //===----------------------------------------------------------------------===//
424 // TypeMap - Make sure that only one instance of a particular type may be
425 // created on any given run of the compiler... note that this involves updating
426 // our map if an abstract type gets refined somehow...
428 template<class ValType, class TypeClass>
429 class TypeMap : public AbstractTypeUser {
430 typedef std::map<ValType, PATypeHandle> MapTy;
433 ~TypeMap() { print("ON EXIT"); }
435 inline TypeClass *get(const ValType &V) {
436 typename std::map<ValType, PATypeHandle>::iterator I
438 // TODO: FIXME: When Types are not CONST.
439 return (I != Map.end()) ? (TypeClass*)I->second.get() : 0;
442 inline void add(const ValType &V, TypeClass *T) {
443 Map.insert(std::make_pair(V, PATypeHandle(T, this)));
447 // containsEquivalent - Return true if the typemap contains a type that is
448 // structurally equivalent to the specified type.
450 inline const TypeClass *containsEquivalent(const TypeClass *Ty) {
451 for (typename MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
452 if (I->second.get() != Ty && TypesEqual(Ty, I->second.get()))
453 return (TypeClass*)I->second.get(); // FIXME TODO when types not const
457 // refineAbstractType - This is called when one of the contained abstract
458 // types gets refined... this simply removes the abstract type from our table.
459 // We expect that whoever refined the type will add it back to the table,
462 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
463 #ifdef DEBUG_MERGE_TYPES
464 std::cerr << "Removing Old type from Tab: " << (void*)OldTy << ", "
465 << OldTy->getDescription() << " replacement == " << (void*)NewTy
466 << ", " << NewTy->getDescription() << "\n";
468 for (typename MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
469 if (I->second == OldTy) {
470 // Check to see if the type just became concrete. If so, remove self
472 I->second.removeUserFromConcrete();
473 I->second = cast<TypeClass>(NewTy);
477 void remove(const ValType &OldVal) {
478 typename MapTy::iterator I = Map.find(OldVal);
479 assert(I != Map.end() && "TypeMap::remove, element not found!");
483 void print(const char *Arg) const {
484 #ifdef DEBUG_MERGE_TYPES
485 std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
487 for (MapTy::const_iterator I = Map.begin(), E = Map.end(); I != E; ++I)
488 std::cerr << " " << (++i) << ". " << I->second << " "
489 << I->second->getDescription() << "\n";
493 void dump() const { print("dump output"); }
497 // ValTypeBase - This is the base class that is used by the various
498 // instantiations of TypeMap. This class is an AbstractType user that notifies
499 // the underlying TypeMap when it gets modified.
501 template<class ValType, class TypeClass>
502 class ValTypeBase : public AbstractTypeUser {
503 TypeMap<ValType, TypeClass> &MyTable;
505 inline ValTypeBase(TypeMap<ValType, TypeClass> &tab) : MyTable(tab) {}
507 // Subclass should override this... to update self as usual
508 virtual void doRefinement(const DerivedType *OldTy, const Type *NewTy) = 0;
510 // typeBecameConcrete - This callback occurs when a contained type refines
511 // to itself, but becomes concrete in the process. Our subclass should remove
512 // itself from the ATU list of the specified type.
514 virtual void typeBecameConcrete(const DerivedType *Ty) = 0;
516 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
517 assert(OldTy == NewTy || OldTy->isAbstract());
519 if (!OldTy->isAbstract())
520 typeBecameConcrete(OldTy);
522 TypeMap<ValType, TypeClass> &Table = MyTable; // Copy MyTable reference
523 ValType Tmp(*(ValType*)this); // Copy this.
524 PATypeHandle OldType(Table.get(*(ValType*)this), this);
525 Table.remove(*(ValType*)this); // Destroy's this!
527 // Refine temporary to new state...
529 Tmp.doRefinement(OldTy, NewTy);
531 // FIXME: when types are not const!
532 Table.add((ValType&)Tmp, (TypeClass*)OldType.get());
536 std::cerr << "ValTypeBase instance!\n";
542 //===----------------------------------------------------------------------===//
543 // Function Type Factory and Value Class...
546 // FunctionValType - Define a class to hold the key that goes into the TypeMap
548 class FunctionValType : public ValTypeBase<FunctionValType, FunctionType> {
550 std::vector<PATypeHandle> ArgTypes;
553 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
554 bool IVA, TypeMap<FunctionValType, FunctionType> &Tab)
555 : ValTypeBase<FunctionValType, FunctionType>(Tab), RetTy(ret, this),
557 for (unsigned i = 0; i < args.size(); ++i)
558 ArgTypes.push_back(PATypeHandle(args[i], this));
561 // We *MUST* have an explicit copy ctor so that the TypeHandles think that
562 // this FunctionValType owns them, not the old one!
564 FunctionValType(const FunctionValType &MVT)
565 : ValTypeBase<FunctionValType, FunctionType>(MVT), RetTy(MVT.RetTy, this),
566 isVarArg(MVT.isVarArg) {
567 ArgTypes.reserve(MVT.ArgTypes.size());
568 for (unsigned i = 0; i < MVT.ArgTypes.size(); ++i)
569 ArgTypes.push_back(PATypeHandle(MVT.ArgTypes[i], this));
572 // Subclass should override this... to update self as usual
573 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
574 if (RetTy == OldType) RetTy = NewType;
575 for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
576 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
579 virtual void typeBecameConcrete(const DerivedType *Ty) {
580 if (RetTy == Ty) RetTy.removeUserFromConcrete();
582 for (unsigned i = 0; i < ArgTypes.size(); ++i)
583 if (ArgTypes[i] == Ty) ArgTypes[i].removeUserFromConcrete();
586 inline bool operator<(const FunctionValType &MTV) const {
587 if (RetTy.get() < MTV.RetTy.get()) return true;
588 if (RetTy.get() > MTV.RetTy.get()) return false;
590 if (ArgTypes < MTV.ArgTypes) return true;
591 return (ArgTypes == MTV.ArgTypes) && isVarArg < MTV.isVarArg;
595 // Define the actual map itself now...
596 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
598 // FunctionType::get - The factory function for the FunctionType class...
599 FunctionType *FunctionType::get(const Type *ReturnType,
600 const std::vector<const Type*> &Params,
602 FunctionValType VT(ReturnType, Params, isVarArg, FunctionTypes);
603 FunctionType *MT = FunctionTypes.get(VT);
606 FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
608 #ifdef DEBUG_MERGE_TYPES
609 std::cerr << "Derived new type: " << MT << "\n";
614 //===----------------------------------------------------------------------===//
615 // Array Type Factory...
617 class ArrayValType : public ValTypeBase<ArrayValType, ArrayType> {
621 ArrayValType(const Type *val, int sz, TypeMap<ArrayValType, ArrayType> &Tab)
622 : ValTypeBase<ArrayValType, ArrayType>(Tab), ValTy(val, this), Size(sz) {}
624 // We *MUST* have an explicit copy ctor so that the ValTy thinks that this
625 // ArrayValType owns it, not the old one!
627 ArrayValType(const ArrayValType &AVT)
628 : ValTypeBase<ArrayValType, ArrayType>(AVT), ValTy(AVT.ValTy, this),
631 // Subclass should override this... to update self as usual
632 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
633 assert(ValTy == OldType);
637 virtual void typeBecameConcrete(const DerivedType *Ty) {
638 assert(ValTy == Ty &&
639 "Contained type became concrete but we're not using it!");
640 ValTy.removeUserFromConcrete();
643 inline bool operator<(const ArrayValType &MTV) const {
644 if (Size < MTV.Size) return true;
645 return Size == MTV.Size && ValTy.get() < MTV.ValTy.get();
649 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
651 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
652 assert(ElementType && "Can't get array of null types!");
654 ArrayValType AVT(ElementType, NumElements, ArrayTypes);
655 ArrayType *AT = ArrayTypes.get(AVT);
656 if (AT) return AT; // Found a match, return it!
658 // Value not found. Derive a new type!
659 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
661 #ifdef DEBUG_MERGE_TYPES
662 std::cerr << "Derived new type: " << AT->getDescription() << "\n";
667 //===----------------------------------------------------------------------===//
668 // Struct Type Factory...
671 // StructValType - Define a class to hold the key that goes into the TypeMap
673 class StructValType : public ValTypeBase<StructValType, StructType> {
674 std::vector<PATypeHandle> ElTypes;
676 StructValType(const std::vector<const Type*> &args,
677 TypeMap<StructValType, StructType> &Tab)
678 : ValTypeBase<StructValType, StructType>(Tab) {
679 ElTypes.reserve(args.size());
680 for (unsigned i = 0, e = args.size(); i != e; ++i)
681 ElTypes.push_back(PATypeHandle(args[i], this));
684 // We *MUST* have an explicit copy ctor so that the TypeHandles think that
685 // this StructValType owns them, not the old one!
687 StructValType(const StructValType &SVT)
688 : ValTypeBase<StructValType, StructType>(SVT){
689 ElTypes.reserve(SVT.ElTypes.size());
690 for (unsigned i = 0, e = SVT.ElTypes.size(); i != e; ++i)
691 ElTypes.push_back(PATypeHandle(SVT.ElTypes[i], this));
694 // Subclass should override this... to update self as usual
695 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
696 for (unsigned i = 0; i < ElTypes.size(); ++i)
697 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
700 virtual void typeBecameConcrete(const DerivedType *Ty) {
701 for (unsigned i = 0, e = ElTypes.size(); i != e; ++i)
702 if (ElTypes[i] == Ty)
703 ElTypes[i].removeUserFromConcrete();
706 inline bool operator<(const StructValType &STV) const {
707 return ElTypes < STV.ElTypes;
711 static TypeMap<StructValType, StructType> StructTypes;
713 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
714 StructValType STV(ETypes, StructTypes);
715 StructType *ST = StructTypes.get(STV);
718 // Value not found. Derive a new type!
719 StructTypes.add(STV, ST = new StructType(ETypes));
721 #ifdef DEBUG_MERGE_TYPES
722 std::cerr << "Derived new type: " << ST->getDescription() << "\n";
727 //===----------------------------------------------------------------------===//
728 // Pointer Type Factory...
731 // PointerValType - Define a class to hold the key that goes into the TypeMap
733 class PointerValType : public ValTypeBase<PointerValType, PointerType> {
736 PointerValType(const Type *val, TypeMap<PointerValType, PointerType> &Tab)
737 : ValTypeBase<PointerValType, PointerType>(Tab), ValTy(val, this) {}
739 // We *MUST* have an explicit copy ctor so that the ValTy thinks that this
740 // PointerValType owns it, not the old one!
742 PointerValType(const PointerValType &PVT)
743 : ValTypeBase<PointerValType, PointerType>(PVT), ValTy(PVT.ValTy, this) {}
745 // Subclass should override this... to update self as usual
746 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
747 assert(ValTy == OldType);
751 virtual void typeBecameConcrete(const DerivedType *Ty) {
752 assert(ValTy == Ty &&
753 "Contained type became concrete but we're not using it!");
754 ValTy.removeUserFromConcrete();
757 inline bool operator<(const PointerValType &MTV) const {
758 return ValTy.get() < MTV.ValTy.get();
762 static TypeMap<PointerValType, PointerType> PointerTypes;
764 PointerType *PointerType::get(const Type *ValueType) {
765 assert(ValueType && "Can't get a pointer to <null> type!");
766 PointerValType PVT(ValueType, PointerTypes);
768 PointerType *PT = PointerTypes.get(PVT);
771 // Value not found. Derive a new type!
772 PointerTypes.add(PVT, PT = new PointerType(ValueType));
774 #ifdef DEBUG_MERGE_TYPES
775 std::cerr << "Derived new type: " << PT->getDescription() << "\n";
780 void debug_type_tables() {
781 FunctionTypes.dump();
788 //===----------------------------------------------------------------------===//
789 // Derived Type Refinement Functions
790 //===----------------------------------------------------------------------===//
792 // addAbstractTypeUser - Notify an abstract type that there is a new user of
793 // it. This function is called primarily by the PATypeHandle class.
795 void DerivedType::addAbstractTypeUser(AbstractTypeUser *U) const {
796 assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
798 #if DEBUG_MERGE_TYPES
799 std::cerr << " addAbstractTypeUser[" << (void*)this << ", "
800 << getDescription() << "][" << AbstractTypeUsers.size()
801 << "] User = " << U << "\n";
803 AbstractTypeUsers.push_back(U);
807 // removeAbstractTypeUser - Notify an abstract type that a user of the class
808 // no longer has a handle to the type. This function is called primarily by
809 // the PATypeHandle class. When there are no users of the abstract type, it
810 // is anihilated, because there is no way to get a reference to it ever again.
812 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
813 // Search from back to front because we will notify users from back to
814 // front. Also, it is likely that there will be a stack like behavior to
815 // users that register and unregister users.
818 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
819 assert(i != 0 && "AbstractTypeUser not in user list!");
821 --i; // Convert to be in range 0 <= i < size()
822 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
824 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
826 #ifdef DEBUG_MERGE_TYPES
827 std::cerr << " remAbstractTypeUser[" << (void*)this << ", "
828 << getDescription() << "][" << i << "] User = " << U << "\n";
831 if (AbstractTypeUsers.empty() && isAbstract()) {
832 #ifdef DEBUG_MERGE_TYPES
833 std::cerr << "DELETEing unused abstract type: <" << getDescription()
834 << ">[" << (void*)this << "]" << "\n";
836 delete this; // No users of this abstract type!
841 // refineAbstractTypeTo - This function is used to when it is discovered that
842 // the 'this' abstract type is actually equivalent to the NewType specified.
843 // This causes all users of 'this' to switch to reference the more concrete
844 // type NewType and for 'this' to be deleted.
846 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
847 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
848 assert(this != NewType && "Can't refine to myself!");
850 #ifdef DEBUG_MERGE_TYPES
851 std::cerr << "REFINING abstract type [" << (void*)this << " "
852 << getDescription() << "] to [" << (void*)NewType << " "
853 << NewType->getDescription() << "]!\n";
857 // Make sure to put the type to be refined to into a holder so that if IT gets
858 // refined, that we will not continue using a dead reference...
860 PATypeHolder NewTy(NewType);
862 // Add a self use of the current type so that we don't delete ourself until
863 // after this while loop. We are careful to never invoke refine on ourself,
864 // so this extra reference shouldn't be a problem. Note that we must only
865 // remove a single reference at the end, but we must tolerate multiple self
866 // references because we could be refineAbstractTypeTo'ing recursively on the
869 addAbstractTypeUser(this);
871 // Count the number of self uses. Stop looping when sizeof(list) == NSU.
872 unsigned NumSelfUses = 0;
874 // Iterate over all of the uses of this type, invoking callback. Each user
875 // should remove itself from our use list automatically. We have to check to
876 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
877 // will not cause users to drop off of the use list. If we resolve to ourself
880 while (AbstractTypeUsers.size() > NumSelfUses && NewTy != this) {
881 AbstractTypeUser *User = AbstractTypeUsers.back();
884 // Move self use to the start of the list. Increment NSU.
885 std::swap(AbstractTypeUsers.back(), AbstractTypeUsers[NumSelfUses++]);
887 unsigned OldSize = AbstractTypeUsers.size();
888 #ifdef DEBUG_MERGE_TYPES
889 std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
890 << "] of abstract type [" << (void*)this << " "
891 << getDescription() << "] to [" << (void*)NewTy.get() << " "
892 << NewTy->getDescription() << "]!\n";
894 User->refineAbstractType(this, NewTy);
896 #ifdef DEBUG_MERGE_TYPES
897 if (AbstractTypeUsers.size() == OldSize) {
898 User->refineAbstractType(this, NewTy);
899 if (AbstractTypeUsers.back() != User)
900 std::cerr << "User changed!\n";
901 std::cerr << "Top of user list is:\n";
902 AbstractTypeUsers.back()->dump();
904 std::cerr <<"\nOld User=\n";
908 assert(AbstractTypeUsers.size() != OldSize &&
909 "AbsTyUser did not remove self from user list!");
913 // Remove a single self use, even though there may be several here. This will
914 // probably 'delete this', so no instance variables may be used after this
917 assert((NewTy == this || AbstractTypeUsers.back() == this) &&
918 "Only self uses should be left!");
919 removeAbstractTypeUser(this);
922 // typeIsRefined - Notify AbstractTypeUsers of this type that the current type
923 // has been refined a bit. The pointer is still valid and still should be
924 // used, but the subtypes have changed.
926 void DerivedType::typeIsRefined() {
927 assert(isRefining >= 0 && isRefining <= 2 && "isRefining out of bounds!");
928 if (isRefining == 1) return; // Kill recursion here...
931 #ifdef DEBUG_MERGE_TYPES
932 std::cerr << "typeIsREFINED type: " << (void*)this <<" "<<getDescription()
936 // In this loop we have to be very careful not to get into infinite loops and
937 // other problem cases. Specifically, we loop through all of the abstract
938 // type users in the user list, notifying them that the type has been refined.
939 // At their choice, they may or may not choose to remove themselves from the
940 // list of users. Regardless of whether they do or not, we have to be sure
941 // that we only notify each user exactly once. Because the refineAbstractType
942 // method can cause an arbitrary permutation to the user list, we cannot loop
943 // through it in any particular order and be guaranteed that we will be
944 // successful at this aim. Because of this, we keep track of all the users we
945 // have visited and only visit users we have not seen. Because this user list
946 // should be small, we use a vector instead of a full featured set to keep
947 // track of what users we have notified so far.
949 std::vector<AbstractTypeUser*> Refined;
952 for (i = AbstractTypeUsers.size(); i != 0; --i)
953 if (find(Refined.begin(), Refined.end(), AbstractTypeUsers[i-1]) ==
955 break; // Found an unrefined user?
957 if (i == 0) break; // Noone to refine left, break out of here!
959 AbstractTypeUser *ATU = AbstractTypeUsers[--i];
960 Refined.push_back(ATU); // Keep track of which users we have refined!
962 #ifdef DEBUG_MERGE_TYPES
963 std::cerr << " typeIsREFINED user " << i << "[" << ATU
964 << "] of abstract type [" << (void*)this << " "
965 << getDescription() << "]\n";
967 ATU->refineAbstractType(this, this);
973 if (!(isAbstract() || AbstractTypeUsers.empty()))
974 for (unsigned i = 0; i < AbstractTypeUsers.size(); ++i) {
975 if (AbstractTypeUsers[i] != this) {
977 std::cerr << "FOUND FAILURE\nUser: ";
978 AbstractTypeUsers[i]->dump();
979 std::cerr << "\nCatch:\n";
980 AbstractTypeUsers[i]->refineAbstractType(this, this);
981 assert(0 && "Type became concrete,"
982 " but it still has abstract type users hanging around!");
991 // refineAbstractType - Called when a contained type is found to be more
992 // concrete - this could potentially change us from an abstract type to a
995 void FunctionType::refineAbstractType(const DerivedType *OldType,
996 const Type *NewType) {
997 #ifdef DEBUG_MERGE_TYPES
998 std::cerr << "FunctionTy::refineAbstractTy(" << (void*)OldType << "["
999 << OldType->getDescription() << "], " << (void*)NewType << " ["
1000 << NewType->getDescription() << "])\n";
1002 // Find the type element we are refining...
1003 if (ResultType == OldType) {
1004 ResultType.removeUserFromConcrete();
1005 ResultType = NewType;
1007 for (unsigned i = 0, e = ParamTys.size(); i != e; ++i)
1008 if (ParamTys[i] == OldType) {
1009 ParamTys[i].removeUserFromConcrete();
1010 ParamTys[i] = NewType;
1013 const FunctionType *MT = FunctionTypes.containsEquivalent(this);
1014 if (MT && MT != this) {
1015 refineAbstractTypeTo(MT); // Different type altogether...
1017 setDerivedTypeProperties(); // Update the name and isAbstract
1018 typeIsRefined(); // Same type, different contents...
1023 // refineAbstractType - Called when a contained type is found to be more
1024 // concrete - this could potentially change us from an abstract type to a
1027 void ArrayType::refineAbstractType(const DerivedType *OldType,
1028 const Type *NewType) {
1029 #ifdef DEBUG_MERGE_TYPES
1030 std::cerr << "ArrayTy::refineAbstractTy(" << (void*)OldType << "["
1031 << OldType->getDescription() << "], " << (void*)NewType << " ["
1032 << NewType->getDescription() << "])\n";
1035 assert(getElementType() == OldType);
1036 ElementType.removeUserFromConcrete();
1037 ElementType = NewType;
1039 const ArrayType *AT = ArrayTypes.containsEquivalent(this);
1040 if (AT && AT != this) {
1041 refineAbstractTypeTo(AT); // Different type altogether...
1043 setDerivedTypeProperties(); // Update the name and isAbstract
1044 typeIsRefined(); // Same type, different contents...
1049 // refineAbstractType - Called when a contained type is found to be more
1050 // concrete - this could potentially change us from an abstract type to a
1053 void StructType::refineAbstractType(const DerivedType *OldType,
1054 const Type *NewType) {
1055 #ifdef DEBUG_MERGE_TYPES
1056 std::cerr << "StructTy::refineAbstractTy(" << (void*)OldType << "["
1057 << OldType->getDescription() << "], " << (void*)NewType << " ["
1058 << NewType->getDescription() << "])\n";
1060 for (int i = ETypes.size()-1; i >= 0; --i)
1061 if (ETypes[i] == OldType) {
1062 ETypes[i].removeUserFromConcrete();
1064 // Update old type to new type in the array...
1065 ETypes[i] = NewType;
1068 const StructType *ST = StructTypes.containsEquivalent(this);
1069 if (ST && ST != this) {
1070 refineAbstractTypeTo(ST); // Different type altogether...
1072 setDerivedTypeProperties(); // Update the name and isAbstract
1073 typeIsRefined(); // Same type, different contents...
1077 // refineAbstractType - Called when a contained type is found to be more
1078 // concrete - this could potentially change us from an abstract type to a
1081 void PointerType::refineAbstractType(const DerivedType *OldType,
1082 const Type *NewType) {
1083 #ifdef DEBUG_MERGE_TYPES
1084 std::cerr << "PointerTy::refineAbstractTy(" << (void*)OldType << "["
1085 << OldType->getDescription() << "], " << (void*)NewType << " ["
1086 << NewType->getDescription() << "])\n";
1089 assert(ElementType == OldType);
1090 ElementType.removeUserFromConcrete();
1091 ElementType = NewType;
1093 const PointerType *PT = PointerTypes.containsEquivalent(this);
1094 if (PT && PT != this) {
1095 refineAbstractTypeTo(PT); // Different type altogether...
1097 setDerivedTypeProperties(); // Update the name and isAbstract
1098 typeIsRefined(); // Same type, different contents...