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 //===----------------------------------------------------------------------===//
329 // Static 'Type' data
330 //===----------------------------------------------------------------------===//
333 struct PrimType : public Type {
334 PrimType(const char *S, TypeID ID) : Type(S, ID) {}
338 static PrimType TheVoidTy ("void" , Type::VoidTyID);
339 static PrimType TheBoolTy ("bool" , Type::BoolTyID);
340 static PrimType TheSByteTy ("sbyte" , Type::SByteTyID);
341 static PrimType TheUByteTy ("ubyte" , Type::UByteTyID);
342 static PrimType TheShortTy ("short" , Type::ShortTyID);
343 static PrimType TheUShortTy("ushort", Type::UShortTyID);
344 static PrimType TheIntTy ("int" , Type::IntTyID);
345 static PrimType TheUIntTy ("uint" , Type::UIntTyID);
346 static PrimType TheLongTy ("long" , Type::LongTyID);
347 static PrimType TheULongTy ("ulong" , Type::ULongTyID);
348 static PrimType TheFloatTy ("float" , Type::FloatTyID);
349 static PrimType TheDoubleTy("double", Type::DoubleTyID);
350 static PrimType TheLabelTy ("label" , Type::LabelTyID);
352 Type *Type::VoidTy = &TheVoidTy;
353 Type *Type::BoolTy = &TheBoolTy;
354 Type *Type::SByteTy = &TheSByteTy;
355 Type *Type::UByteTy = &TheUByteTy;
356 Type *Type::ShortTy = &TheShortTy;
357 Type *Type::UShortTy = &TheUShortTy;
358 Type *Type::IntTy = &TheIntTy;
359 Type *Type::UIntTy = &TheUIntTy;
360 Type *Type::LongTy = &TheLongTy;
361 Type *Type::ULongTy = &TheULongTy;
362 Type *Type::FloatTy = &TheFloatTy;
363 Type *Type::DoubleTy = &TheDoubleTy;
364 Type *Type::LabelTy = &TheLabelTy;
367 //===----------------------------------------------------------------------===//
368 // Derived Type Constructors
369 //===----------------------------------------------------------------------===//
371 FunctionType::FunctionType(const Type *Result,
372 const std::vector<const Type*> &Params,
373 bool IsVarArgs) : DerivedType(FunctionTyID),
374 isVarArgs(IsVarArgs) {
375 assert((Result->isFirstClassType() || Result == Type::VoidTy ||
376 isa<OpaqueType>(Result)) &&
377 "LLVM functions cannot return aggregates");
378 bool isAbstract = Result->isAbstract();
379 ContainedTys.reserve(Params.size()+1);
380 ContainedTys.push_back(PATypeHandle(Result, this));
382 for (unsigned i = 0; i != Params.size(); ++i) {
383 ContainedTys.push_back(PATypeHandle(Params[i], this));
384 isAbstract |= Params[i]->isAbstract();
387 // Calculate whether or not this type is abstract
388 setAbstract(isAbstract);
391 StructType::StructType(const std::vector<const Type*> &Types)
392 : CompositeType(StructTyID) {
393 ContainedTys.reserve(Types.size());
394 bool isAbstract = false;
395 for (unsigned i = 0; i < Types.size(); ++i) {
396 assert(Types[i] != Type::VoidTy && "Void type for structure field!!");
397 ContainedTys.push_back(PATypeHandle(Types[i], this));
398 isAbstract |= Types[i]->isAbstract();
401 // Calculate whether or not this type is abstract
402 setAbstract(isAbstract);
405 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
406 : SequentialType(ArrayTyID, ElType) {
409 // Calculate whether or not this type is abstract
410 setAbstract(ElType->isAbstract());
413 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
414 // Calculate whether or not this type is abstract
415 setAbstract(E->isAbstract());
418 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
420 #ifdef DEBUG_MERGE_TYPES
421 std::cerr << "Derived new type: " << *this << "\n";
425 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
426 // another (more concrete) type, we must eliminate all references to other
427 // types, to avoid some circular reference problems.
428 void DerivedType::dropAllTypeUses() {
429 if (!ContainedTys.empty()) {
430 while (ContainedTys.size() > 1)
431 ContainedTys.pop_back();
433 // The type must stay abstract. To do this, we insert a pointer to a type
434 // that will never get resolved, thus will always be abstract.
435 static Type *AlwaysOpaqueTy = OpaqueType::get();
436 static PATypeHolder Holder(AlwaysOpaqueTy);
437 ContainedTys[0] = AlwaysOpaqueTy;
441 // isTypeAbstract - This is a recursive function that walks a type hierarchy
442 // calculating whether or not a type is abstract. Worst case it will have to do
443 // a lot of traversing if you have some whacko opaque types, but in most cases,
444 // it will do some simple stuff when it hits non-abstract types that aren't
447 bool Type::isTypeAbstract() {
448 if (!isAbstract()) // Base case for the recursion
449 return false; // Primitive = leaf type
451 if (isa<OpaqueType>(this)) // Base case for the recursion
452 return true; // This whole type is abstract!
454 // We have to guard against recursion. To do this, we temporarily mark this
455 // type as concrete, so that if we get back to here recursively we will think
456 // it's not abstract, and thus not scan it again.
459 // Scan all of the sub-types. If any of them are abstract, than so is this
461 for (Type::subtype_iterator I = subtype_begin(), E = subtype_end();
463 if (const_cast<Type*>(I->get())->isTypeAbstract()) {
464 setAbstract(true); // Restore the abstract bit.
465 return true; // This type is abstract if subtype is abstract!
468 // Restore the abstract bit.
471 // Nothing looks abstract here...
476 //===----------------------------------------------------------------------===//
477 // Type Structural Equality Testing
478 //===----------------------------------------------------------------------===//
480 // TypesEqual - Two types are considered structurally equal if they have the
481 // same "shape": Every level and element of the types have identical primitive
482 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
483 // be pointer equals to be equivalent though. This uses an optimistic algorithm
484 // that assumes that two graphs are the same until proven otherwise.
486 static bool TypesEqual(const Type *Ty, const Type *Ty2,
487 std::map<const Type *, const Type *> &EqTypes) {
488 if (Ty == Ty2) return true;
489 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
490 if (isa<OpaqueType>(Ty))
491 return false; // Two unequal opaque types are never equal
493 std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
494 if (It != EqTypes.end() && It->first == Ty)
495 return It->second == Ty2; // Looping back on a type, check for equality
497 // Otherwise, add the mapping to the table to make sure we don't get
498 // recursion on the types...
499 EqTypes.insert(It, std::make_pair(Ty, Ty2));
501 // Two really annoying special cases that breaks an otherwise nice simple
502 // algorithm is the fact that arraytypes have sizes that differentiates types,
503 // and that function types can be varargs or not. Consider this now.
505 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
506 return TypesEqual(PTy->getElementType(),
507 cast<PointerType>(Ty2)->getElementType(), EqTypes);
508 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
509 const StructType *STy2 = cast<StructType>(Ty2);
510 if (STy->getNumElements() != STy2->getNumElements()) return false;
511 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
512 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
515 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
516 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
517 return ATy->getNumElements() == ATy2->getNumElements() &&
518 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
519 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
520 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
521 if (FTy->isVarArg() != FTy2->isVarArg() ||
522 FTy->getNumParams() != FTy2->getNumParams() ||
523 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
525 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i)
526 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
530 assert(0 && "Unknown derived type!");
535 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
536 std::map<const Type *, const Type *> EqTypes;
537 return TypesEqual(Ty, Ty2, EqTypes);
540 // TypeHasCycleThrough - Return true there is a path from CurTy to TargetTy in
541 // the type graph. We know that Ty is an abstract type, so if we ever reach a
542 // non-abstract type, we know that we don't need to search the subgraph.
543 static bool TypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
544 std::set<const Type*> &VisitedTypes) {
545 if (TargetTy == CurTy) return true;
546 if (!CurTy->isAbstract()) return false;
548 std::set<const Type*>::iterator VTI = VisitedTypes.lower_bound(CurTy);
549 if (VTI != VisitedTypes.end() && *VTI == CurTy)
551 VisitedTypes.insert(VTI, CurTy);
553 for (Type::subtype_iterator I = CurTy->subtype_begin(),
554 E = CurTy->subtype_end(); I != E; ++I)
555 if (TypeHasCycleThrough(TargetTy, *I, VisitedTypes))
561 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
563 static bool TypeHasCycleThroughItself(const Type *Ty) {
564 assert(Ty->isAbstract() && "This code assumes that Ty was abstract!");
565 std::set<const Type*> VisitedTypes;
566 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
568 if (TypeHasCycleThrough(Ty, *I, VisitedTypes))
574 //===----------------------------------------------------------------------===//
575 // Derived Type Factory Functions
576 //===----------------------------------------------------------------------===//
578 // TypeMap - Make sure that only one instance of a particular type may be
579 // created on any given run of the compiler... note that this involves updating
580 // our map if an abstract type gets refined somehow.
583 template<class ValType, class TypeClass>
585 std::map<ValType, PATypeHolder> Map;
587 /// TypesByHash - Keep track of each type by its structure hash value.
589 std::multimap<unsigned, PATypeHolder> TypesByHash;
591 typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
592 ~TypeMap() { print("ON EXIT"); }
594 inline TypeClass *get(const ValType &V) {
595 iterator I = Map.find(V);
596 return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
599 inline void add(const ValType &V, TypeClass *Ty) {
600 Map.insert(std::make_pair(V, Ty));
602 // If this type has a cycle, remember it.
603 TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
607 void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
608 std::multimap<unsigned, PATypeHolder>::iterator I =
609 TypesByHash.lower_bound(Hash);
610 while (I->second != Ty) {
612 assert(I != TypesByHash.end() && I->first == Hash);
614 TypesByHash.erase(I);
617 /// finishRefinement - This method is called after we have updated an existing
618 /// type with its new components. We must now either merge the type away with
619 /// some other type or reinstall it in the map with it's new configuration.
620 /// The specified iterator tells us what the type USED to look like.
621 void finishRefinement(TypeClass *Ty, const DerivedType *OldType,
622 const Type *NewType) {
623 assert((Ty->isAbstract() || !OldType->isAbstract()) &&
624 "Refining a non-abstract type!");
625 #ifdef DEBUG_MERGE_TYPES
626 std::cerr << "refineAbstractTy(" << (void*)OldType << "[" << *OldType
627 << "], " << (void*)NewType << " [" << *NewType << "])\n";
630 // Make a temporary type holder for the type so that it doesn't disappear on
631 // us when we erase the entry from the map.
632 PATypeHolder TyHolder = Ty;
634 // The old record is now out-of-date, because one of the children has been
635 // updated. Remove the obsolete entry from the map.
636 Map.erase(ValType::get(Ty));
638 // Remember the structural hash for the type before we start hacking on it,
639 // in case we need it later. Also, check to see if the type HAD a cycle
640 // through it, if so, we know it will when we hack on it.
641 unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
643 // Find the type element we are refining... and change it now!
644 for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
645 if (Ty->ContainedTys[i] == OldType) {
646 Ty->ContainedTys[i].removeUserFromConcrete();
647 Ty->ContainedTys[i] = NewType;
650 unsigned TypeHash = ValType::hashTypeStructure(Ty);
652 // If there are no cycles going through this node, we can do a simple,
653 // efficient lookup in the map, instead of an inefficient nasty linear
655 bool TypeHasCycle = Ty->isAbstract() && TypeHasCycleThroughItself(Ty);
657 iterator I = Map.find(ValType::get(Ty));
658 if (I != Map.end()) {
659 // We already have this type in the table. Get rid of the newly refined
661 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
662 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
664 // Refined to a different type altogether?
665 RemoveFromTypesByHash(TypeHash, Ty);
666 Ty->refineAbstractTypeTo(NewTy);
671 // Now we check to see if there is an existing entry in the table which is
672 // structurally identical to the newly refined type. If so, this type
673 // gets refined to the pre-existing type.
675 std::multimap<unsigned, PATypeHolder>::iterator I,E, Entry;
676 tie(I, E) = TypesByHash.equal_range(TypeHash);
678 for (; I != E; ++I) {
679 if (I->second != Ty) {
680 if (TypesEqual(Ty, I->second)) {
681 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
682 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
685 // Find the location of Ty in the TypesByHash structure.
686 while (I->second != Ty) {
688 assert(I != E && "Structure doesn't contain type??");
693 TypesByHash.erase(Entry);
694 Ty->refineAbstractTypeTo(NewTy);
698 // Remember the position of
704 // If we succeeded, we need to insert the type into the cycletypes table.
705 // There are several cases here, depending on whether the original type
706 // had the same hash code and was itself cyclic.
707 if (TypeHash != OldTypeHash) {
708 RemoveFromTypesByHash(OldTypeHash, Ty);
709 TypesByHash.insert(std::make_pair(TypeHash, Ty));
712 // If there is no existing type of the same structure, we reinsert an
713 // updated record into the map.
714 Map.insert(std::make_pair(ValType::get(Ty), Ty));
716 // If the type is currently thought to be abstract, rescan all of our
717 // subtypes to see if the type has just become concrete!
718 if (Ty->isAbstract()) {
719 Ty->setAbstract(Ty->isTypeAbstract());
721 // If the type just became concrete, notify all users!
722 if (!Ty->isAbstract())
723 Ty->notifyUsesThatTypeBecameConcrete();
727 void print(const char *Arg) const {
728 #ifdef DEBUG_MERGE_TYPES
729 std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
731 for (typename std::map<ValType, PATypeHolder>::const_iterator I
732 = Map.begin(), E = Map.end(); I != E; ++I)
733 std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " "
734 << *I->second.get() << "\n";
738 void dump() const { print("dump output"); }
743 //===----------------------------------------------------------------------===//
744 // Function Type Factory and Value Class...
747 // FunctionValType - Define a class to hold the key that goes into the TypeMap
750 class FunctionValType {
752 std::vector<const Type*> ArgTypes;
755 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
756 bool IVA) : RetTy(ret), isVarArg(IVA) {
757 for (unsigned i = 0; i < args.size(); ++i)
758 ArgTypes.push_back(args[i]);
761 static FunctionValType get(const FunctionType *FT);
763 static unsigned hashTypeStructure(const FunctionType *FT) {
764 return FT->getNumParams()*2+FT->isVarArg();
767 // Subclass should override this... to update self as usual
768 void doRefinement(const DerivedType *OldType, const Type *NewType) {
769 if (RetTy == OldType) RetTy = NewType;
770 for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
771 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
774 inline bool operator<(const FunctionValType &MTV) const {
775 if (RetTy < MTV.RetTy) return true;
776 if (RetTy > MTV.RetTy) return false;
778 if (ArgTypes < MTV.ArgTypes) return true;
779 return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
784 // Define the actual map itself now...
785 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
787 FunctionValType FunctionValType::get(const FunctionType *FT) {
788 // Build up a FunctionValType
789 std::vector<const Type *> ParamTypes;
790 ParamTypes.reserve(FT->getNumParams());
791 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
792 ParamTypes.push_back(FT->getParamType(i));
793 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
797 // FunctionType::get - The factory function for the FunctionType class...
798 FunctionType *FunctionType::get(const Type *ReturnType,
799 const std::vector<const Type*> &Params,
801 FunctionValType VT(ReturnType, Params, isVarArg);
802 FunctionType *MT = FunctionTypes.get(VT);
805 FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
807 #ifdef DEBUG_MERGE_TYPES
808 std::cerr << "Derived new type: " << MT << "\n";
813 //===----------------------------------------------------------------------===//
814 // Array Type Factory...
821 ArrayValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
823 static ArrayValType get(const ArrayType *AT) {
824 return ArrayValType(AT->getElementType(), AT->getNumElements());
827 static unsigned hashTypeStructure(const ArrayType *AT) {
828 return AT->getNumElements();
831 // Subclass should override this... to update self as usual
832 void doRefinement(const DerivedType *OldType, const Type *NewType) {
833 assert(ValTy == OldType);
837 inline bool operator<(const ArrayValType &MTV) const {
838 if (Size < MTV.Size) return true;
839 return Size == MTV.Size && ValTy < MTV.ValTy;
843 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
846 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
847 assert(ElementType && "Can't get array of null types!");
849 ArrayValType AVT(ElementType, NumElements);
850 ArrayType *AT = ArrayTypes.get(AVT);
851 if (AT) return AT; // Found a match, return it!
853 // Value not found. Derive a new type!
854 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
856 #ifdef DEBUG_MERGE_TYPES
857 std::cerr << "Derived new type: " << *AT << "\n";
862 //===----------------------------------------------------------------------===//
863 // Struct Type Factory...
867 // StructValType - Define a class to hold the key that goes into the TypeMap
869 class StructValType {
870 std::vector<const Type*> ElTypes;
872 StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
874 static StructValType get(const StructType *ST) {
875 std::vector<const Type *> ElTypes;
876 ElTypes.reserve(ST->getNumElements());
877 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
878 ElTypes.push_back(ST->getElementType(i));
880 return StructValType(ElTypes);
883 static unsigned hashTypeStructure(const StructType *ST) {
884 return ST->getNumElements();
887 // Subclass should override this... to update self as usual
888 void doRefinement(const DerivedType *OldType, const Type *NewType) {
889 for (unsigned i = 0; i < ElTypes.size(); ++i)
890 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
893 inline bool operator<(const StructValType &STV) const {
894 return ElTypes < STV.ElTypes;
899 static TypeMap<StructValType, StructType> StructTypes;
901 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
902 StructValType STV(ETypes);
903 StructType *ST = StructTypes.get(STV);
906 // Value not found. Derive a new type!
907 StructTypes.add(STV, ST = new StructType(ETypes));
909 #ifdef DEBUG_MERGE_TYPES
910 std::cerr << "Derived new type: " << *ST << "\n";
917 //===----------------------------------------------------------------------===//
918 // Pointer Type Factory...
921 // PointerValType - Define a class to hold the key that goes into the TypeMap
924 class PointerValType {
927 PointerValType(const Type *val) : ValTy(val) {}
929 static PointerValType get(const PointerType *PT) {
930 return PointerValType(PT->getElementType());
933 static unsigned hashTypeStructure(const PointerType *PT) {
937 // Subclass should override this... to update self as usual
938 void doRefinement(const DerivedType *OldType, const Type *NewType) {
939 assert(ValTy == OldType);
943 bool operator<(const PointerValType &MTV) const {
944 return ValTy < MTV.ValTy;
949 static TypeMap<PointerValType, PointerType> PointerTypes;
951 PointerType *PointerType::get(const Type *ValueType) {
952 assert(ValueType && "Can't get a pointer to <null> type!");
953 PointerValType PVT(ValueType);
955 PointerType *PT = PointerTypes.get(PVT);
958 // Value not found. Derive a new type!
959 PointerTypes.add(PVT, PT = new PointerType(ValueType));
961 #ifdef DEBUG_MERGE_TYPES
962 std::cerr << "Derived new type: " << *PT << "\n";
968 //===----------------------------------------------------------------------===//
969 // Derived Type Refinement Functions
970 //===----------------------------------------------------------------------===//
972 // removeAbstractTypeUser - Notify an abstract type that a user of the class
973 // no longer has a handle to the type. This function is called primarily by
974 // the PATypeHandle class. When there are no users of the abstract type, it
975 // is annihilated, because there is no way to get a reference to it ever again.
977 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
978 // Search from back to front because we will notify users from back to
979 // front. Also, it is likely that there will be a stack like behavior to
980 // users that register and unregister users.
983 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
984 assert(i != 0 && "AbstractTypeUser not in user list!");
986 --i; // Convert to be in range 0 <= i < size()
987 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
989 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
991 #ifdef DEBUG_MERGE_TYPES
992 std::cerr << " remAbstractTypeUser[" << (void*)this << ", "
993 << *this << "][" << i << "] User = " << U << "\n";
996 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
997 #ifdef DEBUG_MERGE_TYPES
998 std::cerr << "DELETEing unused abstract type: <" << *this
999 << ">[" << (void*)this << "]" << "\n";
1001 delete this; // No users of this abstract type!
1006 // refineAbstractTypeTo - This function is used to when it is discovered that
1007 // the 'this' abstract type is actually equivalent to the NewType specified.
1008 // This causes all users of 'this' to switch to reference the more concrete type
1009 // NewType and for 'this' to be deleted.
1011 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1012 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1013 assert(this != NewType && "Can't refine to myself!");
1014 assert(ForwardType == 0 && "This type has already been refined!");
1016 // The descriptions may be out of date. Conservatively clear them all!
1017 AbstractTypeDescriptions.clear();
1019 #ifdef DEBUG_MERGE_TYPES
1020 std::cerr << "REFINING abstract type [" << (void*)this << " "
1021 << *this << "] to [" << (void*)NewType << " "
1022 << *NewType << "]!\n";
1025 // Make sure to put the type to be refined to into a holder so that if IT gets
1026 // refined, that we will not continue using a dead reference...
1028 PATypeHolder NewTy(NewType);
1030 // Any PATypeHolders referring to this type will now automatically forward to
1031 // the type we are resolved to.
1032 ForwardType = NewType;
1033 if (NewType->isAbstract())
1034 cast<DerivedType>(NewType)->addRef();
1036 // Add a self use of the current type so that we don't delete ourself until
1037 // after the function exits.
1039 PATypeHolder CurrentTy(this);
1041 // To make the situation simpler, we ask the subclass to remove this type from
1042 // the type map, and to replace any type uses with uses of non-abstract types.
1043 // This dramatically limits the amount of recursive type trouble we can find
1047 // Iterate over all of the uses of this type, invoking callback. Each user
1048 // should remove itself from our use list automatically. We have to check to
1049 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1050 // will not cause users to drop off of the use list. If we resolve to ourself
1053 while (!AbstractTypeUsers.empty() && NewTy != this) {
1054 AbstractTypeUser *User = AbstractTypeUsers.back();
1056 unsigned OldSize = AbstractTypeUsers.size();
1057 #ifdef DEBUG_MERGE_TYPES
1058 std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
1059 << "] of abstract type [" << (void*)this << " "
1060 << *this << "] to [" << (void*)NewTy.get() << " "
1061 << *NewTy << "]!\n";
1063 User->refineAbstractType(this, NewTy);
1065 assert(AbstractTypeUsers.size() != OldSize &&
1066 "AbsTyUser did not remove self from user list!");
1069 // If we were successful removing all users from the type, 'this' will be
1070 // deleted when the last PATypeHolder is destroyed or updated from this type.
1071 // This may occur on exit of this function, as the CurrentTy object is
1075 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1076 // the current type has transitioned from being abstract to being concrete.
1078 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1079 #ifdef DEBUG_MERGE_TYPES
1080 std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1083 unsigned OldSize = AbstractTypeUsers.size();
1084 while (!AbstractTypeUsers.empty()) {
1085 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1086 ATU->typeBecameConcrete(this);
1088 assert(AbstractTypeUsers.size() < OldSize-- &&
1089 "AbstractTypeUser did not remove itself from the use list!");
1096 // refineAbstractType - Called when a contained type is found to be more
1097 // concrete - this could potentially change us from an abstract type to a
1100 void FunctionType::refineAbstractType(const DerivedType *OldType,
1101 const Type *NewType) {
1102 FunctionTypes.finishRefinement(this, OldType, NewType);
1105 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1106 refineAbstractType(AbsTy, AbsTy);
1110 // refineAbstractType - Called when a contained type is found to be more
1111 // concrete - this could potentially change us from an abstract type to a
1114 void ArrayType::refineAbstractType(const DerivedType *OldType,
1115 const Type *NewType) {
1116 ArrayTypes.finishRefinement(this, OldType, NewType);
1119 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1120 refineAbstractType(AbsTy, AbsTy);
1124 // refineAbstractType - Called when a contained type is found to be more
1125 // concrete - this could potentially change us from an abstract type to a
1128 void StructType::refineAbstractType(const DerivedType *OldType,
1129 const Type *NewType) {
1130 StructTypes.finishRefinement(this, OldType, NewType);
1133 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1134 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 PointerType::refineAbstractType(const DerivedType *OldType,
1142 const Type *NewType) {
1143 PointerTypes.finishRefinement(this, OldType, NewType);
1146 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1147 refineAbstractType(AbsTy, AbsTy);
1150 bool SequentialType::indexValid(const Value *V) const {
1151 const Type *Ty = V->getType();
1152 switch (Ty->getTypeID()) {
1154 case Type::UIntTyID:
1155 case Type::LongTyID:
1156 case Type::ULongTyID:
1164 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1166 OS << "<null> value!\n";
1172 std::ostream &operator<<(std::ostream &OS, const Type &T) {