1 //===-- Type.cpp - Implement the Type class -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Type class for the VMCore library.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/DerivedTypes.h"
15 #include "llvm/SymbolTable.h"
16 #include "llvm/Constants.h"
17 #include "Support/StringExtras.h"
18 #include "Support/STLExtras.h"
21 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
22 // created and later destroyed, all in an effort to make sure that there is only
23 // a single canonical version of a type.
25 //#define DEBUG_MERGE_TYPES 1
28 //===----------------------------------------------------------------------===//
29 // Type Class Implementation
30 //===----------------------------------------------------------------------===//
32 static unsigned CurUID = 0;
33 static std::vector<const Type *> UIDMappings;
35 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
36 // for types as they are needed. Because resolution of types must invalidate
37 // all of the abstract type descriptions, we keep them in a seperate map to make
39 static std::map<const Type*, std::string> ConcreteTypeDescriptions;
40 static std::map<const Type*, std::string> AbstractTypeDescriptions;
42 Type::Type(const std::string &name, PrimitiveID id)
43 : Value(Type::TypeTy, Value::TypeVal), ForwardType(0) {
45 ConcreteTypeDescriptions[this] = name;
48 UID = CurUID++; // Assign types UID's as they are created
49 UIDMappings.push_back(this);
52 void Type::setName(const std::string &Name, SymbolTable *ST) {
53 assert(ST && "Type::setName - Must provide symbol table argument!");
55 if (Name.size()) ST->insert(Name, this);
59 const Type *Type::getUniqueIDType(unsigned UID) {
60 assert(UID < UIDMappings.size() &&
61 "Type::getPrimitiveType: UID out of range!");
62 return UIDMappings[UID];
65 const Type *Type::getPrimitiveType(PrimitiveID IDNumber) {
67 case VoidTyID : return VoidTy;
68 case BoolTyID : return BoolTy;
69 case UByteTyID : return UByteTy;
70 case SByteTyID : return SByteTy;
71 case UShortTyID: return UShortTy;
72 case ShortTyID : return ShortTy;
73 case UIntTyID : return UIntTy;
74 case IntTyID : return IntTy;
75 case ULongTyID : return ULongTy;
76 case LongTyID : return LongTy;
77 case FloatTyID : return FloatTy;
78 case DoubleTyID: return DoubleTy;
79 case TypeTyID : return TypeTy;
80 case LabelTyID : return LabelTy;
86 // isLosslesslyConvertibleTo - Return true if this type can be converted to
87 // 'Ty' without any reinterpretation of bits. For example, uint to int.
89 bool Type::isLosslesslyConvertibleTo(const Type *Ty) const {
90 if (this == Ty) return true;
91 if ((!isPrimitiveType() && !isa<PointerType>(this)) ||
92 (!isa<PointerType>(Ty) && !Ty->isPrimitiveType())) return false;
94 if (getPrimitiveID() == Ty->getPrimitiveID())
95 return true; // Handles identity cast, and cast of differing pointer types
97 // Now we know that they are two differing primitive or pointer types
98 switch (getPrimitiveID()) {
99 case Type::UByteTyID: return Ty == Type::SByteTy;
100 case Type::SByteTyID: return Ty == Type::UByteTy;
101 case Type::UShortTyID: return Ty == Type::ShortTy;
102 case Type::ShortTyID: return Ty == Type::UShortTy;
103 case Type::UIntTyID: return Ty == Type::IntTy;
104 case Type::IntTyID: return Ty == Type::UIntTy;
105 case Type::ULongTyID:
107 case Type::PointerTyID:
108 return Ty == Type::ULongTy || Ty == Type::LongTy || isa<PointerType>(Ty);
110 return false; // Other types have no identity values
114 // getPrimitiveSize - Return the basic size of this type if it is a primitive
115 // type. These are fixed by LLVM and are not target dependent. This will
116 // return zero if the type does not have a size or is not a primitive type.
118 unsigned Type::getPrimitiveSize() const {
119 switch (getPrimitiveID()) {
120 #define HANDLE_PRIM_TYPE(TY,SIZE) case TY##TyID: return SIZE;
121 #include "llvm/Type.def"
127 /// getForwardedTypeInternal - This method is used to implement the union-find
128 /// algorithm for when a type is being forwarded to another type.
129 const Type *Type::getForwardedTypeInternal() const {
130 assert(ForwardType && "This type is not being forwarded to another type!");
132 // Check to see if the forwarded type has been forwarded on. If so, collapse
133 // the forwarding links.
134 const Type *RealForwardedType = ForwardType->getForwardedType();
135 if (!RealForwardedType)
136 return ForwardType; // No it's not forwarded again
138 // Yes, it is forwarded again. First thing, add the reference to the new
140 if (RealForwardedType->isAbstract())
141 cast<DerivedType>(RealForwardedType)->addRef();
143 // Now drop the old reference. This could cause ForwardType to get deleted.
144 cast<DerivedType>(ForwardType)->dropRef();
146 // Return the updated type.
147 ForwardType = RealForwardedType;
151 // getTypeDescription - This is a recursive function that walks a type hierarchy
152 // calculating the description for a type.
154 static std::string getTypeDescription(const Type *Ty,
155 std::vector<const Type *> &TypeStack) {
156 if (isa<OpaqueType>(Ty)) { // Base case for the recursion
157 std::map<const Type*, std::string>::iterator I =
158 AbstractTypeDescriptions.lower_bound(Ty);
159 if (I != AbstractTypeDescriptions.end() && I->first == Ty)
161 std::string Desc = "opaque"+utostr(Ty->getUniqueID());
162 AbstractTypeDescriptions.insert(std::make_pair(Ty, Desc));
166 if (!Ty->isAbstract()) { // Base case for the recursion
167 std::map<const Type*, std::string>::iterator I =
168 ConcreteTypeDescriptions.find(Ty);
169 if (I != ConcreteTypeDescriptions.end()) return I->second;
172 // Check to see if the Type is already on the stack...
173 unsigned Slot = 0, CurSize = TypeStack.size();
174 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
176 // This is another base case for the recursion. In this case, we know
177 // that we have looped back to a type that we have previously visited.
178 // Generate the appropriate upreference to handle this.
181 return "\\" + utostr(CurSize-Slot); // Here's the upreference
183 // Recursive case: derived types...
185 TypeStack.push_back(Ty); // Add us to the stack..
187 switch (Ty->getPrimitiveID()) {
188 case Type::FunctionTyID: {
189 const FunctionType *FTy = cast<FunctionType>(Ty);
190 Result = getTypeDescription(FTy->getReturnType(), TypeStack) + " (";
191 for (FunctionType::ParamTypes::const_iterator
192 I = FTy->getParamTypes().begin(),
193 E = FTy->getParamTypes().end(); I != E; ++I) {
194 if (I != FTy->getParamTypes().begin())
196 Result += getTypeDescription(*I, TypeStack);
198 if (FTy->isVarArg()) {
199 if (!FTy->getParamTypes().empty()) Result += ", ";
205 case Type::StructTyID: {
206 const StructType *STy = cast<StructType>(Ty);
208 for (StructType::ElementTypes::const_iterator
209 I = STy->getElementTypes().begin(),
210 E = STy->getElementTypes().end(); I != E; ++I) {
211 if (I != STy->getElementTypes().begin())
213 Result += getTypeDescription(*I, TypeStack);
218 case Type::PointerTyID: {
219 const PointerType *PTy = cast<PointerType>(Ty);
220 Result = getTypeDescription(PTy->getElementType(), TypeStack) + " *";
223 case Type::ArrayTyID: {
224 const ArrayType *ATy = cast<ArrayType>(Ty);
225 unsigned NumElements = ATy->getNumElements();
227 Result += utostr(NumElements) + " x ";
228 Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
233 assert(0 && "Unhandled type in getTypeDescription!");
236 TypeStack.pop_back(); // Remove self from stack...
243 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
245 std::map<const Type*, std::string>::iterator I = Map.find(Ty);
246 if (I != Map.end()) return I->second;
248 std::vector<const Type *> TypeStack;
249 return Map[Ty] = getTypeDescription(Ty, TypeStack);
253 const std::string &Type::getDescription() const {
255 return getOrCreateDesc(AbstractTypeDescriptions, this);
257 return getOrCreateDesc(ConcreteTypeDescriptions, this);
261 bool StructType::indexValid(const Value *V) const {
262 if (!isa<Constant>(V)) return false;
263 if (V->getType() != Type::UByteTy) return false;
264 unsigned Idx = cast<ConstantUInt>(V)->getValue();
265 return Idx < ETypes.size();
268 // getTypeAtIndex - Given an index value into the type, return the type of the
269 // element. For a structure type, this must be a constant value...
271 const Type *StructType::getTypeAtIndex(const Value *V) const {
272 assert(isa<Constant>(V) && "Structure index must be a constant!!");
273 assert(V->getType() == Type::UByteTy && "Structure index must be ubyte!");
274 unsigned Idx = cast<ConstantUInt>(V)->getValue();
275 assert(Idx < ETypes.size() && "Structure index out of range!");
276 assert(indexValid(V) && "Invalid structure index!"); // Duplicate check
282 //===----------------------------------------------------------------------===//
284 //===----------------------------------------------------------------------===//
286 // These classes are used to implement specialized behavior for each different
289 struct SignedIntType : public Type {
290 SignedIntType(const std::string &Name, PrimitiveID id) : Type(Name, id) {}
292 // isSigned - Return whether a numeric type is signed.
293 virtual bool isSigned() const { return 1; }
295 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
296 // virtual function invocation.
298 virtual bool isInteger() const { return 1; }
301 struct UnsignedIntType : public Type {
302 UnsignedIntType(const std::string &N, PrimitiveID id) : Type(N, id) {}
304 // isUnsigned - Return whether a numeric type is signed.
305 virtual bool isUnsigned() const { return 1; }
307 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
308 // virtual function invocation.
310 virtual bool isInteger() const { return 1; }
313 struct OtherType : public Type {
314 OtherType(const std::string &N, PrimitiveID id) : Type(N, id) {}
317 static struct TypeType : public Type {
318 TypeType() : Type("type", TypeTyID) {}
319 } TheTypeTy; // Implement the type that is global.
322 //===----------------------------------------------------------------------===//
323 // Static 'Type' data
324 //===----------------------------------------------------------------------===//
326 static OtherType TheVoidTy ("void" , Type::VoidTyID);
327 static OtherType TheBoolTy ("bool" , Type::BoolTyID);
328 static SignedIntType TheSByteTy ("sbyte" , Type::SByteTyID);
329 static UnsignedIntType TheUByteTy ("ubyte" , Type::UByteTyID);
330 static SignedIntType TheShortTy ("short" , Type::ShortTyID);
331 static UnsignedIntType TheUShortTy("ushort", Type::UShortTyID);
332 static SignedIntType TheIntTy ("int" , Type::IntTyID);
333 static UnsignedIntType TheUIntTy ("uint" , Type::UIntTyID);
334 static SignedIntType TheLongTy ("long" , Type::LongTyID);
335 static UnsignedIntType TheULongTy ("ulong" , Type::ULongTyID);
336 static OtherType TheFloatTy ("float" , Type::FloatTyID);
337 static OtherType TheDoubleTy("double", Type::DoubleTyID);
338 static OtherType TheLabelTy ("label" , Type::LabelTyID);
340 Type *Type::VoidTy = &TheVoidTy;
341 Type *Type::BoolTy = &TheBoolTy;
342 Type *Type::SByteTy = &TheSByteTy;
343 Type *Type::UByteTy = &TheUByteTy;
344 Type *Type::ShortTy = &TheShortTy;
345 Type *Type::UShortTy = &TheUShortTy;
346 Type *Type::IntTy = &TheIntTy;
347 Type *Type::UIntTy = &TheUIntTy;
348 Type *Type::LongTy = &TheLongTy;
349 Type *Type::ULongTy = &TheULongTy;
350 Type *Type::FloatTy = &TheFloatTy;
351 Type *Type::DoubleTy = &TheDoubleTy;
352 Type *Type::TypeTy = &TheTypeTy;
353 Type *Type::LabelTy = &TheLabelTy;
356 //===----------------------------------------------------------------------===//
357 // Derived Type Constructors
358 //===----------------------------------------------------------------------===//
360 FunctionType::FunctionType(const Type *Result,
361 const std::vector<const Type*> &Params,
362 bool IsVarArgs) : DerivedType(FunctionTyID),
363 ResultType(PATypeHandle(Result, this)),
364 isVarArgs(IsVarArgs) {
365 bool isAbstract = Result->isAbstract();
366 ParamTys.reserve(Params.size());
367 for (unsigned i = 0; i < Params.size(); ++i) {
368 ParamTys.push_back(PATypeHandle(Params[i], this));
369 isAbstract |= Params[i]->isAbstract();
372 // Calculate whether or not this type is abstract
373 setAbstract(isAbstract);
376 StructType::StructType(const std::vector<const Type*> &Types)
377 : CompositeType(StructTyID) {
378 ETypes.reserve(Types.size());
379 bool isAbstract = false;
380 for (unsigned i = 0; i < Types.size(); ++i) {
381 assert(Types[i] != Type::VoidTy && "Void type in method prototype!!");
382 ETypes.push_back(PATypeHandle(Types[i], this));
383 isAbstract |= Types[i]->isAbstract();
386 // Calculate whether or not this type is abstract
387 setAbstract(isAbstract);
390 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
391 : SequentialType(ArrayTyID, ElType) {
394 // Calculate whether or not this type is abstract
395 setAbstract(ElType->isAbstract());
398 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
399 // Calculate whether or not this type is abstract
400 setAbstract(E->isAbstract());
403 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
405 #ifdef DEBUG_MERGE_TYPES
406 std::cerr << "Derived new type: " << *this << "\n";
411 // getAlwaysOpaqueTy - This function returns an opaque type. It doesn't matter
412 // _which_ opaque type it is, but the opaque type must never get resolved.
414 static Type *getAlwaysOpaqueTy() {
415 static Type *AlwaysOpaqueTy = OpaqueType::get();
416 static PATypeHolder Holder(AlwaysOpaqueTy);
417 return AlwaysOpaqueTy;
421 //===----------------------------------------------------------------------===//
422 // dropAllTypeUses methods - These methods eliminate any possibly recursive type
423 // references from a derived type. The type must remain abstract, so we make
424 // sure to use an always opaque type as an argument.
427 void FunctionType::dropAllTypeUses() {
428 ResultType = getAlwaysOpaqueTy();
432 void ArrayType::dropAllTypeUses() {
433 ElementType = getAlwaysOpaqueTy();
436 void StructType::dropAllTypeUses() {
438 ETypes.push_back(PATypeHandle(getAlwaysOpaqueTy(), this));
441 void PointerType::dropAllTypeUses() {
442 ElementType = getAlwaysOpaqueTy();
448 // isTypeAbstract - This is a recursive function that walks a type hierarchy
449 // calculating whether or not a type is abstract. Worst case it will have to do
450 // a lot of traversing if you have some whacko opaque types, but in most cases,
451 // it will do some simple stuff when it hits non-abstract types that aren't
454 bool Type::isTypeAbstract() {
455 if (!isAbstract()) // Base case for the recursion
456 return false; // Primitive = leaf type
458 if (isa<OpaqueType>(this)) // Base case for the recursion
459 return true; // This whole type is abstract!
461 // We have to guard against recursion. To do this, we temporarily mark this
462 // type as concrete, so that if we get back to here recursively we will think
463 // it's not abstract, and thus not scan it again.
466 // Scan all of the sub-types. If any of them are abstract, than so is this
468 for (Type::subtype_iterator I = subtype_begin(), E = subtype_end();
470 if (const_cast<Type*>(*I)->isTypeAbstract()) {
471 setAbstract(true); // Restore the abstract bit.
472 return true; // This type is abstract if subtype is abstract!
475 // Restore the abstract bit.
478 // Nothing looks abstract here...
483 //===----------------------------------------------------------------------===//
484 // Type Structural Equality Testing
485 //===----------------------------------------------------------------------===//
487 // TypesEqual - Two types are considered structurally equal if they have the
488 // same "shape": Every level and element of the types have identical primitive
489 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
490 // be pointer equals to be equivalent though. This uses an optimistic algorithm
491 // that assumes that two graphs are the same until proven otherwise.
493 static bool TypesEqual(const Type *Ty, const Type *Ty2,
494 std::map<const Type *, const Type *> &EqTypes) {
495 if (Ty == Ty2) return true;
496 if (Ty->getPrimitiveID() != Ty2->getPrimitiveID()) return false;
497 if (Ty->isPrimitiveType()) return true;
498 if (isa<OpaqueType>(Ty))
499 return false; // Two unequal opaque types are never equal
501 std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
502 if (It != EqTypes.end() && It->first == Ty)
503 return It->second == Ty2; // Looping back on a type, check for equality
505 // Otherwise, add the mapping to the table to make sure we don't get
506 // recursion on the types...
507 EqTypes.insert(It, std::make_pair(Ty, Ty2));
509 // Two really annoying special cases that breaks an otherwise nice simple
510 // algorithm is the fact that arraytypes have sizes that differentiates types,
511 // and that function types can be varargs or not. Consider this now.
513 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
514 return TypesEqual(PTy->getElementType(),
515 cast<PointerType>(Ty2)->getElementType(), EqTypes);
516 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
517 const StructType::ElementTypes &STyE = STy->getElementTypes();
518 const StructType::ElementTypes &STyE2 =
519 cast<StructType>(Ty2)->getElementTypes();
520 if (STyE.size() != STyE2.size()) return false;
521 for (unsigned i = 0, e = STyE.size(); i != e; ++i)
522 if (!TypesEqual(STyE[i], STyE2[i], EqTypes))
525 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
526 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
527 return ATy->getNumElements() == ATy2->getNumElements() &&
528 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
529 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
530 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
531 if (FTy->isVarArg() != FTy2->isVarArg() ||
532 FTy->getParamTypes().size() != FTy2->getParamTypes().size() ||
533 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
535 const FunctionType::ParamTypes &FTyP = FTy->getParamTypes();
536 const FunctionType::ParamTypes &FTy2P = FTy2->getParamTypes();
537 for (unsigned i = 0, e = FTyP.size(); i != e; ++i)
538 if (!TypesEqual(FTyP[i], FTy2P[i], EqTypes))
542 assert(0 && "Unknown derived type!");
547 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
548 std::map<const Type *, const Type *> EqTypes;
549 return TypesEqual(Ty, Ty2, EqTypes);
554 //===----------------------------------------------------------------------===//
555 // Derived Type Factory Functions
556 //===----------------------------------------------------------------------===//
558 // TypeMap - Make sure that only one instance of a particular type may be
559 // created on any given run of the compiler... note that this involves updating
560 // our map if an abstract type gets refined somehow...
562 template<class ValType, class TypeClass>
564 typedef std::map<ValType, TypeClass *> MapTy;
567 typedef typename MapTy::iterator iterator;
568 ~TypeMap() { print("ON EXIT"); }
570 inline TypeClass *get(const ValType &V) {
571 iterator I = Map.find(V);
572 return I != Map.end() ? I->second : 0;
575 inline void add(const ValType &V, TypeClass *T) {
576 Map.insert(std::make_pair(V, T));
580 iterator getEntryForType(TypeClass *Ty) {
581 iterator I = Map.find(ValType::get(Ty));
582 if (I == Map.end()) print("ERROR!");
583 assert(I != Map.end() && "Didn't find type entry!");
584 assert(I->second == Ty && "Type entry wrong?");
589 void finishRefinement(iterator TyIt) {
590 TypeClass *Ty = TyIt->second;
592 // The old record is now out-of-date, because one of the children has been
593 // updated. Remove the obsolete entry from the map.
596 // Now we check to see if there is an existing entry in the table which is
597 // structurally identical to the newly refined type. If so, this type gets
598 // refined to the pre-existing type.
600 for (iterator I = Map.begin(), E = Map.end(); I != E; ++I)
601 if (TypesEqual(Ty, I->second)) {
602 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
603 TypeClass *NewTy = I->second;
605 // Refined to a different type altogether?
606 Ty->refineAbstractTypeTo(NewTy);
610 // If there is no existing type of the same structure, we reinsert an
611 // updated record into the map.
612 Map.insert(std::make_pair(ValType::get(Ty), Ty));
614 // If the type is currently thought to be abstract, rescan all of our
615 // subtypes to see if the type has just become concrete!
616 if (Ty->isAbstract()) {
617 Ty->setAbstract(Ty->isTypeAbstract());
619 // If the type just became concrete, notify all users!
620 if (!Ty->isAbstract())
621 Ty->notifyUsesThatTypeBecameConcrete();
625 void remove(const ValType &OldVal) {
626 iterator I = Map.find(OldVal);
627 assert(I != Map.end() && "TypeMap::remove, element not found!");
631 void remove(iterator I) {
632 assert(I != Map.end() && "Cannot remove invalid iterator pointer!");
636 void print(const char *Arg) const {
637 #ifdef DEBUG_MERGE_TYPES
638 std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
640 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
642 std::cerr << " " << (++i) << ". " << (void*)I->second << " "
643 << *I->second << "\n";
647 void dump() const { print("dump output"); }
652 //===----------------------------------------------------------------------===//
653 // Function Type Factory and Value Class...
656 // FunctionValType - Define a class to hold the key that goes into the TypeMap
658 class FunctionValType {
660 std::vector<const Type*> ArgTypes;
663 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
664 bool IVA) : RetTy(ret), isVarArg(IVA) {
665 for (unsigned i = 0; i < args.size(); ++i)
666 ArgTypes.push_back(args[i]);
669 static FunctionValType get(const FunctionType *FT);
671 // Subclass should override this... to update self as usual
672 void doRefinement(const DerivedType *OldType, const Type *NewType) {
673 if (RetTy == OldType) RetTy = NewType;
674 for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
675 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
678 inline bool operator<(const FunctionValType &MTV) const {
679 if (RetTy < MTV.RetTy) return true;
680 if (RetTy > MTV.RetTy) return false;
682 if (ArgTypes < MTV.ArgTypes) return true;
683 return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
687 // Define the actual map itself now...
688 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
690 FunctionValType FunctionValType::get(const FunctionType *FT) {
691 // Build up a FunctionValType
692 std::vector<const Type *> ParamTypes;
693 ParamTypes.reserve(FT->getParamTypes().size());
694 for (unsigned i = 0, e = FT->getParamTypes().size(); i != e; ++i)
695 ParamTypes.push_back(FT->getParamType(i));
696 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
700 // FunctionType::get - The factory function for the FunctionType class...
701 FunctionType *FunctionType::get(const Type *ReturnType,
702 const std::vector<const Type*> &Params,
704 FunctionValType VT(ReturnType, Params, isVarArg);
705 FunctionType *MT = FunctionTypes.get(VT);
708 FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
710 #ifdef DEBUG_MERGE_TYPES
711 std::cerr << "Derived new type: " << MT << "\n";
716 //===----------------------------------------------------------------------===//
717 // Array Type Factory...
723 ArrayValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
725 static ArrayValType get(const ArrayType *AT) {
726 return ArrayValType(AT->getElementType(), AT->getNumElements());
729 // Subclass should override this... to update self as usual
730 void doRefinement(const DerivedType *OldType, const Type *NewType) {
731 assert(ValTy == OldType);
735 inline bool operator<(const ArrayValType &MTV) const {
736 if (Size < MTV.Size) return true;
737 return Size == MTV.Size && ValTy < MTV.ValTy;
741 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
744 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
745 assert(ElementType && "Can't get array of null types!");
747 ArrayValType AVT(ElementType, NumElements);
748 ArrayType *AT = ArrayTypes.get(AVT);
749 if (AT) return AT; // Found a match, return it!
751 // Value not found. Derive a new type!
752 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
754 #ifdef DEBUG_MERGE_TYPES
755 std::cerr << "Derived new type: " << *AT << "\n";
760 //===----------------------------------------------------------------------===//
761 // Struct Type Factory...
764 // StructValType - Define a class to hold the key that goes into the TypeMap
766 class StructValType {
767 std::vector<const Type*> ElTypes;
769 StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
771 static StructValType get(const StructType *ST) {
772 std::vector<const Type *> ElTypes;
773 ElTypes.reserve(ST->getElementTypes().size());
774 for (unsigned i = 0, e = ST->getElementTypes().size(); i != e; ++i)
775 ElTypes.push_back(ST->getElementTypes()[i]);
777 return StructValType(ElTypes);
780 // Subclass should override this... to update self as usual
781 void doRefinement(const DerivedType *OldType, const Type *NewType) {
782 for (unsigned i = 0; i < ElTypes.size(); ++i)
783 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
786 inline bool operator<(const StructValType &STV) const {
787 return ElTypes < STV.ElTypes;
791 static TypeMap<StructValType, StructType> StructTypes;
793 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
794 StructValType STV(ETypes);
795 StructType *ST = StructTypes.get(STV);
798 // Value not found. Derive a new type!
799 StructTypes.add(STV, ST = new StructType(ETypes));
801 #ifdef DEBUG_MERGE_TYPES
802 std::cerr << "Derived new type: " << *ST << "\n";
809 //===----------------------------------------------------------------------===//
810 // Pointer Type Factory...
813 // PointerValType - Define a class to hold the key that goes into the TypeMap
815 class PointerValType {
818 PointerValType(const Type *val) : ValTy(val) {}
820 static PointerValType get(const PointerType *PT) {
821 return PointerValType(PT->getElementType());
824 // Subclass should override this... to update self as usual
825 void doRefinement(const DerivedType *OldType, const Type *NewType) {
826 assert(ValTy == OldType);
830 bool operator<(const PointerValType &MTV) const {
831 return ValTy < MTV.ValTy;
835 static TypeMap<PointerValType, PointerType> PointerTypes;
837 PointerType *PointerType::get(const Type *ValueType) {
838 assert(ValueType && "Can't get a pointer to <null> type!");
839 PointerValType PVT(ValueType);
841 PointerType *PT = PointerTypes.get(PVT);
844 // Value not found. Derive a new type!
845 PointerTypes.add(PVT, PT = new PointerType(ValueType));
847 #ifdef DEBUG_MERGE_TYPES
848 std::cerr << "Derived new type: " << *PT << "\n";
853 void debug_type_tables() {
854 FunctionTypes.dump();
861 //===----------------------------------------------------------------------===//
862 // Derived Type Refinement Functions
863 //===----------------------------------------------------------------------===//
865 // removeAbstractTypeUser - Notify an abstract type that a user of the class
866 // no longer has a handle to the type. This function is called primarily by
867 // the PATypeHandle class. When there are no users of the abstract type, it
868 // is annihilated, because there is no way to get a reference to it ever again.
870 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
871 // Search from back to front because we will notify users from back to
872 // front. Also, it is likely that there will be a stack like behavior to
873 // users that register and unregister users.
876 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
877 assert(i != 0 && "AbstractTypeUser not in user list!");
879 --i; // Convert to be in range 0 <= i < size()
880 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
882 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
884 #ifdef DEBUG_MERGE_TYPES
885 std::cerr << " remAbstractTypeUser[" << (void*)this << ", "
886 << *this << "][" << i << "] User = " << U << "\n";
889 if (AbstractTypeUsers.empty() && RefCount == 0 && isAbstract()) {
890 #ifdef DEBUG_MERGE_TYPES
891 std::cerr << "DELETEing unused abstract type: <" << *this
892 << ">[" << (void*)this << "]" << "\n";
894 delete this; // No users of this abstract type!
899 // refineAbstractTypeTo - This function is used to when it is discovered that
900 // the 'this' abstract type is actually equivalent to the NewType specified.
901 // This causes all users of 'this' to switch to reference the more concrete type
902 // NewType and for 'this' to be deleted.
904 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
905 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
906 assert(this != NewType && "Can't refine to myself!");
907 assert(ForwardType == 0 && "This type has already been refined!");
909 // The descriptions may be out of date. Conservatively clear them all!
910 AbstractTypeDescriptions.clear();
912 #ifdef DEBUG_MERGE_TYPES
913 std::cerr << "REFINING abstract type [" << (void*)this << " "
914 << *this << "] to [" << (void*)NewType << " "
915 << *NewType << "]!\n";
918 // Make sure to put the type to be refined to into a holder so that if IT gets
919 // refined, that we will not continue using a dead reference...
921 PATypeHolder NewTy(NewType);
923 // Any PATypeHolders referring to this type will now automatically forward to
924 // the type we are resolved to.
925 ForwardType = NewType;
926 if (NewType->isAbstract())
927 cast<DerivedType>(NewType)->addRef();
929 // Add a self use of the current type so that we don't delete ourself until
930 // after the function exits.
932 PATypeHolder CurrentTy(this);
934 // To make the situation simpler, we ask the subclass to remove this type from
935 // the type map, and to replace any type uses with uses of non-abstract types.
936 // This dramatically limits the amount of recursive type trouble we can find
940 // Iterate over all of the uses of this type, invoking callback. Each user
941 // should remove itself from our use list automatically. We have to check to
942 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
943 // will not cause users to drop off of the use list. If we resolve to ourself
946 while (!AbstractTypeUsers.empty() && NewTy != this) {
947 AbstractTypeUser *User = AbstractTypeUsers.back();
949 unsigned OldSize = AbstractTypeUsers.size();
950 #ifdef DEBUG_MERGE_TYPES
951 std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
952 << "] of abstract type [" << (void*)this << " "
953 << *this << "] to [" << (void*)NewTy.get() << " "
956 User->refineAbstractType(this, NewTy);
958 assert(AbstractTypeUsers.size() != OldSize &&
959 "AbsTyUser did not remove self from user list!");
962 // If we were successful removing all users from the type, 'this' will be
963 // deleted when the last PATypeHolder is destroyed or updated from this type.
964 // This may occur on exit of this function, as the CurrentTy object is
968 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
969 // the current type has transitioned from being abstract to being concrete.
971 void DerivedType::notifyUsesThatTypeBecameConcrete() {
972 #ifdef DEBUG_MERGE_TYPES
973 std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
976 unsigned OldSize = AbstractTypeUsers.size();
977 while (!AbstractTypeUsers.empty()) {
978 AbstractTypeUser *ATU = AbstractTypeUsers.back();
979 ATU->typeBecameConcrete(this);
981 assert(AbstractTypeUsers.size() < OldSize-- &&
982 "AbstractTypeUser did not remove itself from the use list!");
989 // refineAbstractType - Called when a contained type is found to be more
990 // concrete - this could potentially change us from an abstract type to a
993 void FunctionType::refineAbstractType(const DerivedType *OldType,
994 const Type *NewType) {
995 assert((isAbstract() || !OldType->isAbstract()) &&
996 "Refining a non-abstract type!");
997 #ifdef DEBUG_MERGE_TYPES
998 std::cerr << "FunctionTy::refineAbstractTy(" << (void*)OldType << "["
999 << *OldType << "], " << (void*)NewType << " ["
1000 << *NewType << "])\n";
1003 // Look up our current type map entry..
1004 TypeMap<FunctionValType, FunctionType>::iterator TMI =
1005 FunctionTypes.getEntryForType(this);
1007 // Find the type element we are refining...
1008 if (ResultType == OldType) {
1009 ResultType.removeUserFromConcrete();
1010 ResultType = NewType;
1012 for (unsigned i = 0, e = ParamTys.size(); i != e; ++i)
1013 if (ParamTys[i] == OldType) {
1014 ParamTys[i].removeUserFromConcrete();
1015 ParamTys[i] = NewType;
1018 FunctionTypes.finishRefinement(TMI);
1021 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1022 refineAbstractType(AbsTy, AbsTy);
1026 // refineAbstractType - Called when a contained type is found to be more
1027 // concrete - this could potentially change us from an abstract type to a
1030 void ArrayType::refineAbstractType(const DerivedType *OldType,
1031 const Type *NewType) {
1032 assert((isAbstract() || !OldType->isAbstract()) &&
1033 "Refining a non-abstract type!");
1034 #ifdef DEBUG_MERGE_TYPES
1035 std::cerr << "ArrayTy::refineAbstractTy(" << (void*)OldType << "["
1036 << *OldType << "], " << (void*)NewType << " ["
1037 << *NewType << "])\n";
1040 // Look up our current type map entry..
1041 TypeMap<ArrayValType, ArrayType>::iterator TMI =
1042 ArrayTypes.getEntryForType(this);
1044 assert(getElementType() == OldType);
1045 ElementType.removeUserFromConcrete();
1046 ElementType = NewType;
1048 ArrayTypes.finishRefinement(TMI);
1051 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1052 refineAbstractType(AbsTy, AbsTy);
1056 // refineAbstractType - Called when a contained type is found to be more
1057 // concrete - this could potentially change us from an abstract type to a
1060 void StructType::refineAbstractType(const DerivedType *OldType,
1061 const Type *NewType) {
1062 assert((isAbstract() || !OldType->isAbstract()) &&
1063 "Refining a non-abstract type!");
1064 #ifdef DEBUG_MERGE_TYPES
1065 std::cerr << "StructTy::refineAbstractTy(" << (void*)OldType << "["
1066 << *OldType << "], " << (void*)NewType << " ["
1067 << *NewType << "])\n";
1070 // Look up our current type map entry..
1071 TypeMap<StructValType, StructType>::iterator TMI =
1072 StructTypes.getEntryForType(this);
1074 for (int i = ETypes.size()-1; i >= 0; --i)
1075 if (ETypes[i] == OldType) {
1076 ETypes[i].removeUserFromConcrete();
1078 // Update old type to new type in the array...
1079 ETypes[i] = NewType;
1082 StructTypes.finishRefinement(TMI);
1085 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1086 refineAbstractType(AbsTy, AbsTy);
1089 // refineAbstractType - Called when a contained type is found to be more
1090 // concrete - this could potentially change us from an abstract type to a
1093 void PointerType::refineAbstractType(const DerivedType *OldType,
1094 const Type *NewType) {
1095 assert((isAbstract() || !OldType->isAbstract()) &&
1096 "Refining a non-abstract type!");
1097 #ifdef DEBUG_MERGE_TYPES
1098 std::cerr << "PointerTy::refineAbstractTy(" << (void*)OldType << "["
1099 << *OldType << "], " << (void*)NewType << " ["
1100 << *NewType << "])\n";
1103 // Look up our current type map entry..
1104 TypeMap<PointerValType, PointerType>::iterator TMI =
1105 PointerTypes.getEntryForType(this);
1107 assert(ElementType == OldType);
1108 ElementType.removeUserFromConcrete();
1109 ElementType = NewType;
1111 PointerTypes.finishRefinement(TMI);
1114 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1115 refineAbstractType(AbsTy, AbsTy);