1 //===-- Type.cpp - Implement the Type class -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Type class for the VMCore library.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/DerivedTypes.h"
15 #include "llvm/SymbolTable.h"
16 #include "llvm/Constants.h"
17 #include "Support/DepthFirstIterator.h"
18 #include "Support/StringExtras.h"
19 #include "Support/STLExtras.h"
20 #include "Support/Statistic.h"
25 static Statistic<> NumSlowTypes("type", "num slow types");
26 static Statistic<> NumTypeEqualsCalls("type", "num typeequals calls");
27 static Statistic<> NumTypeEquals("type", "num types actually equal");
29 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
30 // created and later destroyed, all in an effort to make sure that there is only
31 // a single canonical version of a type.
33 //#define DEBUG_MERGE_TYPES 1
36 //===----------------------------------------------------------------------===//
37 // Type Class Implementation
38 //===----------------------------------------------------------------------===//
40 static unsigned CurUID = 0;
41 static std::vector<const Type *> UIDMappings;
43 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
44 // for types as they are needed. Because resolution of types must invalidate
45 // all of the abstract type descriptions, we keep them in a seperate map to make
47 static std::map<const Type*, std::string> ConcreteTypeDescriptions;
48 static std::map<const Type*, std::string> AbstractTypeDescriptions;
50 Type::Type(const std::string &name, PrimitiveID id)
51 : Value(Type::TypeTy, Value::TypeVal), ForwardType(0) {
53 ConcreteTypeDescriptions[this] = name;
56 UID = CurUID++; // Assign types UID's as they are created
57 UIDMappings.push_back(this);
60 void Type::setName(const std::string &Name, SymbolTable *ST) {
61 assert(ST && "Type::setName - Must provide symbol table argument!");
63 if (Name.size()) ST->insert(Name, this);
67 const Type *Type::getUniqueIDType(unsigned UID) {
68 assert(UID < UIDMappings.size() &&
69 "Type::getPrimitiveType: UID out of range!");
70 return UIDMappings[UID];
73 const Type *Type::getPrimitiveType(PrimitiveID IDNumber) {
75 case VoidTyID : return VoidTy;
76 case BoolTyID : return BoolTy;
77 case UByteTyID : return UByteTy;
78 case SByteTyID : return SByteTy;
79 case UShortTyID: return UShortTy;
80 case ShortTyID : return ShortTy;
81 case UIntTyID : return UIntTy;
82 case IntTyID : return IntTy;
83 case ULongTyID : return ULongTy;
84 case LongTyID : return LongTy;
85 case FloatTyID : return FloatTy;
86 case DoubleTyID: return DoubleTy;
87 case TypeTyID : return TypeTy;
88 case LabelTyID : return LabelTy;
94 // isLosslesslyConvertibleTo - Return true if this type can be converted to
95 // 'Ty' without any reinterpretation of bits. For example, uint to int.
97 bool Type::isLosslesslyConvertibleTo(const Type *Ty) const {
98 if (this == Ty) return true;
99 if ((!isPrimitiveType() && !isa<PointerType>(this)) ||
100 (!isa<PointerType>(Ty) && !Ty->isPrimitiveType())) return false;
102 if (getPrimitiveID() == Ty->getPrimitiveID())
103 return true; // Handles identity cast, and cast of differing pointer types
105 // Now we know that they are two differing primitive or pointer types
106 switch (getPrimitiveID()) {
107 case Type::UByteTyID: return Ty == Type::SByteTy;
108 case Type::SByteTyID: return Ty == Type::UByteTy;
109 case Type::UShortTyID: return Ty == Type::ShortTy;
110 case Type::ShortTyID: return Ty == Type::UShortTy;
111 case Type::UIntTyID: return Ty == Type::IntTy;
112 case Type::IntTyID: return Ty == Type::UIntTy;
113 case Type::ULongTyID: return Ty == Type::LongTy;
114 case Type::LongTyID: return Ty == Type::ULongTy;
115 case Type::PointerTyID: return isa<PointerType>(Ty);
117 return false; // Other types have no identity values
121 // getPrimitiveSize - Return the basic size of this type if it is a primitive
122 // type. These are fixed by LLVM and are not target dependent. This will
123 // return zero if the type does not have a size or is not a primitive type.
125 unsigned Type::getPrimitiveSize() const {
126 switch (getPrimitiveID()) {
127 #define HANDLE_PRIM_TYPE(TY,SIZE) case TY##TyID: return SIZE;
128 #include "llvm/Type.def"
134 /// getForwardedTypeInternal - This method is used to implement the union-find
135 /// algorithm for when a type is being forwarded to another type.
136 const Type *Type::getForwardedTypeInternal() const {
137 assert(ForwardType && "This type is not being forwarded to another type!");
139 // Check to see if the forwarded type has been forwarded on. If so, collapse
140 // the forwarding links.
141 const Type *RealForwardedType = ForwardType->getForwardedType();
142 if (!RealForwardedType)
143 return ForwardType; // No it's not forwarded again
145 // Yes, it is forwarded again. First thing, add the reference to the new
147 if (RealForwardedType->isAbstract())
148 cast<DerivedType>(RealForwardedType)->addRef();
150 // Now drop the old reference. This could cause ForwardType to get deleted.
151 cast<DerivedType>(ForwardType)->dropRef();
153 // Return the updated type.
154 ForwardType = RealForwardedType;
158 // getTypeDescription - This is a recursive function that walks a type hierarchy
159 // calculating the description for a type.
161 static std::string getTypeDescription(const Type *Ty,
162 std::vector<const Type *> &TypeStack) {
163 if (isa<OpaqueType>(Ty)) { // Base case for the recursion
164 std::map<const Type*, std::string>::iterator I =
165 AbstractTypeDescriptions.lower_bound(Ty);
166 if (I != AbstractTypeDescriptions.end() && I->first == Ty)
168 std::string Desc = "opaque"+utostr(Ty->getUniqueID());
169 AbstractTypeDescriptions.insert(std::make_pair(Ty, Desc));
173 if (!Ty->isAbstract()) { // Base case for the recursion
174 std::map<const Type*, std::string>::iterator I =
175 ConcreteTypeDescriptions.find(Ty);
176 if (I != ConcreteTypeDescriptions.end()) return I->second;
179 // Check to see if the Type is already on the stack...
180 unsigned Slot = 0, CurSize = TypeStack.size();
181 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
183 // This is another base case for the recursion. In this case, we know
184 // that we have looped back to a type that we have previously visited.
185 // Generate the appropriate upreference to handle this.
188 return "\\" + utostr(CurSize-Slot); // Here's the upreference
190 // Recursive case: derived types...
192 TypeStack.push_back(Ty); // Add us to the stack..
194 switch (Ty->getPrimitiveID()) {
195 case Type::FunctionTyID: {
196 const FunctionType *FTy = cast<FunctionType>(Ty);
197 Result = getTypeDescription(FTy->getReturnType(), TypeStack) + " (";
198 for (FunctionType::param_iterator I = FTy->param_begin(),
199 E = FTy->param_end(); I != E; ++I) {
200 if (I != FTy->param_begin())
202 Result += getTypeDescription(*I, TypeStack);
204 if (FTy->isVarArg()) {
205 if (FTy->getNumParams()) Result += ", ";
211 case Type::StructTyID: {
212 const StructType *STy = cast<StructType>(Ty);
214 for (StructType::element_iterator I = STy->element_begin(),
215 E = STy->element_end(); I != E; ++I) {
216 if (I != STy->element_begin())
218 Result += getTypeDescription(*I, TypeStack);
223 case Type::PointerTyID: {
224 const PointerType *PTy = cast<PointerType>(Ty);
225 Result = getTypeDescription(PTy->getElementType(), TypeStack) + " *";
228 case Type::ArrayTyID: {
229 const ArrayType *ATy = cast<ArrayType>(Ty);
230 unsigned NumElements = ATy->getNumElements();
232 Result += utostr(NumElements) + " x ";
233 Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
238 assert(0 && "Unhandled type in getTypeDescription!");
241 TypeStack.pop_back(); // Remove self from stack...
248 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
250 std::map<const Type*, std::string>::iterator I = Map.find(Ty);
251 if (I != Map.end()) return I->second;
253 std::vector<const Type *> TypeStack;
254 return Map[Ty] = getTypeDescription(Ty, TypeStack);
258 const std::string &Type::getDescription() const {
260 return getOrCreateDesc(AbstractTypeDescriptions, this);
262 return getOrCreateDesc(ConcreteTypeDescriptions, this);
266 bool StructType::indexValid(const Value *V) const {
267 // Structure indexes require unsigned integer constants.
268 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(V))
269 return CU->getValue() < ContainedTys.size();
273 // getTypeAtIndex - Given an index value into the type, return the type of the
274 // element. For a structure type, this must be a constant value...
276 const Type *StructType::getTypeAtIndex(const Value *V) const {
277 assert(isa<Constant>(V) && "Structure index must be a constant!!");
278 unsigned Idx = cast<ConstantUInt>(V)->getValue();
279 assert(Idx < ContainedTys.size() && "Structure index out of range!");
280 assert(indexValid(V) && "Invalid structure index!"); // Duplicate check
281 return ContainedTys[Idx];
285 //===----------------------------------------------------------------------===//
287 //===----------------------------------------------------------------------===//
289 // These classes are used to implement specialized behavior for each different
292 struct SignedIntType : public Type {
293 SignedIntType(const std::string &Name, PrimitiveID id) : Type(Name, id) {}
295 // isSigned - Return whether a numeric type is signed.
296 virtual bool isSigned() const { return 1; }
298 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
299 // virtual function invocation.
301 virtual bool isInteger() const { return 1; }
304 struct UnsignedIntType : public Type {
305 UnsignedIntType(const std::string &N, PrimitiveID id) : Type(N, id) {}
307 // isUnsigned - Return whether a numeric type is signed.
308 virtual bool isUnsigned() const { return 1; }
310 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
311 // virtual function invocation.
313 virtual bool isInteger() const { return 1; }
316 struct OtherType : public Type {
317 OtherType(const std::string &N, PrimitiveID id) : Type(N, id) {}
320 static struct TypeType : public Type {
321 TypeType() : Type("type", TypeTyID) {}
322 } TheTypeTy; // Implement the type that is global.
325 //===----------------------------------------------------------------------===//
326 // Static 'Type' data
327 //===----------------------------------------------------------------------===//
329 static OtherType TheVoidTy ("void" , Type::VoidTyID);
330 static OtherType TheBoolTy ("bool" , Type::BoolTyID);
331 static SignedIntType TheSByteTy ("sbyte" , Type::SByteTyID);
332 static UnsignedIntType TheUByteTy ("ubyte" , Type::UByteTyID);
333 static SignedIntType TheShortTy ("short" , Type::ShortTyID);
334 static UnsignedIntType TheUShortTy("ushort", Type::UShortTyID);
335 static SignedIntType TheIntTy ("int" , Type::IntTyID);
336 static UnsignedIntType TheUIntTy ("uint" , Type::UIntTyID);
337 static SignedIntType TheLongTy ("long" , Type::LongTyID);
338 static UnsignedIntType TheULongTy ("ulong" , Type::ULongTyID);
339 static OtherType TheFloatTy ("float" , Type::FloatTyID);
340 static OtherType TheDoubleTy("double", Type::DoubleTyID);
341 static OtherType TheLabelTy ("label" , Type::LabelTyID);
343 Type *Type::VoidTy = &TheVoidTy;
344 Type *Type::BoolTy = &TheBoolTy;
345 Type *Type::SByteTy = &TheSByteTy;
346 Type *Type::UByteTy = &TheUByteTy;
347 Type *Type::ShortTy = &TheShortTy;
348 Type *Type::UShortTy = &TheUShortTy;
349 Type *Type::IntTy = &TheIntTy;
350 Type *Type::UIntTy = &TheUIntTy;
351 Type *Type::LongTy = &TheLongTy;
352 Type *Type::ULongTy = &TheULongTy;
353 Type *Type::FloatTy = &TheFloatTy;
354 Type *Type::DoubleTy = &TheDoubleTy;
355 Type *Type::TypeTy = &TheTypeTy;
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 bool isAbstract = Result->isAbstract();
368 ContainedTys.reserve(Params.size()+1);
369 ContainedTys.push_back(PATypeHandle(Result, this));
371 for (unsigned i = 0; i != Params.size(); ++i) {
372 ContainedTys.push_back(PATypeHandle(Params[i], this));
373 isAbstract |= Params[i]->isAbstract();
376 // Calculate whether or not this type is abstract
377 setAbstract(isAbstract);
380 StructType::StructType(const std::vector<const Type*> &Types)
381 : CompositeType(StructTyID) {
382 ContainedTys.reserve(Types.size());
383 bool isAbstract = false;
384 for (unsigned i = 0; i < Types.size(); ++i) {
385 assert(Types[i] != Type::VoidTy && "Void type in method prototype!!");
386 ContainedTys.push_back(PATypeHandle(Types[i], this));
387 isAbstract |= Types[i]->isAbstract();
390 // Calculate whether or not this type is abstract
391 setAbstract(isAbstract);
394 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
395 : SequentialType(ArrayTyID, ElType) {
398 // Calculate whether or not this type is abstract
399 setAbstract(ElType->isAbstract());
402 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
403 // Calculate whether or not this type is abstract
404 setAbstract(E->isAbstract());
407 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
409 #ifdef DEBUG_MERGE_TYPES
410 std::cerr << "Derived new type: " << *this << "\n";
414 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
415 // another (more concrete) type, we must eliminate all references to other
416 // types, to avoid some circular reference problems.
417 void DerivedType::dropAllTypeUses() {
418 if (!ContainedTys.empty()) {
419 while (ContainedTys.size() > 1)
420 ContainedTys.pop_back();
422 // The type must stay abstract. To do this, we insert a pointer to a type
423 // that will never get resolved, thus will always be abstract.
424 static Type *AlwaysOpaqueTy = OpaqueType::get();
425 static PATypeHolder Holder(AlwaysOpaqueTy);
426 ContainedTys[0] = AlwaysOpaqueTy;
430 // isTypeAbstract - This is a recursive function that walks a type hierarchy
431 // calculating whether or not a type is abstract. Worst case it will have to do
432 // a lot of traversing if you have some whacko opaque types, but in most cases,
433 // it will do some simple stuff when it hits non-abstract types that aren't
436 bool Type::isTypeAbstract() {
437 if (!isAbstract()) // Base case for the recursion
438 return false; // Primitive = leaf type
440 if (isa<OpaqueType>(this)) // Base case for the recursion
441 return true; // This whole type is abstract!
443 // We have to guard against recursion. To do this, we temporarily mark this
444 // type as concrete, so that if we get back to here recursively we will think
445 // it's not abstract, and thus not scan it again.
448 // Scan all of the sub-types. If any of them are abstract, than so is this
450 for (Type::subtype_iterator I = subtype_begin(), E = subtype_end();
452 if (const_cast<Type*>(I->get())->isTypeAbstract()) {
453 setAbstract(true); // Restore the abstract bit.
454 return true; // This type is abstract if subtype is abstract!
457 // Restore the abstract bit.
460 // Nothing looks abstract here...
465 //===----------------------------------------------------------------------===//
466 // Type Structural Equality Testing
467 //===----------------------------------------------------------------------===//
469 // TypesEqual - Two types are considered structurally equal if they have the
470 // same "shape": Every level and element of the types have identical primitive
471 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
472 // be pointer equals to be equivalent though. This uses an optimistic algorithm
473 // that assumes that two graphs are the same until proven otherwise.
475 static bool TypesEqual(const Type *Ty, const Type *Ty2,
476 std::map<const Type *, const Type *> &EqTypes) {
477 if (Ty == Ty2) return true;
478 if (Ty->getPrimitiveID() != Ty2->getPrimitiveID()) return false;
479 if (isa<OpaqueType>(Ty))
480 return false; // Two unequal opaque types are never equal
482 std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
483 if (It != EqTypes.end() && It->first == Ty)
484 return It->second == Ty2; // Looping back on a type, check for equality
486 // Otherwise, add the mapping to the table to make sure we don't get
487 // recursion on the types...
488 EqTypes.insert(It, std::make_pair(Ty, Ty2));
490 // Two really annoying special cases that breaks an otherwise nice simple
491 // algorithm is the fact that arraytypes have sizes that differentiates types,
492 // and that function types can be varargs or not. Consider this now.
494 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
495 return TypesEqual(PTy->getElementType(),
496 cast<PointerType>(Ty2)->getElementType(), EqTypes);
497 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
498 const StructType *STy2 = cast<StructType>(Ty2);
499 if (STy->getNumElements() != STy2->getNumElements()) return false;
500 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
501 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
504 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
505 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
506 return ATy->getNumElements() == ATy2->getNumElements() &&
507 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
508 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
509 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
510 if (FTy->isVarArg() != FTy2->isVarArg() ||
511 FTy->getNumParams() != FTy2->getNumParams() ||
512 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
514 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i)
515 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
519 assert(0 && "Unknown derived type!");
524 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
525 std::map<const Type *, const Type *> EqTypes;
526 return TypesEqual(Ty, Ty2, EqTypes);
529 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
531 static bool TypeHasCycleThroughItself(const Type *Ty) {
532 std::set<const Type*> VisitedTypes;
533 for (Type::subtype_iterator I = Ty->subtype_begin(),
534 E = Ty->subtype_end(); I != E; ++I)
535 for (df_ext_iterator<const Type *, std::set<const Type*> >
536 DFI = df_ext_begin(I->get(), VisitedTypes),
537 E = df_ext_end(I->get(), VisitedTypes); DFI != E; ++DFI)
539 return true; // Found a cycle through ty!
544 //===----------------------------------------------------------------------===//
545 // Derived Type Factory Functions
546 //===----------------------------------------------------------------------===//
548 // TypeMap - Make sure that only one instance of a particular type may be
549 // created on any given run of the compiler... note that this involves updating
550 // our map if an abstract type gets refined somehow.
553 template<class ValType, class TypeClass>
555 std::map<ValType, PATypeHolder> Map;
557 /// TypesByHash - Keep track of each type by its structure hash value.
559 std::multimap<unsigned, PATypeHolder> TypesByHash;
561 typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
562 ~TypeMap() { print("ON EXIT"); }
564 inline TypeClass *get(const ValType &V) {
565 iterator I = Map.find(V);
566 return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
569 inline void add(const ValType &V, TypeClass *Ty) {
570 Map.insert(std::make_pair(V, Ty));
572 // If this type has a cycle, remember it.
573 TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
577 void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
578 std::multimap<unsigned, PATypeHolder>::iterator I =
579 TypesByHash.lower_bound(Hash);
580 while (I->second != Ty) {
582 assert(I != TypesByHash.end() && I->first == Hash);
584 TypesByHash.erase(I);
587 /// finishRefinement - This method is called after we have updated an existing
588 /// type with its new components. We must now either merge the type away with
589 /// some other type or reinstall it in the map with it's new configuration.
590 /// The specified iterator tells us what the type USED to look like.
591 void finishRefinement(TypeClass *Ty, const DerivedType *OldType,
592 const Type *NewType) {
593 assert((Ty->isAbstract() || !OldType->isAbstract()) &&
594 "Refining a non-abstract type!");
595 #ifdef DEBUG_MERGE_TYPES
596 std::cerr << "refineAbstractTy(" << (void*)OldType << "[" << *OldType
597 << "], " << (void*)NewType << " [" << *NewType << "])\n";
600 // Make a temporary type holder for the type so that it doesn't disappear on
601 // us when we erase the entry from the map.
602 PATypeHolder TyHolder = Ty;
604 // The old record is now out-of-date, because one of the children has been
605 // updated. Remove the obsolete entry from the map.
606 Map.erase(ValType::get(Ty));
608 // Remember the structural hash for the type before we start hacking on it,
609 // in case we need it later. Also, check to see if the type HAD a cycle
610 // through it, if so, we know it will when we hack on it.
611 unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
613 // Find the type element we are refining... and change it now!
614 for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
615 if (Ty->ContainedTys[i] == OldType) {
616 Ty->ContainedTys[i].removeUserFromConcrete();
617 Ty->ContainedTys[i] = NewType;
620 unsigned TypeHash = ValType::hashTypeStructure(Ty);
622 // If there are no cycles going through this node, we can do a simple,
623 // efficient lookup in the map, instead of an inefficient nasty linear
625 bool TypeHasCycle = TypeHasCycleThroughItself(Ty);
627 iterator I = Map.find(ValType::get(Ty));
628 if (I != Map.end()) {
629 // We already have this type in the table. Get rid of the newly refined
631 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
632 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
634 // Refined to a different type altogether?
635 RemoveFromTypesByHash(TypeHash, Ty);
636 Ty->refineAbstractTypeTo(NewTy);
643 // Now we check to see if there is an existing entry in the table which is
644 // structurally identical to the newly refined type. If so, this type
645 // gets refined to the pre-existing type.
647 std::multimap<unsigned, PATypeHolder>::iterator I,E, Entry;
648 tie(I, E) = TypesByHash.equal_range(TypeHash);
650 for (; I != E; ++I) {
651 ++NumTypeEqualsCalls;
652 if (I->second != Ty) {
653 if (TypesEqual(Ty, I->second)) {
656 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
657 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
660 // Find the location of Ty in the TypesByHash structure.
661 while (I->second != Ty) {
663 assert(I != E && "Structure doesn't contain type??");
668 TypesByHash.erase(Entry);
669 Ty->refineAbstractTypeTo(NewTy);
673 // Remember the position of
679 // If we succeeded, we need to insert the type into the cycletypes table.
680 // There are several cases here, depending on whether the original type
681 // had the same hash code and was itself cyclic.
682 if (TypeHash != OldTypeHash) {
683 RemoveFromTypesByHash(OldTypeHash, Ty);
684 TypesByHash.insert(std::make_pair(TypeHash, Ty));
687 // If there is no existing type of the same structure, we reinsert an
688 // updated record into the map.
689 Map.insert(std::make_pair(ValType::get(Ty), Ty));
691 // If the type is currently thought to be abstract, rescan all of our
692 // subtypes to see if the type has just become concrete!
693 if (Ty->isAbstract()) {
694 Ty->setAbstract(Ty->isTypeAbstract());
696 // If the type just became concrete, notify all users!
697 if (!Ty->isAbstract())
698 Ty->notifyUsesThatTypeBecameConcrete();
702 void print(const char *Arg) const {
703 #ifdef DEBUG_MERGE_TYPES
704 std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
706 for (typename std::map<ValType, PATypeHolder>::const_iterator I
707 = Map.begin(), E = Map.end(); I != E; ++I)
708 std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " "
709 << *I->second.get() << "\n";
713 void dump() const { print("dump output"); }
718 //===----------------------------------------------------------------------===//
719 // Function Type Factory and Value Class...
722 // FunctionValType - Define a class to hold the key that goes into the TypeMap
725 class FunctionValType {
727 std::vector<const Type*> ArgTypes;
730 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
731 bool IVA) : RetTy(ret), isVarArg(IVA) {
732 for (unsigned i = 0; i < args.size(); ++i)
733 ArgTypes.push_back(args[i]);
736 static FunctionValType get(const FunctionType *FT);
738 static unsigned hashTypeStructure(const FunctionType *FT) {
739 return FT->getNumParams()*2+FT->isVarArg();
742 // Subclass should override this... to update self as usual
743 void doRefinement(const DerivedType *OldType, const Type *NewType) {
744 if (RetTy == OldType) RetTy = NewType;
745 for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
746 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
749 inline bool operator<(const FunctionValType &MTV) const {
750 if (RetTy < MTV.RetTy) return true;
751 if (RetTy > MTV.RetTy) return false;
753 if (ArgTypes < MTV.ArgTypes) return true;
754 return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
759 // Define the actual map itself now...
760 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
762 FunctionValType FunctionValType::get(const FunctionType *FT) {
763 // Build up a FunctionValType
764 std::vector<const Type *> ParamTypes;
765 ParamTypes.reserve(FT->getNumParams());
766 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
767 ParamTypes.push_back(FT->getParamType(i));
768 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
772 // FunctionType::get - The factory function for the FunctionType class...
773 FunctionType *FunctionType::get(const Type *ReturnType,
774 const std::vector<const Type*> &Params,
776 FunctionValType VT(ReturnType, Params, isVarArg);
777 FunctionType *MT = FunctionTypes.get(VT);
780 FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
782 #ifdef DEBUG_MERGE_TYPES
783 std::cerr << "Derived new type: " << MT << "\n";
788 //===----------------------------------------------------------------------===//
789 // Array Type Factory...
796 ArrayValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
798 static ArrayValType get(const ArrayType *AT) {
799 return ArrayValType(AT->getElementType(), AT->getNumElements());
802 static unsigned hashTypeStructure(const ArrayType *AT) {
803 return AT->getNumElements();
806 // Subclass should override this... to update self as usual
807 void doRefinement(const DerivedType *OldType, const Type *NewType) {
808 assert(ValTy == OldType);
812 inline bool operator<(const ArrayValType &MTV) const {
813 if (Size < MTV.Size) return true;
814 return Size == MTV.Size && ValTy < MTV.ValTy;
818 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
821 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
822 assert(ElementType && "Can't get array of null types!");
824 ArrayValType AVT(ElementType, NumElements);
825 ArrayType *AT = ArrayTypes.get(AVT);
826 if (AT) return AT; // Found a match, return it!
828 // Value not found. Derive a new type!
829 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
831 #ifdef DEBUG_MERGE_TYPES
832 std::cerr << "Derived new type: " << *AT << "\n";
837 //===----------------------------------------------------------------------===//
838 // Struct Type Factory...
842 // StructValType - Define a class to hold the key that goes into the TypeMap
844 class StructValType {
845 std::vector<const Type*> ElTypes;
847 StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
849 static StructValType get(const StructType *ST) {
850 std::vector<const Type *> ElTypes;
851 ElTypes.reserve(ST->getNumElements());
852 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
853 ElTypes.push_back(ST->getElementType(i));
855 return StructValType(ElTypes);
858 static unsigned hashTypeStructure(const StructType *ST) {
859 return ST->getNumElements();
862 // Subclass should override this... to update self as usual
863 void doRefinement(const DerivedType *OldType, const Type *NewType) {
864 for (unsigned i = 0; i < ElTypes.size(); ++i)
865 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
868 inline bool operator<(const StructValType &STV) const {
869 return ElTypes < STV.ElTypes;
874 static TypeMap<StructValType, StructType> StructTypes;
876 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
877 StructValType STV(ETypes);
878 StructType *ST = StructTypes.get(STV);
881 // Value not found. Derive a new type!
882 StructTypes.add(STV, ST = new StructType(ETypes));
884 #ifdef DEBUG_MERGE_TYPES
885 std::cerr << "Derived new type: " << *ST << "\n";
892 //===----------------------------------------------------------------------===//
893 // Pointer Type Factory...
896 // PointerValType - Define a class to hold the key that goes into the TypeMap
899 class PointerValType {
902 PointerValType(const Type *val) : ValTy(val) {}
904 static PointerValType get(const PointerType *PT) {
905 return PointerValType(PT->getElementType());
908 static unsigned hashTypeStructure(const PointerType *PT) {
912 // Subclass should override this... to update self as usual
913 void doRefinement(const DerivedType *OldType, const Type *NewType) {
914 assert(ValTy == OldType);
918 bool operator<(const PointerValType &MTV) const {
919 return ValTy < MTV.ValTy;
924 static TypeMap<PointerValType, PointerType> PointerTypes;
926 PointerType *PointerType::get(const Type *ValueType) {
927 assert(ValueType && "Can't get a pointer to <null> type!");
928 PointerValType PVT(ValueType);
930 PointerType *PT = PointerTypes.get(PVT);
933 // Value not found. Derive a new type!
934 PointerTypes.add(PVT, PT = new PointerType(ValueType));
936 #ifdef DEBUG_MERGE_TYPES
937 std::cerr << "Derived new type: " << *PT << "\n";
943 //===----------------------------------------------------------------------===//
944 // Derived Type Refinement Functions
945 //===----------------------------------------------------------------------===//
947 // removeAbstractTypeUser - Notify an abstract type that a user of the class
948 // no longer has a handle to the type. This function is called primarily by
949 // the PATypeHandle class. When there are no users of the abstract type, it
950 // is annihilated, because there is no way to get a reference to it ever again.
952 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
953 // Search from back to front because we will notify users from back to
954 // front. Also, it is likely that there will be a stack like behavior to
955 // users that register and unregister users.
958 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
959 assert(i != 0 && "AbstractTypeUser not in user list!");
961 --i; // Convert to be in range 0 <= i < size()
962 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
964 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
966 #ifdef DEBUG_MERGE_TYPES
967 std::cerr << " remAbstractTypeUser[" << (void*)this << ", "
968 << *this << "][" << i << "] User = " << U << "\n";
971 if (AbstractTypeUsers.empty() && RefCount == 0 && isAbstract()) {
972 #ifdef DEBUG_MERGE_TYPES
973 std::cerr << "DELETEing unused abstract type: <" << *this
974 << ">[" << (void*)this << "]" << "\n";
976 delete this; // No users of this abstract type!
981 // refineAbstractTypeTo - This function is used to when it is discovered that
982 // the 'this' abstract type is actually equivalent to the NewType specified.
983 // This causes all users of 'this' to switch to reference the more concrete type
984 // NewType and for 'this' to be deleted.
986 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
987 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
988 assert(this != NewType && "Can't refine to myself!");
989 assert(ForwardType == 0 && "This type has already been refined!");
991 // The descriptions may be out of date. Conservatively clear them all!
992 AbstractTypeDescriptions.clear();
994 #ifdef DEBUG_MERGE_TYPES
995 std::cerr << "REFINING abstract type [" << (void*)this << " "
996 << *this << "] to [" << (void*)NewType << " "
997 << *NewType << "]!\n";
1000 // Make sure to put the type to be refined to into a holder so that if IT gets
1001 // refined, that we will not continue using a dead reference...
1003 PATypeHolder NewTy(NewType);
1005 // Any PATypeHolders referring to this type will now automatically forward to
1006 // the type we are resolved to.
1007 ForwardType = NewType;
1008 if (NewType->isAbstract())
1009 cast<DerivedType>(NewType)->addRef();
1011 // Add a self use of the current type so that we don't delete ourself until
1012 // after the function exits.
1014 PATypeHolder CurrentTy(this);
1016 // To make the situation simpler, we ask the subclass to remove this type from
1017 // the type map, and to replace any type uses with uses of non-abstract types.
1018 // This dramatically limits the amount of recursive type trouble we can find
1022 // Iterate over all of the uses of this type, invoking callback. Each user
1023 // should remove itself from our use list automatically. We have to check to
1024 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1025 // will not cause users to drop off of the use list. If we resolve to ourself
1028 while (!AbstractTypeUsers.empty() && NewTy != this) {
1029 AbstractTypeUser *User = AbstractTypeUsers.back();
1031 unsigned OldSize = AbstractTypeUsers.size();
1032 #ifdef DEBUG_MERGE_TYPES
1033 std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
1034 << "] of abstract type [" << (void*)this << " "
1035 << *this << "] to [" << (void*)NewTy.get() << " "
1036 << *NewTy << "]!\n";
1038 User->refineAbstractType(this, NewTy);
1040 assert(AbstractTypeUsers.size() != OldSize &&
1041 "AbsTyUser did not remove self from user list!");
1044 // If we were successful removing all users from the type, 'this' will be
1045 // deleted when the last PATypeHolder is destroyed or updated from this type.
1046 // This may occur on exit of this function, as the CurrentTy object is
1050 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1051 // the current type has transitioned from being abstract to being concrete.
1053 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1054 #ifdef DEBUG_MERGE_TYPES
1055 std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1058 unsigned OldSize = AbstractTypeUsers.size();
1059 while (!AbstractTypeUsers.empty()) {
1060 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1061 ATU->typeBecameConcrete(this);
1063 assert(AbstractTypeUsers.size() < OldSize-- &&
1064 "AbstractTypeUser did not remove itself from the use list!");
1071 // refineAbstractType - Called when a contained type is found to be more
1072 // concrete - this could potentially change us from an abstract type to a
1075 void FunctionType::refineAbstractType(const DerivedType *OldType,
1076 const Type *NewType) {
1077 FunctionTypes.finishRefinement(this, OldType, NewType);
1080 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1081 refineAbstractType(AbsTy, AbsTy);
1085 // refineAbstractType - Called when a contained type is found to be more
1086 // concrete - this could potentially change us from an abstract type to a
1089 void ArrayType::refineAbstractType(const DerivedType *OldType,
1090 const Type *NewType) {
1091 ArrayTypes.finishRefinement(this, OldType, NewType);
1094 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1095 refineAbstractType(AbsTy, AbsTy);
1099 // refineAbstractType - Called when a contained type is found to be more
1100 // concrete - this could potentially change us from an abstract type to a
1103 void StructType::refineAbstractType(const DerivedType *OldType,
1104 const Type *NewType) {
1105 StructTypes.finishRefinement(this, OldType, NewType);
1108 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1109 refineAbstractType(AbsTy, AbsTy);
1112 // refineAbstractType - Called when a contained type is found to be more
1113 // concrete - this could potentially change us from an abstract type to a
1116 void PointerType::refineAbstractType(const DerivedType *OldType,
1117 const Type *NewType) {
1118 PointerTypes.finishRefinement(this, OldType, NewType);
1121 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1122 refineAbstractType(AbsTy, AbsTy);