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/AbstractTypeUser.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/SymbolTable.h"
17 #include "llvm/Constants.h"
18 #include "llvm/ADT/DepthFirstIterator.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/STLExtras.h"
25 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
26 // created and later destroyed, all in an effort to make sure that there is only
27 // a single canonical version of a type.
29 //#define DEBUG_MERGE_TYPES 1
31 AbstractTypeUser::~AbstractTypeUser() {}
33 //===----------------------------------------------------------------------===//
34 // Type Class Implementation
35 //===----------------------------------------------------------------------===//
37 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
38 // for types as they are needed. Because resolution of types must invalidate
39 // all of the abstract type descriptions, we keep them in a seperate map to make
41 static std::map<const Type*, std::string> ConcreteTypeDescriptions;
42 static std::map<const Type*, std::string> AbstractTypeDescriptions;
44 Type::Type( const std::string& name, TypeID id )
45 : RefCount(0), ForwardType(0) {
47 ConcreteTypeDescriptions[this] = name;
52 const Type *Type::getPrimitiveType(TypeID IDNumber) {
54 case VoidTyID : return VoidTy;
55 case BoolTyID : return BoolTy;
56 case UByteTyID : return UByteTy;
57 case SByteTyID : return SByteTy;
58 case UShortTyID: return UShortTy;
59 case ShortTyID : return ShortTy;
60 case UIntTyID : return UIntTy;
61 case IntTyID : return IntTy;
62 case ULongTyID : return ULongTy;
63 case LongTyID : return LongTy;
64 case FloatTyID : return FloatTy;
65 case DoubleTyID: return DoubleTy;
66 case LabelTyID : return LabelTy;
72 // isLosslesslyConvertibleTo - Return true if this type can be converted to
73 // 'Ty' without any reinterpretation of bits. For example, uint to int.
75 bool Type::isLosslesslyConvertibleTo(const Type *Ty) const {
76 if (this == Ty) return true;
77 if ((!isPrimitiveType() && !isa<PointerType>(this)) ||
78 (!isa<PointerType>(Ty) && !Ty->isPrimitiveType())) return false;
80 if (getTypeID() == Ty->getTypeID())
81 return true; // Handles identity cast, and cast of differing pointer types
83 // Now we know that they are two differing primitive or pointer types
84 switch (getTypeID()) {
85 case Type::UByteTyID: return Ty == Type::SByteTy;
86 case Type::SByteTyID: return Ty == Type::UByteTy;
87 case Type::UShortTyID: return Ty == Type::ShortTy;
88 case Type::ShortTyID: return Ty == Type::UShortTy;
89 case Type::UIntTyID: return Ty == Type::IntTy;
90 case Type::IntTyID: return Ty == Type::UIntTy;
91 case Type::ULongTyID: return Ty == Type::LongTy;
92 case Type::LongTyID: return Ty == Type::ULongTy;
93 case Type::PointerTyID: return isa<PointerType>(Ty);
95 return false; // Other types have no identity values
99 /// getUnsignedVersion - If this is an integer type, return the unsigned
100 /// variant of this type. For example int -> uint.
101 const Type *Type::getUnsignedVersion() const {
102 switch (getTypeID()) {
104 assert(isInteger()&&"Type::getUnsignedVersion is only valid for integers!");
105 case Type::UByteTyID:
106 case Type::SByteTyID: return Type::UByteTy;
107 case Type::UShortTyID:
108 case Type::ShortTyID: return Type::UShortTy;
110 case Type::IntTyID: return Type::UIntTy;
111 case Type::ULongTyID:
112 case Type::LongTyID: return Type::ULongTy;
116 /// getSignedVersion - If this is an integer type, return the signed variant
117 /// of this type. For example uint -> int.
118 const Type *Type::getSignedVersion() const {
119 switch (getTypeID()) {
121 assert(isInteger() && "Type::getSignedVersion is only valid for integers!");
122 case Type::UByteTyID:
123 case Type::SByteTyID: return Type::SByteTy;
124 case Type::UShortTyID:
125 case Type::ShortTyID: return Type::ShortTy;
127 case Type::IntTyID: return Type::IntTy;
128 case Type::ULongTyID:
129 case Type::LongTyID: return Type::LongTy;
134 // getPrimitiveSize - Return the basic size of this type if it is a primitive
135 // type. These are fixed by LLVM and are not target dependent. This will
136 // return zero if the type does not have a size or is not a primitive type.
138 unsigned Type::getPrimitiveSize() const {
139 switch (getTypeID()) {
140 #define HANDLE_PRIM_TYPE(TY,SIZE) case TY##TyID: return SIZE;
141 #include "llvm/Type.def"
146 /// isSizedDerivedType - Derived types like structures and arrays are sized
147 /// iff all of the members of the type are sized as well. Since asking for
148 /// their size is relatively uncommon, move this operation out of line.
149 bool Type::isSizedDerivedType() const {
150 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
151 return ATy->getElementType()->isSized();
153 if (!isa<StructType>(this)) return false;
155 // Okay, our struct is sized if all of the elements are...
156 for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
157 if (!(*I)->isSized()) return false;
162 /// getForwardedTypeInternal - This method is used to implement the union-find
163 /// algorithm for when a type is being forwarded to another type.
164 const Type *Type::getForwardedTypeInternal() const {
165 assert(ForwardType && "This type is not being forwarded to another type!");
167 // Check to see if the forwarded type has been forwarded on. If so, collapse
168 // the forwarding links.
169 const Type *RealForwardedType = ForwardType->getForwardedType();
170 if (!RealForwardedType)
171 return ForwardType; // No it's not forwarded again
173 // Yes, it is forwarded again. First thing, add the reference to the new
175 if (RealForwardedType->isAbstract())
176 cast<DerivedType>(RealForwardedType)->addRef();
178 // Now drop the old reference. This could cause ForwardType to get deleted.
179 cast<DerivedType>(ForwardType)->dropRef();
181 // Return the updated type.
182 ForwardType = RealForwardedType;
186 // getTypeDescription - This is a recursive function that walks a type hierarchy
187 // calculating the description for a type.
189 static std::string getTypeDescription(const Type *Ty,
190 std::vector<const Type *> &TypeStack) {
191 if (isa<OpaqueType>(Ty)) { // Base case for the recursion
192 std::map<const Type*, std::string>::iterator I =
193 AbstractTypeDescriptions.lower_bound(Ty);
194 if (I != AbstractTypeDescriptions.end() && I->first == Ty)
196 std::string Desc = "opaque";
197 AbstractTypeDescriptions.insert(std::make_pair(Ty, Desc));
201 if (!Ty->isAbstract()) { // Base case for the recursion
202 std::map<const Type*, std::string>::iterator I =
203 ConcreteTypeDescriptions.find(Ty);
204 if (I != ConcreteTypeDescriptions.end()) return I->second;
207 // Check to see if the Type is already on the stack...
208 unsigned Slot = 0, CurSize = TypeStack.size();
209 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
211 // This is another base case for the recursion. In this case, we know
212 // that we have looped back to a type that we have previously visited.
213 // Generate the appropriate upreference to handle this.
216 return "\\" + utostr(CurSize-Slot); // Here's the upreference
218 // Recursive case: derived types...
220 TypeStack.push_back(Ty); // Add us to the stack..
222 switch (Ty->getTypeID()) {
223 case Type::FunctionTyID: {
224 const FunctionType *FTy = cast<FunctionType>(Ty);
225 Result = getTypeDescription(FTy->getReturnType(), TypeStack) + " (";
226 for (FunctionType::param_iterator I = FTy->param_begin(),
227 E = FTy->param_end(); I != E; ++I) {
228 if (I != FTy->param_begin())
230 Result += getTypeDescription(*I, TypeStack);
232 if (FTy->isVarArg()) {
233 if (FTy->getNumParams()) Result += ", ";
239 case Type::StructTyID: {
240 const StructType *STy = cast<StructType>(Ty);
242 for (StructType::element_iterator I = STy->element_begin(),
243 E = STy->element_end(); I != E; ++I) {
244 if (I != STy->element_begin())
246 Result += getTypeDescription(*I, TypeStack);
251 case Type::PointerTyID: {
252 const PointerType *PTy = cast<PointerType>(Ty);
253 Result = getTypeDescription(PTy->getElementType(), TypeStack) + " *";
256 case Type::ArrayTyID: {
257 const ArrayType *ATy = cast<ArrayType>(Ty);
258 unsigned NumElements = ATy->getNumElements();
260 Result += utostr(NumElements) + " x ";
261 Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
264 case Type::PackedTyID: {
265 const PackedType *PTy = cast<PackedType>(Ty);
266 unsigned NumElements = PTy->getNumElements();
268 Result += utostr(NumElements) + " x ";
269 Result += getTypeDescription(PTy->getElementType(), TypeStack) + ">";
274 assert(0 && "Unhandled type in getTypeDescription!");
277 TypeStack.pop_back(); // Remove self from stack...
284 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
286 std::map<const Type*, std::string>::iterator I = Map.find(Ty);
287 if (I != Map.end()) return I->second;
289 std::vector<const Type *> TypeStack;
290 return Map[Ty] = getTypeDescription(Ty, TypeStack);
294 const std::string &Type::getDescription() const {
296 return getOrCreateDesc(AbstractTypeDescriptions, this);
298 return getOrCreateDesc(ConcreteTypeDescriptions, this);
302 bool StructType::indexValid(const Value *V) const {
303 // Structure indexes require unsigned integer constants.
304 if (V->getType() == Type::UIntTy)
305 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(V))
306 return CU->getValue() < ContainedTys.size();
310 // getTypeAtIndex - Given an index value into the type, return the type of the
311 // element. For a structure type, this must be a constant value...
313 const Type *StructType::getTypeAtIndex(const Value *V) const {
314 assert(indexValid(V) && "Invalid structure index!");
315 unsigned Idx = (unsigned)cast<ConstantUInt>(V)->getValue();
316 return ContainedTys[Idx];
320 //===----------------------------------------------------------------------===//
321 // Static 'Type' data
322 //===----------------------------------------------------------------------===//
325 struct PrimType : public Type {
326 PrimType(const char *S, TypeID ID) : Type(S, ID) {}
330 static PrimType TheVoidTy ("void" , Type::VoidTyID);
331 static PrimType TheBoolTy ("bool" , Type::BoolTyID);
332 static PrimType TheSByteTy ("sbyte" , Type::SByteTyID);
333 static PrimType TheUByteTy ("ubyte" , Type::UByteTyID);
334 static PrimType TheShortTy ("short" , Type::ShortTyID);
335 static PrimType TheUShortTy("ushort", Type::UShortTyID);
336 static PrimType TheIntTy ("int" , Type::IntTyID);
337 static PrimType TheUIntTy ("uint" , Type::UIntTyID);
338 static PrimType TheLongTy ("long" , Type::LongTyID);
339 static PrimType TheULongTy ("ulong" , Type::ULongTyID);
340 static PrimType TheFloatTy ("float" , Type::FloatTyID);
341 static PrimType TheDoubleTy("double", Type::DoubleTyID);
342 static PrimType TheLabelTy ("label" , Type::LabelTyID);
344 Type *Type::VoidTy = &TheVoidTy;
345 Type *Type::BoolTy = &TheBoolTy;
346 Type *Type::SByteTy = &TheSByteTy;
347 Type *Type::UByteTy = &TheUByteTy;
348 Type *Type::ShortTy = &TheShortTy;
349 Type *Type::UShortTy = &TheUShortTy;
350 Type *Type::IntTy = &TheIntTy;
351 Type *Type::UIntTy = &TheUIntTy;
352 Type *Type::LongTy = &TheLongTy;
353 Type *Type::ULongTy = &TheULongTy;
354 Type *Type::FloatTy = &TheFloatTy;
355 Type *Type::DoubleTy = &TheDoubleTy;
356 Type *Type::LabelTy = &TheLabelTy;
359 //===----------------------------------------------------------------------===//
360 // Derived Type Constructors
361 //===----------------------------------------------------------------------===//
363 FunctionType::FunctionType(const Type *Result,
364 const std::vector<const Type*> &Params,
365 bool IsVarArgs) : DerivedType(FunctionTyID),
366 isVarArgs(IsVarArgs) {
367 assert((Result->isFirstClassType() || Result == Type::VoidTy ||
368 isa<OpaqueType>(Result)) &&
369 "LLVM functions cannot return aggregates");
370 bool isAbstract = Result->isAbstract();
371 ContainedTys.reserve(Params.size()+1);
372 ContainedTys.push_back(PATypeHandle(Result, this));
374 for (unsigned i = 0; i != Params.size(); ++i) {
375 assert((Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])) &&
376 "Function arguments must be value types!");
378 ContainedTys.push_back(PATypeHandle(Params[i], this));
379 isAbstract |= Params[i]->isAbstract();
382 // Calculate whether or not this type is abstract
383 setAbstract(isAbstract);
386 StructType::StructType(const std::vector<const Type*> &Types)
387 : CompositeType(StructTyID) {
388 ContainedTys.reserve(Types.size());
389 bool isAbstract = false;
390 for (unsigned i = 0; i < Types.size(); ++i) {
391 assert(Types[i] != Type::VoidTy && "Void type for structure field!!");
392 ContainedTys.push_back(PATypeHandle(Types[i], this));
393 isAbstract |= Types[i]->isAbstract();
396 // Calculate whether or not this type is abstract
397 setAbstract(isAbstract);
400 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
401 : SequentialType(ArrayTyID, ElType) {
404 // Calculate whether or not this type is abstract
405 setAbstract(ElType->isAbstract());
408 PackedType::PackedType(const Type *ElType, unsigned NumEl)
409 : SequentialType(PackedTyID, ElType) {
412 assert(NumEl > 0 && "NumEl of a PackedType must be greater than 0");
413 assert((ElType->isIntegral() || ElType->isFloatingPoint()) &&
414 "Elements of a PackedType must be a primitive type");
418 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
419 // Calculate whether or not this type is abstract
420 setAbstract(E->isAbstract());
423 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
425 #ifdef DEBUG_MERGE_TYPES
426 std::cerr << "Derived new type: " << *this << "\n";
430 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
431 // another (more concrete) type, we must eliminate all references to other
432 // types, to avoid some circular reference problems.
433 void DerivedType::dropAllTypeUses() {
434 if (!ContainedTys.empty()) {
435 while (ContainedTys.size() > 1)
436 ContainedTys.pop_back();
438 // The type must stay abstract. To do this, we insert a pointer to a type
439 // that will never get resolved, thus will always be abstract.
440 static Type *AlwaysOpaqueTy = OpaqueType::get();
441 static PATypeHolder Holder(AlwaysOpaqueTy);
442 ContainedTys[0] = AlwaysOpaqueTy;
446 // isTypeAbstract - This is a recursive function that walks a type hierarchy
447 // calculating whether or not a type is abstract. Worst case it will have to do
448 // a lot of traversing if you have some whacko opaque types, but in most cases,
449 // it will do some simple stuff when it hits non-abstract types that aren't
452 bool Type::isTypeAbstract() {
453 if (!isAbstract()) // Base case for the recursion
454 return false; // Primitive = leaf type
456 if (isa<OpaqueType>(this)) // Base case for the recursion
457 return true; // This whole type is abstract!
459 // We have to guard against recursion. To do this, we temporarily mark this
460 // type as concrete, so that if we get back to here recursively we will think
461 // it's not abstract, and thus not scan it again.
464 // Scan all of the sub-types. If any of them are abstract, than so is this
466 for (Type::subtype_iterator I = subtype_begin(), E = subtype_end();
468 if (const_cast<Type*>(I->get())->isTypeAbstract()) {
469 setAbstract(true); // Restore the abstract bit.
470 return true; // This type is abstract if subtype is abstract!
473 // Restore the abstract bit.
476 // Nothing looks abstract here...
481 //===----------------------------------------------------------------------===//
482 // Type Structural Equality Testing
483 //===----------------------------------------------------------------------===//
485 // TypesEqual - Two types are considered structurally equal if they have the
486 // same "shape": Every level and element of the types have identical primitive
487 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
488 // be pointer equals to be equivalent though. This uses an optimistic algorithm
489 // that assumes that two graphs are the same until proven otherwise.
491 static bool TypesEqual(const Type *Ty, const Type *Ty2,
492 std::map<const Type *, const Type *> &EqTypes) {
493 if (Ty == Ty2) return true;
494 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
495 if (isa<OpaqueType>(Ty))
496 return false; // Two unequal opaque types are never equal
498 std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
499 if (It != EqTypes.end() && It->first == Ty)
500 return It->second == Ty2; // Looping back on a type, check for equality
502 // Otherwise, add the mapping to the table to make sure we don't get
503 // recursion on the types...
504 EqTypes.insert(It, std::make_pair(Ty, Ty2));
506 // Two really annoying special cases that breaks an otherwise nice simple
507 // algorithm is the fact that arraytypes have sizes that differentiates types,
508 // and that function types can be varargs or not. Consider this now.
510 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
511 return TypesEqual(PTy->getElementType(),
512 cast<PointerType>(Ty2)->getElementType(), EqTypes);
513 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
514 const StructType *STy2 = cast<StructType>(Ty2);
515 if (STy->getNumElements() != STy2->getNumElements()) return false;
516 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
517 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
520 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
521 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
522 return ATy->getNumElements() == ATy2->getNumElements() &&
523 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
524 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
525 const PackedType *PTy2 = cast<PackedType>(Ty2);
526 return PTy->getNumElements() == PTy2->getNumElements() &&
527 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
528 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
529 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
530 if (FTy->isVarArg() != FTy2->isVarArg() ||
531 FTy->getNumParams() != FTy2->getNumParams() ||
532 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
534 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i)
535 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
539 assert(0 && "Unknown derived type!");
544 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
545 std::map<const Type *, const Type *> EqTypes;
546 return TypesEqual(Ty, Ty2, EqTypes);
549 // TypeHasCycleThrough - Return true there is a path from CurTy to TargetTy in
550 // the type graph. We know that Ty is an abstract type, so if we ever reach a
551 // non-abstract type, we know that we don't need to search the subgraph.
552 static bool TypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
553 std::set<const Type*> &VisitedTypes) {
554 if (TargetTy == CurTy) return true;
555 if (!CurTy->isAbstract()) return false;
557 std::set<const Type*>::iterator VTI = VisitedTypes.lower_bound(CurTy);
558 if (VTI != VisitedTypes.end() && *VTI == CurTy)
560 VisitedTypes.insert(VTI, CurTy);
562 for (Type::subtype_iterator I = CurTy->subtype_begin(),
563 E = CurTy->subtype_end(); I != E; ++I)
564 if (TypeHasCycleThrough(TargetTy, *I, VisitedTypes))
570 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
572 static bool TypeHasCycleThroughItself(const Type *Ty) {
573 assert(Ty->isAbstract() && "This code assumes that Ty was abstract!");
574 std::set<const Type*> VisitedTypes;
575 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
577 if (TypeHasCycleThrough(Ty, *I, VisitedTypes))
583 //===----------------------------------------------------------------------===//
584 // Derived Type Factory Functions
585 //===----------------------------------------------------------------------===//
587 // TypeMap - Make sure that only one instance of a particular type may be
588 // created on any given run of the compiler... note that this involves updating
589 // our map if an abstract type gets refined somehow.
592 template<class ValType, class TypeClass>
594 std::map<ValType, PATypeHolder> Map;
596 /// TypesByHash - Keep track of each type by its structure hash value.
598 std::multimap<unsigned, PATypeHolder> TypesByHash;
600 typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
601 ~TypeMap() { print("ON EXIT"); }
603 inline TypeClass *get(const ValType &V) {
604 iterator I = Map.find(V);
605 return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
608 inline void add(const ValType &V, TypeClass *Ty) {
609 Map.insert(std::make_pair(V, Ty));
611 // If this type has a cycle, remember it.
612 TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
616 void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
617 std::multimap<unsigned, PATypeHolder>::iterator I =
618 TypesByHash.lower_bound(Hash);
619 while (I->second != Ty) {
621 assert(I != TypesByHash.end() && I->first == Hash);
623 TypesByHash.erase(I);
626 /// finishRefinement - This method is called after we have updated an existing
627 /// type with its new components. We must now either merge the type away with
628 /// some other type or reinstall it in the map with it's new configuration.
629 /// The specified iterator tells us what the type USED to look like.
630 void finishRefinement(TypeClass *Ty, const DerivedType *OldType,
631 const Type *NewType) {
632 assert((Ty->isAbstract() || !OldType->isAbstract()) &&
633 "Refining a non-abstract type!");
634 #ifdef DEBUG_MERGE_TYPES
635 std::cerr << "refineAbstractTy(" << (void*)OldType << "[" << *OldType
636 << "], " << (void*)NewType << " [" << *NewType << "])\n";
639 // Make a temporary type holder for the type so that it doesn't disappear on
640 // us when we erase the entry from the map.
641 PATypeHolder TyHolder = Ty;
643 // The old record is now out-of-date, because one of the children has been
644 // updated. Remove the obsolete entry from the map.
645 Map.erase(ValType::get(Ty));
647 // Remember the structural hash for the type before we start hacking on it,
648 // in case we need it later. Also, check to see if the type HAD a cycle
649 // through it, if so, we know it will when we hack on it.
650 unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
652 // Find the type element we are refining... and change it now!
653 for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
654 if (Ty->ContainedTys[i] == OldType) {
655 Ty->ContainedTys[i].removeUserFromConcrete();
656 Ty->ContainedTys[i] = NewType;
659 unsigned TypeHash = ValType::hashTypeStructure(Ty);
661 // If there are no cycles going through this node, we can do a simple,
662 // efficient lookup in the map, instead of an inefficient nasty linear
664 bool TypeHasCycle = Ty->isAbstract() && TypeHasCycleThroughItself(Ty);
666 iterator I = Map.find(ValType::get(Ty));
667 if (I != Map.end()) {
668 // We already have this type in the table. Get rid of the newly refined
670 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
671 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
673 // Refined to a different type altogether?
674 RemoveFromTypesByHash(TypeHash, Ty);
675 Ty->refineAbstractTypeTo(NewTy);
680 // Now we check to see if there is an existing entry in the table which is
681 // structurally identical to the newly refined type. If so, this type
682 // gets refined to the pre-existing type.
684 std::multimap<unsigned, PATypeHolder>::iterator I,E, Entry;
685 tie(I, E) = TypesByHash.equal_range(TypeHash);
687 for (; I != E; ++I) {
688 if (I->second != Ty) {
689 if (TypesEqual(Ty, I->second)) {
690 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
691 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
694 // Find the location of Ty in the TypesByHash structure.
695 while (I->second != Ty) {
697 assert(I != E && "Structure doesn't contain type??");
702 TypesByHash.erase(Entry);
703 Ty->refineAbstractTypeTo(NewTy);
707 // Remember the position of
713 // If we succeeded, we need to insert the type into the cycletypes table.
714 // There are several cases here, depending on whether the original type
715 // had the same hash code and was itself cyclic.
716 if (TypeHash != OldTypeHash) {
717 RemoveFromTypesByHash(OldTypeHash, Ty);
718 TypesByHash.insert(std::make_pair(TypeHash, Ty));
721 // If there is no existing type of the same structure, we reinsert an
722 // updated record into the map.
723 Map.insert(std::make_pair(ValType::get(Ty), Ty));
725 // If the type is currently thought to be abstract, rescan all of our
726 // subtypes to see if the type has just become concrete!
727 if (Ty->isAbstract()) {
728 Ty->setAbstract(Ty->isTypeAbstract());
730 // If the type just became concrete, notify all users!
731 if (!Ty->isAbstract())
732 Ty->notifyUsesThatTypeBecameConcrete();
736 void print(const char *Arg) const {
737 #ifdef DEBUG_MERGE_TYPES
738 std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
740 for (typename std::map<ValType, PATypeHolder>::const_iterator I
741 = Map.begin(), E = Map.end(); I != E; ++I)
742 std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " "
743 << *I->second.get() << "\n";
747 void dump() const { print("dump output"); }
752 //===----------------------------------------------------------------------===//
753 // Function Type Factory and Value Class...
756 // FunctionValType - Define a class to hold the key that goes into the TypeMap
759 class FunctionValType {
761 std::vector<const Type*> ArgTypes;
764 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
765 bool IVA) : RetTy(ret), isVarArg(IVA) {
766 for (unsigned i = 0; i < args.size(); ++i)
767 ArgTypes.push_back(args[i]);
770 static FunctionValType get(const FunctionType *FT);
772 static unsigned hashTypeStructure(const FunctionType *FT) {
773 return FT->getNumParams()*2+FT->isVarArg();
776 // Subclass should override this... to update self as usual
777 void doRefinement(const DerivedType *OldType, const Type *NewType) {
778 if (RetTy == OldType) RetTy = NewType;
779 for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
780 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
783 inline bool operator<(const FunctionValType &MTV) const {
784 if (RetTy < MTV.RetTy) return true;
785 if (RetTy > MTV.RetTy) return false;
787 if (ArgTypes < MTV.ArgTypes) return true;
788 return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
793 // Define the actual map itself now...
794 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
796 FunctionValType FunctionValType::get(const FunctionType *FT) {
797 // Build up a FunctionValType
798 std::vector<const Type *> ParamTypes;
799 ParamTypes.reserve(FT->getNumParams());
800 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
801 ParamTypes.push_back(FT->getParamType(i));
802 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
806 // FunctionType::get - The factory function for the FunctionType class...
807 FunctionType *FunctionType::get(const Type *ReturnType,
808 const std::vector<const Type*> &Params,
810 FunctionValType VT(ReturnType, Params, isVarArg);
811 FunctionType *MT = FunctionTypes.get(VT);
814 FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
816 #ifdef DEBUG_MERGE_TYPES
817 std::cerr << "Derived new type: " << MT << "\n";
822 //===----------------------------------------------------------------------===//
823 // Array Type Factory...
830 ArrayValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
832 static ArrayValType get(const ArrayType *AT) {
833 return ArrayValType(AT->getElementType(), AT->getNumElements());
836 static unsigned hashTypeStructure(const ArrayType *AT) {
837 return AT->getNumElements();
840 // Subclass should override this... to update self as usual
841 void doRefinement(const DerivedType *OldType, const Type *NewType) {
842 assert(ValTy == OldType);
846 inline bool operator<(const ArrayValType &MTV) const {
847 if (Size < MTV.Size) return true;
848 return Size == MTV.Size && ValTy < MTV.ValTy;
852 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
855 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
856 assert(ElementType && "Can't get array of null types!");
858 ArrayValType AVT(ElementType, NumElements);
859 ArrayType *AT = ArrayTypes.get(AVT);
860 if (AT) return AT; // Found a match, return it!
862 // Value not found. Derive a new type!
863 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
865 #ifdef DEBUG_MERGE_TYPES
866 std::cerr << "Derived new type: " << *AT << "\n";
872 //===----------------------------------------------------------------------===//
873 // Packed Type Factory...
876 class PackedValType {
880 PackedValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
882 static PackedValType get(const PackedType *PT) {
883 return PackedValType(PT->getElementType(), PT->getNumElements());
886 static unsigned hashTypeStructure(const PackedType *PT) {
887 return PT->getNumElements();
890 // Subclass should override this... to update self as usual
891 void doRefinement(const DerivedType *OldType, const Type *NewType) {
892 assert(ValTy == OldType);
896 inline bool operator<(const PackedValType &MTV) const {
897 if (Size < MTV.Size) return true;
898 return Size == MTV.Size && ValTy < MTV.ValTy;
902 static TypeMap<PackedValType, PackedType> PackedTypes;
905 PackedType *PackedType::get(const Type *ElementType, unsigned NumElements) {
906 assert(ElementType && "Can't get packed of null types!");
908 PackedValType PVT(ElementType, NumElements);
909 PackedType *PT = PackedTypes.get(PVT);
910 if (PT) return PT; // Found a match, return it!
912 // Value not found. Derive a new type!
913 PackedTypes.add(PVT, PT = new PackedType(ElementType, NumElements));
915 #ifdef DEBUG_MERGE_TYPES
916 std::cerr << "Derived new type: " << *PT << "\n";
921 //===----------------------------------------------------------------------===//
922 // Struct Type Factory...
926 // StructValType - Define a class to hold the key that goes into the TypeMap
928 class StructValType {
929 std::vector<const Type*> ElTypes;
931 StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
933 static StructValType get(const StructType *ST) {
934 std::vector<const Type *> ElTypes;
935 ElTypes.reserve(ST->getNumElements());
936 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
937 ElTypes.push_back(ST->getElementType(i));
939 return StructValType(ElTypes);
942 static unsigned hashTypeStructure(const StructType *ST) {
943 return ST->getNumElements();
946 // Subclass should override this... to update self as usual
947 void doRefinement(const DerivedType *OldType, const Type *NewType) {
948 for (unsigned i = 0; i < ElTypes.size(); ++i)
949 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
952 inline bool operator<(const StructValType &STV) const {
953 return ElTypes < STV.ElTypes;
958 static TypeMap<StructValType, StructType> StructTypes;
960 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
961 StructValType STV(ETypes);
962 StructType *ST = StructTypes.get(STV);
965 // Value not found. Derive a new type!
966 StructTypes.add(STV, ST = new StructType(ETypes));
968 #ifdef DEBUG_MERGE_TYPES
969 std::cerr << "Derived new type: " << *ST << "\n";
976 //===----------------------------------------------------------------------===//
977 // Pointer Type Factory...
980 // PointerValType - Define a class to hold the key that goes into the TypeMap
983 class PointerValType {
986 PointerValType(const Type *val) : ValTy(val) {}
988 static PointerValType get(const PointerType *PT) {
989 return PointerValType(PT->getElementType());
992 static unsigned hashTypeStructure(const PointerType *PT) {
996 // Subclass should override this... to update self as usual
997 void doRefinement(const DerivedType *OldType, const Type *NewType) {
998 assert(ValTy == OldType);
1002 bool operator<(const PointerValType &MTV) const {
1003 return ValTy < MTV.ValTy;
1008 static TypeMap<PointerValType, PointerType> PointerTypes;
1010 PointerType *PointerType::get(const Type *ValueType) {
1011 assert(ValueType && "Can't get a pointer to <null> type!");
1012 PointerValType PVT(ValueType);
1014 PointerType *PT = PointerTypes.get(PVT);
1017 // Value not found. Derive a new type!
1018 PointerTypes.add(PVT, PT = new PointerType(ValueType));
1020 #ifdef DEBUG_MERGE_TYPES
1021 std::cerr << "Derived new type: " << *PT << "\n";
1027 //===----------------------------------------------------------------------===//
1028 // Derived Type Refinement Functions
1029 //===----------------------------------------------------------------------===//
1031 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1032 // no longer has a handle to the type. This function is called primarily by
1033 // the PATypeHandle class. When there are no users of the abstract type, it
1034 // is annihilated, because there is no way to get a reference to it ever again.
1036 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
1037 // Search from back to front because we will notify users from back to
1038 // front. Also, it is likely that there will be a stack like behavior to
1039 // users that register and unregister users.
1042 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1043 assert(i != 0 && "AbstractTypeUser not in user list!");
1045 --i; // Convert to be in range 0 <= i < size()
1046 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1048 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1050 #ifdef DEBUG_MERGE_TYPES
1051 std::cerr << " remAbstractTypeUser[" << (void*)this << ", "
1052 << *this << "][" << i << "] User = " << U << "\n";
1055 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1056 #ifdef DEBUG_MERGE_TYPES
1057 std::cerr << "DELETEing unused abstract type: <" << *this
1058 << ">[" << (void*)this << "]" << "\n";
1060 delete this; // No users of this abstract type!
1065 // refineAbstractTypeTo - This function is used to when it is discovered that
1066 // the 'this' abstract type is actually equivalent to the NewType specified.
1067 // This causes all users of 'this' to switch to reference the more concrete type
1068 // NewType and for 'this' to be deleted.
1070 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1071 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1072 assert(this != NewType && "Can't refine to myself!");
1073 assert(ForwardType == 0 && "This type has already been refined!");
1075 // The descriptions may be out of date. Conservatively clear them all!
1076 AbstractTypeDescriptions.clear();
1078 #ifdef DEBUG_MERGE_TYPES
1079 std::cerr << "REFINING abstract type [" << (void*)this << " "
1080 << *this << "] to [" << (void*)NewType << " "
1081 << *NewType << "]!\n";
1084 // Make sure to put the type to be refined to into a holder so that if IT gets
1085 // refined, that we will not continue using a dead reference...
1087 PATypeHolder NewTy(NewType);
1089 // Any PATypeHolders referring to this type will now automatically forward to
1090 // the type we are resolved to.
1091 ForwardType = NewType;
1092 if (NewType->isAbstract())
1093 cast<DerivedType>(NewType)->addRef();
1095 // Add a self use of the current type so that we don't delete ourself until
1096 // after the function exits.
1098 PATypeHolder CurrentTy(this);
1100 // To make the situation simpler, we ask the subclass to remove this type from
1101 // the type map, and to replace any type uses with uses of non-abstract types.
1102 // This dramatically limits the amount of recursive type trouble we can find
1106 // Iterate over all of the uses of this type, invoking callback. Each user
1107 // should remove itself from our use list automatically. We have to check to
1108 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1109 // will not cause users to drop off of the use list. If we resolve to ourself
1112 while (!AbstractTypeUsers.empty() && NewTy != this) {
1113 AbstractTypeUser *User = AbstractTypeUsers.back();
1115 unsigned OldSize = AbstractTypeUsers.size();
1116 #ifdef DEBUG_MERGE_TYPES
1117 std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
1118 << "] of abstract type [" << (void*)this << " "
1119 << *this << "] to [" << (void*)NewTy.get() << " "
1120 << *NewTy << "]!\n";
1122 User->refineAbstractType(this, NewTy);
1124 assert(AbstractTypeUsers.size() != OldSize &&
1125 "AbsTyUser did not remove self from user list!");
1128 // If we were successful removing all users from the type, 'this' will be
1129 // deleted when the last PATypeHolder is destroyed or updated from this type.
1130 // This may occur on exit of this function, as the CurrentTy object is
1134 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1135 // the current type has transitioned from being abstract to being concrete.
1137 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1138 #ifdef DEBUG_MERGE_TYPES
1139 std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1142 unsigned OldSize = AbstractTypeUsers.size();
1143 while (!AbstractTypeUsers.empty()) {
1144 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1145 ATU->typeBecameConcrete(this);
1147 assert(AbstractTypeUsers.size() < OldSize-- &&
1148 "AbstractTypeUser did not remove itself from the use list!");
1155 // refineAbstractType - Called when a contained type is found to be more
1156 // concrete - this could potentially change us from an abstract type to a
1159 void FunctionType::refineAbstractType(const DerivedType *OldType,
1160 const Type *NewType) {
1161 FunctionTypes.finishRefinement(this, OldType, NewType);
1164 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1165 refineAbstractType(AbsTy, AbsTy);
1169 // refineAbstractType - Called when a contained type is found to be more
1170 // concrete - this could potentially change us from an abstract type to a
1173 void ArrayType::refineAbstractType(const DerivedType *OldType,
1174 const Type *NewType) {
1175 ArrayTypes.finishRefinement(this, OldType, NewType);
1178 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1179 refineAbstractType(AbsTy, AbsTy);
1182 // refineAbstractType - Called when a contained type is found to be more
1183 // concrete - this could potentially change us from an abstract type to a
1186 void PackedType::refineAbstractType(const DerivedType *OldType,
1187 const Type *NewType) {
1188 PackedTypes.finishRefinement(this, OldType, NewType);
1191 void PackedType::typeBecameConcrete(const DerivedType *AbsTy) {
1192 refineAbstractType(AbsTy, AbsTy);
1195 // refineAbstractType - Called when a contained type is found to be more
1196 // concrete - this could potentially change us from an abstract type to a
1199 void StructType::refineAbstractType(const DerivedType *OldType,
1200 const Type *NewType) {
1201 StructTypes.finishRefinement(this, OldType, NewType);
1204 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1205 refineAbstractType(AbsTy, AbsTy);
1208 // refineAbstractType - Called when a contained type is found to be more
1209 // concrete - this could potentially change us from an abstract type to a
1212 void PointerType::refineAbstractType(const DerivedType *OldType,
1213 const Type *NewType) {
1214 PointerTypes.finishRefinement(this, OldType, NewType);
1217 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1218 refineAbstractType(AbsTy, AbsTy);
1221 bool SequentialType::indexValid(const Value *V) const {
1222 const Type *Ty = V->getType();
1223 switch (Ty->getTypeID()) {
1225 case Type::UIntTyID:
1226 case Type::LongTyID:
1227 case Type::ULongTyID:
1235 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1237 OS << "<null> value!\n";
1243 std::ostream &operator<<(std::ostream &OS, const Type &T) {