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 "Support/DepthFirstIterator.h"
19 #include "Support/StringExtras.h"
20 #include "Support/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 static unsigned CurUID = 0;
38 static std::vector<const Type *> UIDMappings;
40 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
41 // for types as they are needed. Because resolution of types must invalidate
42 // all of the abstract type descriptions, we keep them in a seperate map to make
44 static std::map<const Type*, std::string> ConcreteTypeDescriptions;
45 static std::map<const Type*, std::string> AbstractTypeDescriptions;
47 Type::Type( const std::string& name, TypeID id )
48 : RefCount(0), ForwardType(0) {
50 ConcreteTypeDescriptions[this] = name;
53 UID = CurUID++; // Assign types UID's as they are created
54 UIDMappings.push_back(this);
57 void Type::setName(const std::string &Name, SymbolTable *ST) {
58 assert(ST && "Type::setName - Must provide symbol table argument!");
59 if (!Name.empty()) ST->insert(Name, this);
62 const Type *Type::getUniqueIDType(unsigned UID) {
63 assert(UID < UIDMappings.size() &&
64 "Type::getPrimitiveType: UID out of range!");
65 return UIDMappings[UID];
68 const Type *Type::getPrimitiveType(TypeID IDNumber) {
70 case VoidTyID : return VoidTy;
71 case BoolTyID : return BoolTy;
72 case UByteTyID : return UByteTy;
73 case SByteTyID : return SByteTy;
74 case UShortTyID: return UShortTy;
75 case ShortTyID : return ShortTy;
76 case UIntTyID : return UIntTy;
77 case IntTyID : return IntTy;
78 case ULongTyID : return ULongTy;
79 case LongTyID : return LongTy;
80 case FloatTyID : return FloatTy;
81 case DoubleTyID: return DoubleTy;
82 case LabelTyID : return LabelTy;
88 // isLosslesslyConvertibleTo - Return true if this type can be converted to
89 // 'Ty' without any reinterpretation of bits. For example, uint to int.
91 bool Type::isLosslesslyConvertibleTo(const Type *Ty) const {
92 if (this == Ty) return true;
93 if ((!isPrimitiveType() && !isa<PointerType>(this)) ||
94 (!isa<PointerType>(Ty) && !Ty->isPrimitiveType())) return false;
96 if (getTypeID() == Ty->getTypeID())
97 return true; // Handles identity cast, and cast of differing pointer types
99 // Now we know that they are two differing primitive or pointer types
100 switch (getTypeID()) {
101 case Type::UByteTyID: return Ty == Type::SByteTy;
102 case Type::SByteTyID: return Ty == Type::UByteTy;
103 case Type::UShortTyID: return Ty == Type::ShortTy;
104 case Type::ShortTyID: return Ty == Type::UShortTy;
105 case Type::UIntTyID: return Ty == Type::IntTy;
106 case Type::IntTyID: return Ty == Type::UIntTy;
107 case Type::ULongTyID: return Ty == Type::LongTy;
108 case Type::LongTyID: return Ty == Type::ULongTy;
109 case Type::PointerTyID: return isa<PointerType>(Ty);
111 return false; // Other types have no identity values
115 /// getUnsignedVersion - If this is an integer type, return the unsigned
116 /// variant of this type. For example int -> uint.
117 const Type *Type::getUnsignedVersion() const {
118 switch (getTypeID()) {
120 assert(isInteger()&&"Type::getUnsignedVersion is only valid for integers!");
121 case Type::UByteTyID:
122 case Type::SByteTyID: return Type::UByteTy;
123 case Type::UShortTyID:
124 case Type::ShortTyID: return Type::UShortTy;
126 case Type::IntTyID: return Type::UIntTy;
127 case Type::ULongTyID:
128 case Type::LongTyID: return Type::ULongTy;
132 /// getSignedVersion - If this is an integer type, return the signed variant
133 /// of this type. For example uint -> int.
134 const Type *Type::getSignedVersion() const {
135 switch (getTypeID()) {
137 assert(isInteger() && "Type::getSignedVersion is only valid for integers!");
138 case Type::UByteTyID:
139 case Type::SByteTyID: return Type::SByteTy;
140 case Type::UShortTyID:
141 case Type::ShortTyID: return Type::ShortTy;
143 case Type::IntTyID: return Type::IntTy;
144 case Type::ULongTyID:
145 case Type::LongTyID: return Type::LongTy;
150 // getPrimitiveSize - Return the basic size of this type if it is a primitive
151 // type. These are fixed by LLVM and are not target dependent. This will
152 // return zero if the type does not have a size or is not a primitive type.
154 unsigned Type::getPrimitiveSize() const {
155 switch (getTypeID()) {
156 #define HANDLE_PRIM_TYPE(TY,SIZE) case TY##TyID: return SIZE;
157 #include "llvm/Type.def"
162 /// isSizedDerivedType - Derived types like structures and arrays are sized
163 /// iff all of the members of the type are sized as well. Since asking for
164 /// their size is relatively uncommon, move this operation out of line.
165 bool Type::isSizedDerivedType() const {
166 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
167 return ATy->getElementType()->isSized();
169 if (!isa<StructType>(this)) return false;
171 // Okay, our struct is sized if all of the elements are...
172 for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
173 if (!(*I)->isSized()) return false;
178 /// getForwardedTypeInternal - This method is used to implement the union-find
179 /// algorithm for when a type is being forwarded to another type.
180 const Type *Type::getForwardedTypeInternal() const {
181 assert(ForwardType && "This type is not being forwarded to another type!");
183 // Check to see if the forwarded type has been forwarded on. If so, collapse
184 // the forwarding links.
185 const Type *RealForwardedType = ForwardType->getForwardedType();
186 if (!RealForwardedType)
187 return ForwardType; // No it's not forwarded again
189 // Yes, it is forwarded again. First thing, add the reference to the new
191 if (RealForwardedType->isAbstract())
192 cast<DerivedType>(RealForwardedType)->addRef();
194 // Now drop the old reference. This could cause ForwardType to get deleted.
195 cast<DerivedType>(ForwardType)->dropRef();
197 // Return the updated type.
198 ForwardType = RealForwardedType;
202 // getTypeDescription - This is a recursive function that walks a type hierarchy
203 // calculating the description for a type.
205 static std::string getTypeDescription(const Type *Ty,
206 std::vector<const Type *> &TypeStack) {
207 if (isa<OpaqueType>(Ty)) { // Base case for the recursion
208 std::map<const Type*, std::string>::iterator I =
209 AbstractTypeDescriptions.lower_bound(Ty);
210 if (I != AbstractTypeDescriptions.end() && I->first == Ty)
212 std::string Desc = "opaque"+utostr(Ty->getUniqueID());
213 AbstractTypeDescriptions.insert(std::make_pair(Ty, Desc));
217 if (!Ty->isAbstract()) { // Base case for the recursion
218 std::map<const Type*, std::string>::iterator I =
219 ConcreteTypeDescriptions.find(Ty);
220 if (I != ConcreteTypeDescriptions.end()) return I->second;
223 // Check to see if the Type is already on the stack...
224 unsigned Slot = 0, CurSize = TypeStack.size();
225 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
227 // This is another base case for the recursion. In this case, we know
228 // that we have looped back to a type that we have previously visited.
229 // Generate the appropriate upreference to handle this.
232 return "\\" + utostr(CurSize-Slot); // Here's the upreference
234 // Recursive case: derived types...
236 TypeStack.push_back(Ty); // Add us to the stack..
238 switch (Ty->getTypeID()) {
239 case Type::FunctionTyID: {
240 const FunctionType *FTy = cast<FunctionType>(Ty);
241 Result = getTypeDescription(FTy->getReturnType(), TypeStack) + " (";
242 for (FunctionType::param_iterator I = FTy->param_begin(),
243 E = FTy->param_end(); I != E; ++I) {
244 if (I != FTy->param_begin())
246 Result += getTypeDescription(*I, TypeStack);
248 if (FTy->isVarArg()) {
249 if (FTy->getNumParams()) Result += ", ";
255 case Type::StructTyID: {
256 const StructType *STy = cast<StructType>(Ty);
258 for (StructType::element_iterator I = STy->element_begin(),
259 E = STy->element_end(); I != E; ++I) {
260 if (I != STy->element_begin())
262 Result += getTypeDescription(*I, TypeStack);
267 case Type::PointerTyID: {
268 const PointerType *PTy = cast<PointerType>(Ty);
269 Result = getTypeDescription(PTy->getElementType(), TypeStack) + " *";
272 case Type::ArrayTyID: {
273 const ArrayType *ATy = cast<ArrayType>(Ty);
274 unsigned NumElements = ATy->getNumElements();
276 Result += utostr(NumElements) + " x ";
277 Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
282 assert(0 && "Unhandled type in getTypeDescription!");
285 TypeStack.pop_back(); // Remove self from stack...
292 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
294 std::map<const Type*, std::string>::iterator I = Map.find(Ty);
295 if (I != Map.end()) return I->second;
297 std::vector<const Type *> TypeStack;
298 return Map[Ty] = getTypeDescription(Ty, TypeStack);
302 const std::string &Type::getDescription() const {
304 return getOrCreateDesc(AbstractTypeDescriptions, this);
306 return getOrCreateDesc(ConcreteTypeDescriptions, this);
310 bool StructType::indexValid(const Value *V) const {
311 // Structure indexes require unsigned integer constants.
312 if (V->getType() == Type::UIntTy)
313 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(V))
314 return CU->getValue() < ContainedTys.size();
318 // getTypeAtIndex - Given an index value into the type, return the type of the
319 // element. For a structure type, this must be a constant value...
321 const Type *StructType::getTypeAtIndex(const Value *V) const {
322 assert(indexValid(V) && "Invalid structure index!");
323 unsigned Idx = (unsigned)cast<ConstantUInt>(V)->getValue();
324 return ContainedTys[Idx];
328 //===----------------------------------------------------------------------===//
330 //===----------------------------------------------------------------------===//
332 // These classes are used to implement specialized behavior for each different
335 struct SignedIntType : public Type {
336 SignedIntType(std::string name, TypeID id) : Type(name, id) {}
338 // isSigned - Return whether a numeric type is signed.
339 virtual bool isSigned() const { return 1; }
341 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
342 // virtual function invocation.
344 virtual bool isInteger() const { return 1; }
347 struct UnsignedIntType : public Type {
348 UnsignedIntType(std::string name, TypeID id) : Type(name,id) {}
350 // isUnsigned - Return whether a numeric type is signed.
351 virtual bool isUnsigned() const { return 1; }
353 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
354 // virtual function invocation.
356 virtual bool isInteger() const { return 1; }
359 struct OtherType : public Type {
360 OtherType(std:;string name, TypeID id) : Type(name,id) {}
364 //===----------------------------------------------------------------------===//
365 // Static 'Type' data
366 //===----------------------------------------------------------------------===//
368 static OtherType TheVoidTy ("void" , Type::VoidTyID);
369 static OtherType TheBoolTy ("bool" , Type::BoolTyID);
370 static SignedIntType TheSByteTy ("sbyte" , Type::SByteTyID);
371 static UnsignedIntType TheUByteTy ("ubyte" , Type::UByteTyID);
372 static SignedIntType TheShortTy ("short" , Type::ShortTyID);
373 static UnsignedIntType TheUShortTy("ushort", Type::UShortTyID);
374 static SignedIntType TheIntTy ("int" , Type::IntTyID);
375 static UnsignedIntType TheUIntTy ("uint" , Type::UIntTyID);
376 static SignedIntType TheLongTy ("long" , Type::LongTyID);
377 static UnsignedIntType TheULongTy ("ulong" , Type::ULongTyID);
378 static OtherType TheFloatTy ("float" , Type::FloatTyID);
379 static OtherType TheDoubleTy("double", Type::DoubleTyID);
380 static OtherType TheLabelTy ("label" , Type::LabelTyID);
382 Type *Type::VoidTy = &TheVoidTy;
383 Type *Type::BoolTy = &TheBoolTy;
384 Type *Type::SByteTy = &TheSByteTy;
385 Type *Type::UByteTy = &TheUByteTy;
386 Type *Type::ShortTy = &TheShortTy;
387 Type *Type::UShortTy = &TheUShortTy;
388 Type *Type::IntTy = &TheIntTy;
389 Type *Type::UIntTy = &TheUIntTy;
390 Type *Type::LongTy = &TheLongTy;
391 Type *Type::ULongTy = &TheULongTy;
392 Type *Type::FloatTy = &TheFloatTy;
393 Type *Type::DoubleTy = &TheDoubleTy;
394 Type *Type::LabelTy = &TheLabelTy;
397 //===----------------------------------------------------------------------===//
398 // Derived Type Constructors
399 //===----------------------------------------------------------------------===//
401 FunctionType::FunctionType(const Type *Result,
402 const std::vector<const Type*> &Params,
403 bool IsVarArgs) : DerivedType(FunctionTyID),
404 isVarArgs(IsVarArgs) {
405 bool isAbstract = Result->isAbstract();
406 ContainedTys.reserve(Params.size()+1);
407 ContainedTys.push_back(PATypeHandle(Result, this));
409 for (unsigned i = 0; i != Params.size(); ++i) {
410 ContainedTys.push_back(PATypeHandle(Params[i], this));
411 isAbstract |= Params[i]->isAbstract();
414 // Calculate whether or not this type is abstract
415 setAbstract(isAbstract);
418 StructType::StructType(const std::vector<const Type*> &Types)
419 : CompositeType(StructTyID) {
420 ContainedTys.reserve(Types.size());
421 bool isAbstract = false;
422 for (unsigned i = 0; i < Types.size(); ++i) {
423 assert(Types[i] != Type::VoidTy && "Void type for structure field!!");
424 ContainedTys.push_back(PATypeHandle(Types[i], this));
425 isAbstract |= Types[i]->isAbstract();
428 // Calculate whether or not this type is abstract
429 setAbstract(isAbstract);
432 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
433 : SequentialType(ArrayTyID, ElType) {
436 // Calculate whether or not this type is abstract
437 setAbstract(ElType->isAbstract());
440 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
441 // Calculate whether or not this type is abstract
442 setAbstract(E->isAbstract());
445 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
447 #ifdef DEBUG_MERGE_TYPES
448 std::cerr << "Derived new type: " << *this << "\n";
452 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
453 // another (more concrete) type, we must eliminate all references to other
454 // types, to avoid some circular reference problems.
455 void DerivedType::dropAllTypeUses() {
456 if (!ContainedTys.empty()) {
457 while (ContainedTys.size() > 1)
458 ContainedTys.pop_back();
460 // The type must stay abstract. To do this, we insert a pointer to a type
461 // that will never get resolved, thus will always be abstract.
462 static Type *AlwaysOpaqueTy = OpaqueType::get();
463 static PATypeHolder Holder(AlwaysOpaqueTy);
464 ContainedTys[0] = AlwaysOpaqueTy;
468 // isTypeAbstract - This is a recursive function that walks a type hierarchy
469 // calculating whether or not a type is abstract. Worst case it will have to do
470 // a lot of traversing if you have some whacko opaque types, but in most cases,
471 // it will do some simple stuff when it hits non-abstract types that aren't
474 bool Type::isTypeAbstract() {
475 if (!isAbstract()) // Base case for the recursion
476 return false; // Primitive = leaf type
478 if (isa<OpaqueType>(this)) // Base case for the recursion
479 return true; // This whole type is abstract!
481 // We have to guard against recursion. To do this, we temporarily mark this
482 // type as concrete, so that if we get back to here recursively we will think
483 // it's not abstract, and thus not scan it again.
486 // Scan all of the sub-types. If any of them are abstract, than so is this
488 for (Type::subtype_iterator I = subtype_begin(), E = subtype_end();
490 if (const_cast<Type*>(I->get())->isTypeAbstract()) {
491 setAbstract(true); // Restore the abstract bit.
492 return true; // This type is abstract if subtype is abstract!
495 // Restore the abstract bit.
498 // Nothing looks abstract here...
503 //===----------------------------------------------------------------------===//
504 // Type Structural Equality Testing
505 //===----------------------------------------------------------------------===//
507 // TypesEqual - Two types are considered structurally equal if they have the
508 // same "shape": Every level and element of the types have identical primitive
509 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
510 // be pointer equals to be equivalent though. This uses an optimistic algorithm
511 // that assumes that two graphs are the same until proven otherwise.
513 static bool TypesEqual(const Type *Ty, const Type *Ty2,
514 std::map<const Type *, const Type *> &EqTypes) {
515 if (Ty == Ty2) return true;
516 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
517 if (isa<OpaqueType>(Ty))
518 return false; // Two unequal opaque types are never equal
520 std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
521 if (It != EqTypes.end() && It->first == Ty)
522 return It->second == Ty2; // Looping back on a type, check for equality
524 // Otherwise, add the mapping to the table to make sure we don't get
525 // recursion on the types...
526 EqTypes.insert(It, std::make_pair(Ty, Ty2));
528 // Two really annoying special cases that breaks an otherwise nice simple
529 // algorithm is the fact that arraytypes have sizes that differentiates types,
530 // and that function types can be varargs or not. Consider this now.
532 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
533 return TypesEqual(PTy->getElementType(),
534 cast<PointerType>(Ty2)->getElementType(), EqTypes);
535 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
536 const StructType *STy2 = cast<StructType>(Ty2);
537 if (STy->getNumElements() != STy2->getNumElements()) return false;
538 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
539 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
542 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
543 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
544 return ATy->getNumElements() == ATy2->getNumElements() &&
545 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
546 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
547 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
548 if (FTy->isVarArg() != FTy2->isVarArg() ||
549 FTy->getNumParams() != FTy2->getNumParams() ||
550 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
552 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i)
553 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
557 assert(0 && "Unknown derived type!");
562 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
563 std::map<const Type *, const Type *> EqTypes;
564 return TypesEqual(Ty, Ty2, EqTypes);
567 // TypeHasCycleThrough - Return true there is a path from CurTy to TargetTy in
568 // the type graph. We know that Ty is an abstract type, so if we ever reach a
569 // non-abstract type, we know that we don't need to search the subgraph.
570 static bool TypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
571 std::set<const Type*> &VisitedTypes) {
572 if (TargetTy == CurTy) return true;
573 if (!CurTy->isAbstract()) return false;
575 std::set<const Type*>::iterator VTI = VisitedTypes.lower_bound(CurTy);
576 if (VTI != VisitedTypes.end() && *VTI == CurTy)
578 VisitedTypes.insert(VTI, CurTy);
580 for (Type::subtype_iterator I = CurTy->subtype_begin(),
581 E = CurTy->subtype_end(); I != E; ++I)
582 if (TypeHasCycleThrough(TargetTy, *I, VisitedTypes))
588 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
590 static bool TypeHasCycleThroughItself(const Type *Ty) {
591 assert(Ty->isAbstract() && "This code assumes that Ty was abstract!");
592 std::set<const Type*> VisitedTypes;
593 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
595 if (TypeHasCycleThrough(Ty, *I, VisitedTypes))
601 //===----------------------------------------------------------------------===//
602 // Derived Type Factory Functions
603 //===----------------------------------------------------------------------===//
605 // TypeMap - Make sure that only one instance of a particular type may be
606 // created on any given run of the compiler... note that this involves updating
607 // our map if an abstract type gets refined somehow.
610 template<class ValType, class TypeClass>
612 std::map<ValType, PATypeHolder> Map;
614 /// TypesByHash - Keep track of each type by its structure hash value.
616 std::multimap<unsigned, PATypeHolder> TypesByHash;
618 typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
619 ~TypeMap() { print("ON EXIT"); }
621 inline TypeClass *get(const ValType &V) {
622 iterator I = Map.find(V);
623 return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
626 inline void add(const ValType &V, TypeClass *Ty) {
627 Map.insert(std::make_pair(V, Ty));
629 // If this type has a cycle, remember it.
630 TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
634 void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
635 std::multimap<unsigned, PATypeHolder>::iterator I =
636 TypesByHash.lower_bound(Hash);
637 while (I->second != Ty) {
639 assert(I != TypesByHash.end() && I->first == Hash);
641 TypesByHash.erase(I);
644 /// finishRefinement - This method is called after we have updated an existing
645 /// type with its new components. We must now either merge the type away with
646 /// some other type or reinstall it in the map with it's new configuration.
647 /// The specified iterator tells us what the type USED to look like.
648 void finishRefinement(TypeClass *Ty, const DerivedType *OldType,
649 const Type *NewType) {
650 assert((Ty->isAbstract() || !OldType->isAbstract()) &&
651 "Refining a non-abstract type!");
652 #ifdef DEBUG_MERGE_TYPES
653 std::cerr << "refineAbstractTy(" << (void*)OldType << "[" << *OldType
654 << "], " << (void*)NewType << " [" << *NewType << "])\n";
657 // Make a temporary type holder for the type so that it doesn't disappear on
658 // us when we erase the entry from the map.
659 PATypeHolder TyHolder = Ty;
661 // The old record is now out-of-date, because one of the children has been
662 // updated. Remove the obsolete entry from the map.
663 Map.erase(ValType::get(Ty));
665 // Remember the structural hash for the type before we start hacking on it,
666 // in case we need it later. Also, check to see if the type HAD a cycle
667 // through it, if so, we know it will when we hack on it.
668 unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
670 // Find the type element we are refining... and change it now!
671 for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
672 if (Ty->ContainedTys[i] == OldType) {
673 Ty->ContainedTys[i].removeUserFromConcrete();
674 Ty->ContainedTys[i] = NewType;
677 unsigned TypeHash = ValType::hashTypeStructure(Ty);
679 // If there are no cycles going through this node, we can do a simple,
680 // efficient lookup in the map, instead of an inefficient nasty linear
682 bool TypeHasCycle = Ty->isAbstract() && TypeHasCycleThroughItself(Ty);
684 iterator I = Map.find(ValType::get(Ty));
685 if (I != Map.end()) {
686 // We already have this type in the table. Get rid of the newly refined
688 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
689 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
691 // Refined to a different type altogether?
692 RemoveFromTypesByHash(TypeHash, Ty);
693 Ty->refineAbstractTypeTo(NewTy);
698 // Now we check to see if there is an existing entry in the table which is
699 // structurally identical to the newly refined type. If so, this type
700 // gets refined to the pre-existing type.
702 std::multimap<unsigned, PATypeHolder>::iterator I,E, Entry;
703 tie(I, E) = TypesByHash.equal_range(TypeHash);
705 for (; I != E; ++I) {
706 if (I->second != Ty) {
707 if (TypesEqual(Ty, I->second)) {
708 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
709 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
712 // Find the location of Ty in the TypesByHash structure.
713 while (I->second != Ty) {
715 assert(I != E && "Structure doesn't contain type??");
720 TypesByHash.erase(Entry);
721 Ty->refineAbstractTypeTo(NewTy);
725 // Remember the position of
731 // If we succeeded, we need to insert the type into the cycletypes table.
732 // There are several cases here, depending on whether the original type
733 // had the same hash code and was itself cyclic.
734 if (TypeHash != OldTypeHash) {
735 RemoveFromTypesByHash(OldTypeHash, Ty);
736 TypesByHash.insert(std::make_pair(TypeHash, Ty));
739 // If there is no existing type of the same structure, we reinsert an
740 // updated record into the map.
741 Map.insert(std::make_pair(ValType::get(Ty), Ty));
743 // If the type is currently thought to be abstract, rescan all of our
744 // subtypes to see if the type has just become concrete!
745 if (Ty->isAbstract()) {
746 Ty->setAbstract(Ty->isTypeAbstract());
748 // If the type just became concrete, notify all users!
749 if (!Ty->isAbstract())
750 Ty->notifyUsesThatTypeBecameConcrete();
754 void print(const char *Arg) const {
755 #ifdef DEBUG_MERGE_TYPES
756 std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
758 for (typename std::map<ValType, PATypeHolder>::const_iterator I
759 = Map.begin(), E = Map.end(); I != E; ++I)
760 std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " "
761 << *I->second.get() << "\n";
765 void dump() const { print("dump output"); }
770 //===----------------------------------------------------------------------===//
771 // Function Type Factory and Value Class...
774 // FunctionValType - Define a class to hold the key that goes into the TypeMap
777 class FunctionValType {
779 std::vector<const Type*> ArgTypes;
782 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
783 bool IVA) : RetTy(ret), isVarArg(IVA) {
784 for (unsigned i = 0; i < args.size(); ++i)
785 ArgTypes.push_back(args[i]);
788 static FunctionValType get(const FunctionType *FT);
790 static unsigned hashTypeStructure(const FunctionType *FT) {
791 return FT->getNumParams()*2+FT->isVarArg();
794 // Subclass should override this... to update self as usual
795 void doRefinement(const DerivedType *OldType, const Type *NewType) {
796 if (RetTy == OldType) RetTy = NewType;
797 for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
798 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
801 inline bool operator<(const FunctionValType &MTV) const {
802 if (RetTy < MTV.RetTy) return true;
803 if (RetTy > MTV.RetTy) return false;
805 if (ArgTypes < MTV.ArgTypes) return true;
806 return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
811 // Define the actual map itself now...
812 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
814 FunctionValType FunctionValType::get(const FunctionType *FT) {
815 // Build up a FunctionValType
816 std::vector<const Type *> ParamTypes;
817 ParamTypes.reserve(FT->getNumParams());
818 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
819 ParamTypes.push_back(FT->getParamType(i));
820 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
824 // FunctionType::get - The factory function for the FunctionType class...
825 FunctionType *FunctionType::get(const Type *ReturnType,
826 const std::vector<const Type*> &Params,
828 FunctionValType VT(ReturnType, Params, isVarArg);
829 FunctionType *MT = FunctionTypes.get(VT);
832 FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
834 #ifdef DEBUG_MERGE_TYPES
835 std::cerr << "Derived new type: " << MT << "\n";
840 //===----------------------------------------------------------------------===//
841 // Array Type Factory...
848 ArrayValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
850 static ArrayValType get(const ArrayType *AT) {
851 return ArrayValType(AT->getElementType(), AT->getNumElements());
854 static unsigned hashTypeStructure(const ArrayType *AT) {
855 return AT->getNumElements();
858 // Subclass should override this... to update self as usual
859 void doRefinement(const DerivedType *OldType, const Type *NewType) {
860 assert(ValTy == OldType);
864 inline bool operator<(const ArrayValType &MTV) const {
865 if (Size < MTV.Size) return true;
866 return Size == MTV.Size && ValTy < MTV.ValTy;
870 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
873 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
874 assert(ElementType && "Can't get array of null types!");
876 ArrayValType AVT(ElementType, NumElements);
877 ArrayType *AT = ArrayTypes.get(AVT);
878 if (AT) return AT; // Found a match, return it!
880 // Value not found. Derive a new type!
881 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
883 #ifdef DEBUG_MERGE_TYPES
884 std::cerr << "Derived new type: " << *AT << "\n";
889 //===----------------------------------------------------------------------===//
890 // Struct Type Factory...
894 // StructValType - Define a class to hold the key that goes into the TypeMap
896 class StructValType {
897 std::vector<const Type*> ElTypes;
899 StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
901 static StructValType get(const StructType *ST) {
902 std::vector<const Type *> ElTypes;
903 ElTypes.reserve(ST->getNumElements());
904 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
905 ElTypes.push_back(ST->getElementType(i));
907 return StructValType(ElTypes);
910 static unsigned hashTypeStructure(const StructType *ST) {
911 return ST->getNumElements();
914 // Subclass should override this... to update self as usual
915 void doRefinement(const DerivedType *OldType, const Type *NewType) {
916 for (unsigned i = 0; i < ElTypes.size(); ++i)
917 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
920 inline bool operator<(const StructValType &STV) const {
921 return ElTypes < STV.ElTypes;
926 static TypeMap<StructValType, StructType> StructTypes;
928 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
929 StructValType STV(ETypes);
930 StructType *ST = StructTypes.get(STV);
933 // Value not found. Derive a new type!
934 StructTypes.add(STV, ST = new StructType(ETypes));
936 #ifdef DEBUG_MERGE_TYPES
937 std::cerr << "Derived new type: " << *ST << "\n";
944 //===----------------------------------------------------------------------===//
945 // Pointer Type Factory...
948 // PointerValType - Define a class to hold the key that goes into the TypeMap
951 class PointerValType {
954 PointerValType(const Type *val) : ValTy(val) {}
956 static PointerValType get(const PointerType *PT) {
957 return PointerValType(PT->getElementType());
960 static unsigned hashTypeStructure(const PointerType *PT) {
964 // Subclass should override this... to update self as usual
965 void doRefinement(const DerivedType *OldType, const Type *NewType) {
966 assert(ValTy == OldType);
970 bool operator<(const PointerValType &MTV) const {
971 return ValTy < MTV.ValTy;
976 static TypeMap<PointerValType, PointerType> PointerTypes;
978 PointerType *PointerType::get(const Type *ValueType) {
979 assert(ValueType && "Can't get a pointer to <null> type!");
980 PointerValType PVT(ValueType);
982 PointerType *PT = PointerTypes.get(PVT);
985 // Value not found. Derive a new type!
986 PointerTypes.add(PVT, PT = new PointerType(ValueType));
988 #ifdef DEBUG_MERGE_TYPES
989 std::cerr << "Derived new type: " << *PT << "\n";
995 //===----------------------------------------------------------------------===//
996 // Derived Type Refinement Functions
997 //===----------------------------------------------------------------------===//
999 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1000 // no longer has a handle to the type. This function is called primarily by
1001 // the PATypeHandle class. When there are no users of the abstract type, it
1002 // is annihilated, because there is no way to get a reference to it ever again.
1004 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
1005 // Search from back to front because we will notify users from back to
1006 // front. Also, it is likely that there will be a stack like behavior to
1007 // users that register and unregister users.
1010 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1011 assert(i != 0 && "AbstractTypeUser not in user list!");
1013 --i; // Convert to be in range 0 <= i < size()
1014 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1016 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1018 #ifdef DEBUG_MERGE_TYPES
1019 std::cerr << " remAbstractTypeUser[" << (void*)this << ", "
1020 << *this << "][" << i << "] User = " << U << "\n";
1023 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1024 #ifdef DEBUG_MERGE_TYPES
1025 std::cerr << "DELETEing unused abstract type: <" << *this
1026 << ">[" << (void*)this << "]" << "\n";
1028 delete this; // No users of this abstract type!
1033 // refineAbstractTypeTo - This function is used to when it is discovered that
1034 // the 'this' abstract type is actually equivalent to the NewType specified.
1035 // This causes all users of 'this' to switch to reference the more concrete type
1036 // NewType and for 'this' to be deleted.
1038 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1039 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1040 assert(this != NewType && "Can't refine to myself!");
1041 assert(ForwardType == 0 && "This type has already been refined!");
1043 // The descriptions may be out of date. Conservatively clear them all!
1044 AbstractTypeDescriptions.clear();
1046 #ifdef DEBUG_MERGE_TYPES
1047 std::cerr << "REFINING abstract type [" << (void*)this << " "
1048 << *this << "] to [" << (void*)NewType << " "
1049 << *NewType << "]!\n";
1052 // Make sure to put the type to be refined to into a holder so that if IT gets
1053 // refined, that we will not continue using a dead reference...
1055 PATypeHolder NewTy(NewType);
1057 // Any PATypeHolders referring to this type will now automatically forward to
1058 // the type we are resolved to.
1059 ForwardType = NewType;
1060 if (NewType->isAbstract())
1061 cast<DerivedType>(NewType)->addRef();
1063 // Add a self use of the current type so that we don't delete ourself until
1064 // after the function exits.
1066 PATypeHolder CurrentTy(this);
1068 // To make the situation simpler, we ask the subclass to remove this type from
1069 // the type map, and to replace any type uses with uses of non-abstract types.
1070 // This dramatically limits the amount of recursive type trouble we can find
1074 // Iterate over all of the uses of this type, invoking callback. Each user
1075 // should remove itself from our use list automatically. We have to check to
1076 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1077 // will not cause users to drop off of the use list. If we resolve to ourself
1080 while (!AbstractTypeUsers.empty() && NewTy != this) {
1081 AbstractTypeUser *User = AbstractTypeUsers.back();
1083 unsigned OldSize = AbstractTypeUsers.size();
1084 #ifdef DEBUG_MERGE_TYPES
1085 std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
1086 << "] of abstract type [" << (void*)this << " "
1087 << *this << "] to [" << (void*)NewTy.get() << " "
1088 << *NewTy << "]!\n";
1090 User->refineAbstractType(this, NewTy);
1092 assert(AbstractTypeUsers.size() != OldSize &&
1093 "AbsTyUser did not remove self from user list!");
1096 // If we were successful removing all users from the type, 'this' will be
1097 // deleted when the last PATypeHolder is destroyed or updated from this type.
1098 // This may occur on exit of this function, as the CurrentTy object is
1102 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1103 // the current type has transitioned from being abstract to being concrete.
1105 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1106 #ifdef DEBUG_MERGE_TYPES
1107 std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1110 unsigned OldSize = AbstractTypeUsers.size();
1111 while (!AbstractTypeUsers.empty()) {
1112 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1113 ATU->typeBecameConcrete(this);
1115 assert(AbstractTypeUsers.size() < OldSize-- &&
1116 "AbstractTypeUser did not remove itself from the use list!");
1123 // refineAbstractType - Called when a contained type is found to be more
1124 // concrete - this could potentially change us from an abstract type to a
1127 void FunctionType::refineAbstractType(const DerivedType *OldType,
1128 const Type *NewType) {
1129 FunctionTypes.finishRefinement(this, OldType, NewType);
1132 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1133 refineAbstractType(AbsTy, AbsTy);
1137 // refineAbstractType - Called when a contained type is found to be more
1138 // concrete - this could potentially change us from an abstract type to a
1141 void ArrayType::refineAbstractType(const DerivedType *OldType,
1142 const Type *NewType) {
1143 ArrayTypes.finishRefinement(this, OldType, NewType);
1146 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1147 refineAbstractType(AbsTy, AbsTy);
1151 // refineAbstractType - Called when a contained type is found to be more
1152 // concrete - this could potentially change us from an abstract type to a
1155 void StructType::refineAbstractType(const DerivedType *OldType,
1156 const Type *NewType) {
1157 StructTypes.finishRefinement(this, OldType, NewType);
1160 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1161 refineAbstractType(AbsTy, AbsTy);
1164 // refineAbstractType - Called when a contained type is found to be more
1165 // concrete - this could potentially change us from an abstract type to a
1168 void PointerType::refineAbstractType(const DerivedType *OldType,
1169 const Type *NewType) {
1170 PointerTypes.finishRefinement(this, OldType, NewType);
1173 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1174 refineAbstractType(AbsTy, AbsTy);
1177 bool SequentialType::indexValid(const Value *V) const {
1178 const Type *Ty = V->getType();
1179 switch (Ty->getTypeID()) {
1181 case Type::UIntTyID:
1182 case Type::LongTyID:
1183 case Type::ULongTyID:
1191 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1193 OS << "<null> value!\n";
1199 std::ostream &operator<<(std::ostream &OS, const Type &T) {