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", "numslowtypes");
26 static Statistic<> NumTypeEquals("type", "numtypeequals");
28 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
29 // created and later destroyed, all in an effort to make sure that there is only
30 // a single canonical version of a type.
32 //#define DEBUG_MERGE_TYPES 1
35 //===----------------------------------------------------------------------===//
36 // Type Class Implementation
37 //===----------------------------------------------------------------------===//
39 static unsigned CurUID = 0;
40 static std::vector<const Type *> UIDMappings;
42 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
43 // for types as they are needed. Because resolution of types must invalidate
44 // all of the abstract type descriptions, we keep them in a seperate map to make
46 static std::map<const Type*, std::string> ConcreteTypeDescriptions;
47 static std::map<const Type*, std::string> AbstractTypeDescriptions;
49 Type::Type(const std::string &name, PrimitiveID id)
50 : Value(Type::TypeTy, Value::TypeVal), ForwardType(0) {
52 ConcreteTypeDescriptions[this] = name;
55 UID = CurUID++; // Assign types UID's as they are created
56 UIDMappings.push_back(this);
59 void Type::setName(const std::string &Name, SymbolTable *ST) {
60 assert(ST && "Type::setName - Must provide symbol table argument!");
62 if (Name.size()) ST->insert(Name, this);
66 const Type *Type::getUniqueIDType(unsigned UID) {
67 assert(UID < UIDMappings.size() &&
68 "Type::getPrimitiveType: UID out of range!");
69 return UIDMappings[UID];
72 const Type *Type::getPrimitiveType(PrimitiveID IDNumber) {
74 case VoidTyID : return VoidTy;
75 case BoolTyID : return BoolTy;
76 case UByteTyID : return UByteTy;
77 case SByteTyID : return SByteTy;
78 case UShortTyID: return UShortTy;
79 case ShortTyID : return ShortTy;
80 case UIntTyID : return UIntTy;
81 case IntTyID : return IntTy;
82 case ULongTyID : return ULongTy;
83 case LongTyID : return LongTy;
84 case FloatTyID : return FloatTy;
85 case DoubleTyID: return DoubleTy;
86 case TypeTyID : return TypeTy;
87 case LabelTyID : return LabelTy;
93 // isLosslesslyConvertibleTo - Return true if this type can be converted to
94 // 'Ty' without any reinterpretation of bits. For example, uint to int.
96 bool Type::isLosslesslyConvertibleTo(const Type *Ty) const {
97 if (this == Ty) return true;
98 if ((!isPrimitiveType() && !isa<PointerType>(this)) ||
99 (!isa<PointerType>(Ty) && !Ty->isPrimitiveType())) return false;
101 if (getPrimitiveID() == Ty->getPrimitiveID())
102 return true; // Handles identity cast, and cast of differing pointer types
104 // Now we know that they are two differing primitive or pointer types
105 switch (getPrimitiveID()) {
106 case Type::UByteTyID: return Ty == Type::SByteTy;
107 case Type::SByteTyID: return Ty == Type::UByteTy;
108 case Type::UShortTyID: return Ty == Type::ShortTy;
109 case Type::ShortTyID: return Ty == Type::UShortTy;
110 case Type::UIntTyID: return Ty == Type::IntTy;
111 case Type::IntTyID: return Ty == Type::UIntTy;
112 case Type::ULongTyID: return Ty == Type::LongTy;
113 case Type::LongTyID: return Ty == Type::ULongTy;
114 case Type::PointerTyID: return isa<PointerType>(Ty);
116 return false; // Other types have no identity values
120 // getPrimitiveSize - Return the basic size of this type if it is a primitive
121 // type. These are fixed by LLVM and are not target dependent. This will
122 // return zero if the type does not have a size or is not a primitive type.
124 unsigned Type::getPrimitiveSize() const {
125 switch (getPrimitiveID()) {
126 #define HANDLE_PRIM_TYPE(TY,SIZE) case TY##TyID: return SIZE;
127 #include "llvm/Type.def"
133 /// getForwardedTypeInternal - This method is used to implement the union-find
134 /// algorithm for when a type is being forwarded to another type.
135 const Type *Type::getForwardedTypeInternal() const {
136 assert(ForwardType && "This type is not being forwarded to another type!");
138 // Check to see if the forwarded type has been forwarded on. If so, collapse
139 // the forwarding links.
140 const Type *RealForwardedType = ForwardType->getForwardedType();
141 if (!RealForwardedType)
142 return ForwardType; // No it's not forwarded again
144 // Yes, it is forwarded again. First thing, add the reference to the new
146 if (RealForwardedType->isAbstract())
147 cast<DerivedType>(RealForwardedType)->addRef();
149 // Now drop the old reference. This could cause ForwardType to get deleted.
150 cast<DerivedType>(ForwardType)->dropRef();
152 // Return the updated type.
153 ForwardType = RealForwardedType;
157 // getTypeDescription - This is a recursive function that walks a type hierarchy
158 // calculating the description for a type.
160 static std::string getTypeDescription(const Type *Ty,
161 std::vector<const Type *> &TypeStack) {
162 if (isa<OpaqueType>(Ty)) { // Base case for the recursion
163 std::map<const Type*, std::string>::iterator I =
164 AbstractTypeDescriptions.lower_bound(Ty);
165 if (I != AbstractTypeDescriptions.end() && I->first == Ty)
167 std::string Desc = "opaque"+utostr(Ty->getUniqueID());
168 AbstractTypeDescriptions.insert(std::make_pair(Ty, Desc));
172 if (!Ty->isAbstract()) { // Base case for the recursion
173 std::map<const Type*, std::string>::iterator I =
174 ConcreteTypeDescriptions.find(Ty);
175 if (I != ConcreteTypeDescriptions.end()) return I->second;
178 // Check to see if the Type is already on the stack...
179 unsigned Slot = 0, CurSize = TypeStack.size();
180 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
182 // This is another base case for the recursion. In this case, we know
183 // that we have looped back to a type that we have previously visited.
184 // Generate the appropriate upreference to handle this.
187 return "\\" + utostr(CurSize-Slot); // Here's the upreference
189 // Recursive case: derived types...
191 TypeStack.push_back(Ty); // Add us to the stack..
193 switch (Ty->getPrimitiveID()) {
194 case Type::FunctionTyID: {
195 const FunctionType *FTy = cast<FunctionType>(Ty);
196 Result = getTypeDescription(FTy->getReturnType(), TypeStack) + " (";
197 for (FunctionType::param_iterator I = FTy->param_begin(),
198 E = FTy->param_end(); I != E; ++I) {
199 if (I != FTy->param_begin())
201 Result += getTypeDescription(*I, TypeStack);
203 if (FTy->isVarArg()) {
204 if (FTy->getNumParams()) Result += ", ";
210 case Type::StructTyID: {
211 const StructType *STy = cast<StructType>(Ty);
213 for (StructType::element_iterator I = STy->element_begin(),
214 E = STy->element_end(); I != E; ++I) {
215 if (I != STy->element_begin())
217 Result += getTypeDescription(*I, TypeStack);
222 case Type::PointerTyID: {
223 const PointerType *PTy = cast<PointerType>(Ty);
224 Result = getTypeDescription(PTy->getElementType(), TypeStack) + " *";
227 case Type::ArrayTyID: {
228 const ArrayType *ATy = cast<ArrayType>(Ty);
229 unsigned NumElements = ATy->getNumElements();
231 Result += utostr(NumElements) + " x ";
232 Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
237 assert(0 && "Unhandled type in getTypeDescription!");
240 TypeStack.pop_back(); // Remove self from stack...
247 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
249 std::map<const Type*, std::string>::iterator I = Map.find(Ty);
250 if (I != Map.end()) return I->second;
252 std::vector<const Type *> TypeStack;
253 return Map[Ty] = getTypeDescription(Ty, TypeStack);
257 const std::string &Type::getDescription() const {
259 return getOrCreateDesc(AbstractTypeDescriptions, this);
261 return getOrCreateDesc(ConcreteTypeDescriptions, this);
265 bool StructType::indexValid(const Value *V) const {
266 // Structure indexes require unsigned integer constants.
267 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(V))
268 return CU->getValue() < ContainedTys.size();
272 // getTypeAtIndex - Given an index value into the type, return the type of the
273 // element. For a structure type, this must be a constant value...
275 const Type *StructType::getTypeAtIndex(const Value *V) const {
276 assert(isa<Constant>(V) && "Structure index must be a constant!!");
277 unsigned Idx = cast<ConstantUInt>(V)->getValue();
278 assert(Idx < ContainedTys.size() && "Structure index out of range!");
279 assert(indexValid(V) && "Invalid structure index!"); // Duplicate check
280 return ContainedTys[Idx];
284 //===----------------------------------------------------------------------===//
286 //===----------------------------------------------------------------------===//
288 // These classes are used to implement specialized behavior for each different
291 struct SignedIntType : public Type {
292 SignedIntType(const std::string &Name, PrimitiveID id) : Type(Name, id) {}
294 // isSigned - Return whether a numeric type is signed.
295 virtual bool isSigned() const { return 1; }
297 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
298 // virtual function invocation.
300 virtual bool isInteger() const { return 1; }
303 struct UnsignedIntType : public Type {
304 UnsignedIntType(const std::string &N, PrimitiveID id) : Type(N, id) {}
306 // isUnsigned - Return whether a numeric type is signed.
307 virtual bool isUnsigned() const { return 1; }
309 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
310 // virtual function invocation.
312 virtual bool isInteger() const { return 1; }
315 struct OtherType : public Type {
316 OtherType(const std::string &N, PrimitiveID id) : Type(N, id) {}
319 static struct TypeType : public Type {
320 TypeType() : Type("type", TypeTyID) {}
321 } TheTypeTy; // Implement the type that is global.
324 //===----------------------------------------------------------------------===//
325 // Static 'Type' data
326 //===----------------------------------------------------------------------===//
328 static OtherType TheVoidTy ("void" , Type::VoidTyID);
329 static OtherType TheBoolTy ("bool" , Type::BoolTyID);
330 static SignedIntType TheSByteTy ("sbyte" , Type::SByteTyID);
331 static UnsignedIntType TheUByteTy ("ubyte" , Type::UByteTyID);
332 static SignedIntType TheShortTy ("short" , Type::ShortTyID);
333 static UnsignedIntType TheUShortTy("ushort", Type::UShortTyID);
334 static SignedIntType TheIntTy ("int" , Type::IntTyID);
335 static UnsignedIntType TheUIntTy ("uint" , Type::UIntTyID);
336 static SignedIntType TheLongTy ("long" , Type::LongTyID);
337 static UnsignedIntType TheULongTy ("ulong" , Type::ULongTyID);
338 static OtherType TheFloatTy ("float" , Type::FloatTyID);
339 static OtherType TheDoubleTy("double", Type::DoubleTyID);
340 static OtherType TheLabelTy ("label" , Type::LabelTyID);
342 Type *Type::VoidTy = &TheVoidTy;
343 Type *Type::BoolTy = &TheBoolTy;
344 Type *Type::SByteTy = &TheSByteTy;
345 Type *Type::UByteTy = &TheUByteTy;
346 Type *Type::ShortTy = &TheShortTy;
347 Type *Type::UShortTy = &TheUShortTy;
348 Type *Type::IntTy = &TheIntTy;
349 Type *Type::UIntTy = &TheUIntTy;
350 Type *Type::LongTy = &TheLongTy;
351 Type *Type::ULongTy = &TheULongTy;
352 Type *Type::FloatTy = &TheFloatTy;
353 Type *Type::DoubleTy = &TheDoubleTy;
354 Type *Type::TypeTy = &TheTypeTy;
355 Type *Type::LabelTy = &TheLabelTy;
358 //===----------------------------------------------------------------------===//
359 // Derived Type Constructors
360 //===----------------------------------------------------------------------===//
362 FunctionType::FunctionType(const Type *Result,
363 const std::vector<const Type*> &Params,
364 bool IsVarArgs) : DerivedType(FunctionTyID),
365 isVarArgs(IsVarArgs) {
366 bool isAbstract = Result->isAbstract();
367 ContainedTys.reserve(Params.size()+1);
368 ContainedTys.push_back(PATypeHandle(Result, this));
370 for (unsigned i = 0; i != Params.size(); ++i) {
371 ContainedTys.push_back(PATypeHandle(Params[i], this));
372 isAbstract |= Params[i]->isAbstract();
375 // Calculate whether or not this type is abstract
376 setAbstract(isAbstract);
379 StructType::StructType(const std::vector<const Type*> &Types)
380 : CompositeType(StructTyID) {
381 ContainedTys.reserve(Types.size());
382 bool isAbstract = false;
383 for (unsigned i = 0; i < Types.size(); ++i) {
384 assert(Types[i] != Type::VoidTy && "Void type in method prototype!!");
385 ContainedTys.push_back(PATypeHandle(Types[i], this));
386 isAbstract |= Types[i]->isAbstract();
389 // Calculate whether or not this type is abstract
390 setAbstract(isAbstract);
393 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
394 : SequentialType(ArrayTyID, ElType) {
397 // Calculate whether or not this type is abstract
398 setAbstract(ElType->isAbstract());
401 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
402 // Calculate whether or not this type is abstract
403 setAbstract(E->isAbstract());
406 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
408 #ifdef DEBUG_MERGE_TYPES
409 std::cerr << "Derived new type: " << *this << "\n";
413 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
414 // another (more concrete) type, we must eliminate all references to other
415 // types, to avoid some circular reference problems.
416 void DerivedType::dropAllTypeUses() {
417 if (!ContainedTys.empty()) {
418 while (ContainedTys.size() > 1)
419 ContainedTys.pop_back();
421 // The type must stay abstract. To do this, we insert a pointer to a type
422 // that will never get resolved, thus will always be abstract.
423 static Type *AlwaysOpaqueTy = OpaqueType::get();
424 static PATypeHolder Holder(AlwaysOpaqueTy);
425 ContainedTys[0] = AlwaysOpaqueTy;
429 // isTypeAbstract - This is a recursive function that walks a type hierarchy
430 // calculating whether or not a type is abstract. Worst case it will have to do
431 // a lot of traversing if you have some whacko opaque types, but in most cases,
432 // it will do some simple stuff when it hits non-abstract types that aren't
435 bool Type::isTypeAbstract() {
436 if (!isAbstract()) // Base case for the recursion
437 return false; // Primitive = leaf type
439 if (isa<OpaqueType>(this)) // Base case for the recursion
440 return true; // This whole type is abstract!
442 // We have to guard against recursion. To do this, we temporarily mark this
443 // type as concrete, so that if we get back to here recursively we will think
444 // it's not abstract, and thus not scan it again.
447 // Scan all of the sub-types. If any of them are abstract, than so is this
449 for (Type::subtype_iterator I = subtype_begin(), E = subtype_end();
451 if (const_cast<Type*>(I->get())->isTypeAbstract()) {
452 setAbstract(true); // Restore the abstract bit.
453 return true; // This type is abstract if subtype is abstract!
456 // Restore the abstract bit.
459 // Nothing looks abstract here...
464 //===----------------------------------------------------------------------===//
465 // Type Structural Equality Testing
466 //===----------------------------------------------------------------------===//
468 // TypesEqual - Two types are considered structurally equal if they have the
469 // same "shape": Every level and element of the types have identical primitive
470 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
471 // be pointer equals to be equivalent though. This uses an optimistic algorithm
472 // that assumes that two graphs are the same until proven otherwise.
474 static bool TypesEqual(const Type *Ty, const Type *Ty2,
475 std::map<const Type *, const Type *> &EqTypes) {
476 if (Ty == Ty2) return true;
477 if (Ty->getPrimitiveID() != Ty2->getPrimitiveID()) return false;
478 if (isa<OpaqueType>(Ty))
479 return false; // Two unequal opaque types are never equal
481 std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
482 if (It != EqTypes.end() && It->first == Ty)
483 return It->second == Ty2; // Looping back on a type, check for equality
485 // Otherwise, add the mapping to the table to make sure we don't get
486 // recursion on the types...
487 EqTypes.insert(It, std::make_pair(Ty, Ty2));
489 // Two really annoying special cases that breaks an otherwise nice simple
490 // algorithm is the fact that arraytypes have sizes that differentiates types,
491 // and that function types can be varargs or not. Consider this now.
493 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
494 return TypesEqual(PTy->getElementType(),
495 cast<PointerType>(Ty2)->getElementType(), EqTypes);
496 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
497 const StructType *STy2 = cast<StructType>(Ty2);
498 if (STy->getNumElements() != STy2->getNumElements()) return false;
499 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
500 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
503 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
504 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
505 return ATy->getNumElements() == ATy2->getNumElements() &&
506 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
507 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
508 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
509 if (FTy->isVarArg() != FTy2->isVarArg() ||
510 FTy->getNumParams() != FTy2->getNumParams() ||
511 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
513 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i)
514 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
518 assert(0 && "Unknown derived type!");
523 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
524 std::map<const Type *, const Type *> EqTypes;
525 return TypesEqual(Ty, Ty2, EqTypes);
528 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
530 static bool TypeHasCycleThroughItself(const Type *Ty) {
531 std::set<const Type*> VisitedTypes;
532 for (Type::subtype_iterator I = Ty->subtype_begin(),
533 E = Ty->subtype_end(); I != E; ++I)
534 for (df_ext_iterator<const Type *, std::set<const Type*> >
535 DFI = df_ext_begin(I->get(), VisitedTypes),
536 E = df_ext_end(I->get(), VisitedTypes); DFI != E; ++DFI)
538 return true; // Found a cycle through ty!
543 //===----------------------------------------------------------------------===//
544 // Derived Type Factory Functions
545 //===----------------------------------------------------------------------===//
547 // TypeMap - Make sure that only one instance of a particular type may be
548 // created on any given run of the compiler... note that this involves updating
549 // our map if an abstract type gets refined somehow.
552 template<class ValType, class TypeClass>
554 std::map<ValType, PATypeHolder> Map;
557 typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
558 ~TypeMap() { print("ON EXIT"); }
560 inline TypeClass *get(const ValType &V) {
561 iterator I = Map.find(V);
562 return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
565 inline void add(const ValType &V, TypeClass *T) {
566 Map.insert(std::make_pair(V, T));
570 iterator getEntryForType(TypeClass *Ty) {
571 iterator I = Map.find(ValType::get(Ty));
572 if (I == Map.end()) print("ERROR!");
573 assert(I != Map.end() && "Didn't find type entry!");
574 assert(I->second.get() == (const Type*)Ty && "Type entry wrong?");
578 /// finishRefinement - This method is called after we have updated an existing
579 /// type with its new components. We must now either merge the type away with
580 /// some other type or reinstall it in the map with it's new configuration.
581 /// The specified iterator tells us what the type USED to look like.
582 void finishRefinement(TypeClass *Ty, const DerivedType *OldType,
583 const Type *NewType) {
584 assert((Ty->isAbstract() || !OldType->isAbstract()) &&
585 "Refining a non-abstract type!");
586 #ifdef DEBUG_MERGE_TYPES
587 std::cerr << "refineAbstractTy(" << (void*)OldType << "[" << *OldType
588 << "], " << (void*)NewType << " [" << *NewType << "])\n";
591 // Make a temporary type holder for the type so that it doesn't disappear on
592 // us when we erase the entry from the map.
593 PATypeHolder TyHolder = Ty;
595 // Look up our current type map entry..
596 iterator TyIt = getEntryForType(Ty);
598 // The old record is now out-of-date, because one of the children has been
599 // updated. Remove the obsolete entry from the map.
602 // Find the type element we are refining...
603 for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
604 if (Ty->ContainedTys[i] == OldType) {
605 Ty->ContainedTys[i].removeUserFromConcrete();
606 Ty->ContainedTys[i] = NewType;
609 // If there are no cycles going through this node, we can do a simple,
610 // efficient lookup in the map, instead of an inefficient nasty linear
612 bool TypeHasCycle = TypeHasCycleThroughItself(Ty);
614 iterator I = Map.find(ValType::get(Ty));
615 if (I != Map.end()) {
616 // We already have this type in the table. Get rid of the newly refined
618 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
619 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
621 // Refined to a different type altogether?
622 Ty->refineAbstractTypeTo(NewTy);
629 unsigned TypeHash = ValType::hashTypeStructure(Ty);
633 // Now we check to see if there is an existing entry in the table which is
634 // structurally identical to the newly refined type. If so, this type
635 // gets refined to the pre-existing type.
637 for (iterator I = Map.begin(), E = Map.end(); I != E; ++I) {
639 if (TypesEqual(Ty, I->second)) {
640 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
641 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
643 // Refined to a different type altogether?
644 Ty->refineAbstractTypeTo(NewTy);
650 // If there is no existing type of the same structure, we reinsert an
651 // updated record into the map.
652 Map.insert(std::make_pair(ValType::get(Ty), Ty));
654 // If the type is currently thought to be abstract, rescan all of our
655 // subtypes to see if the type has just become concrete!
656 if (Ty->isAbstract()) {
657 Ty->setAbstract(Ty->isTypeAbstract());
659 // If the type just became concrete, notify all users!
660 if (!Ty->isAbstract())
661 Ty->notifyUsesThatTypeBecameConcrete();
665 void remove(const ValType &OldVal) {
666 iterator I = Map.find(OldVal);
667 assert(I != Map.end() && "TypeMap::remove, element not found!");
671 void remove(iterator I) {
672 assert(I != Map.end() && "Cannot remove invalid iterator pointer!");
676 void print(const char *Arg) const {
677 #ifdef DEBUG_MERGE_TYPES
678 std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
680 for (typename std::map<ValType, PATypeHolder>::const_iterator I
681 = Map.begin(), E = Map.end(); I != E; ++I)
682 std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " "
683 << *I->second.get() << "\n";
687 void dump() const { print("dump output"); }
692 //===----------------------------------------------------------------------===//
693 // Function Type Factory and Value Class...
696 // FunctionValType - Define a class to hold the key that goes into the TypeMap
699 class FunctionValType {
701 std::vector<const Type*> ArgTypes;
704 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
705 bool IVA) : RetTy(ret), isVarArg(IVA) {
706 for (unsigned i = 0; i < args.size(); ++i)
707 ArgTypes.push_back(args[i]);
710 static FunctionValType get(const FunctionType *FT);
712 static unsigned hashTypeStructure(const FunctionType *FT) {
716 // Subclass should override this... to update self as usual
717 void doRefinement(const DerivedType *OldType, const Type *NewType) {
718 if (RetTy == OldType) RetTy = NewType;
719 for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
720 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
723 inline bool operator<(const FunctionValType &MTV) const {
724 if (RetTy < MTV.RetTy) return true;
725 if (RetTy > MTV.RetTy) return false;
727 if (ArgTypes < MTV.ArgTypes) return true;
728 return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
733 // Define the actual map itself now...
734 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
736 FunctionValType FunctionValType::get(const FunctionType *FT) {
737 // Build up a FunctionValType
738 std::vector<const Type *> ParamTypes;
739 ParamTypes.reserve(FT->getNumParams());
740 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
741 ParamTypes.push_back(FT->getParamType(i));
742 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
746 // FunctionType::get - The factory function for the FunctionType class...
747 FunctionType *FunctionType::get(const Type *ReturnType,
748 const std::vector<const Type*> &Params,
750 FunctionValType VT(ReturnType, Params, isVarArg);
751 FunctionType *MT = FunctionTypes.get(VT);
754 FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
756 #ifdef DEBUG_MERGE_TYPES
757 std::cerr << "Derived new type: " << MT << "\n";
762 //===----------------------------------------------------------------------===//
763 // Array Type Factory...
770 ArrayValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
772 static ArrayValType get(const ArrayType *AT) {
773 return ArrayValType(AT->getElementType(), AT->getNumElements());
776 static unsigned hashTypeStructure(const ArrayType *AT) {
780 // Subclass should override this... to update self as usual
781 void doRefinement(const DerivedType *OldType, const Type *NewType) {
782 assert(ValTy == OldType);
786 inline bool operator<(const ArrayValType &MTV) const {
787 if (Size < MTV.Size) return true;
788 return Size == MTV.Size && ValTy < MTV.ValTy;
792 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
795 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
796 assert(ElementType && "Can't get array of null types!");
798 ArrayValType AVT(ElementType, NumElements);
799 ArrayType *AT = ArrayTypes.get(AVT);
800 if (AT) return AT; // Found a match, return it!
802 // Value not found. Derive a new type!
803 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
805 #ifdef DEBUG_MERGE_TYPES
806 std::cerr << "Derived new type: " << *AT << "\n";
811 //===----------------------------------------------------------------------===//
812 // Struct Type Factory...
816 // StructValType - Define a class to hold the key that goes into the TypeMap
818 class StructValType {
819 std::vector<const Type*> ElTypes;
821 StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
823 static StructValType get(const StructType *ST) {
824 std::vector<const Type *> ElTypes;
825 ElTypes.reserve(ST->getNumElements());
826 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
827 ElTypes.push_back(ST->getElementType(i));
829 return StructValType(ElTypes);
832 static unsigned hashTypeStructure(const StructType *ST) {
836 // Subclass should override this... to update self as usual
837 void doRefinement(const DerivedType *OldType, const Type *NewType) {
838 for (unsigned i = 0; i < ElTypes.size(); ++i)
839 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
842 inline bool operator<(const StructValType &STV) const {
843 return ElTypes < STV.ElTypes;
848 static TypeMap<StructValType, StructType> StructTypes;
850 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
851 StructValType STV(ETypes);
852 StructType *ST = StructTypes.get(STV);
855 // Value not found. Derive a new type!
856 StructTypes.add(STV, ST = new StructType(ETypes));
858 #ifdef DEBUG_MERGE_TYPES
859 std::cerr << "Derived new type: " << *ST << "\n";
866 //===----------------------------------------------------------------------===//
867 // Pointer Type Factory...
870 // PointerValType - Define a class to hold the key that goes into the TypeMap
873 class PointerValType {
876 PointerValType(const Type *val) : ValTy(val) {}
878 static PointerValType get(const PointerType *PT) {
879 return PointerValType(PT->getElementType());
882 static unsigned hashTypeStructure(const PointerType *PT) {
886 // Subclass should override this... to update self as usual
887 void doRefinement(const DerivedType *OldType, const Type *NewType) {
888 assert(ValTy == OldType);
892 bool operator<(const PointerValType &MTV) const {
893 return ValTy < MTV.ValTy;
898 static TypeMap<PointerValType, PointerType> PointerTypes;
900 PointerType *PointerType::get(const Type *ValueType) {
901 assert(ValueType && "Can't get a pointer to <null> type!");
902 PointerValType PVT(ValueType);
904 PointerType *PT = PointerTypes.get(PVT);
907 // Value not found. Derive a new type!
908 PointerTypes.add(PVT, PT = new PointerType(ValueType));
910 #ifdef DEBUG_MERGE_TYPES
911 std::cerr << "Derived new type: " << *PT << "\n";
917 void debug_type_tables() {
918 FunctionTypes.dump();
925 //===----------------------------------------------------------------------===//
926 // Derived Type Refinement Functions
927 //===----------------------------------------------------------------------===//
929 // removeAbstractTypeUser - Notify an abstract type that a user of the class
930 // no longer has a handle to the type. This function is called primarily by
931 // the PATypeHandle class. When there are no users of the abstract type, it
932 // is annihilated, because there is no way to get a reference to it ever again.
934 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
935 // Search from back to front because we will notify users from back to
936 // front. Also, it is likely that there will be a stack like behavior to
937 // users that register and unregister users.
940 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
941 assert(i != 0 && "AbstractTypeUser not in user list!");
943 --i; // Convert to be in range 0 <= i < size()
944 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
946 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
948 #ifdef DEBUG_MERGE_TYPES
949 std::cerr << " remAbstractTypeUser[" << (void*)this << ", "
950 << *this << "][" << i << "] User = " << U << "\n";
953 if (AbstractTypeUsers.empty() && RefCount == 0 && isAbstract()) {
954 #ifdef DEBUG_MERGE_TYPES
955 std::cerr << "DELETEing unused abstract type: <" << *this
956 << ">[" << (void*)this << "]" << "\n";
958 delete this; // No users of this abstract type!
963 // refineAbstractTypeTo - This function is used to when it is discovered that
964 // the 'this' abstract type is actually equivalent to the NewType specified.
965 // This causes all users of 'this' to switch to reference the more concrete type
966 // NewType and for 'this' to be deleted.
968 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
969 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
970 assert(this != NewType && "Can't refine to myself!");
971 assert(ForwardType == 0 && "This type has already been refined!");
973 // The descriptions may be out of date. Conservatively clear them all!
974 AbstractTypeDescriptions.clear();
976 #ifdef DEBUG_MERGE_TYPES
977 std::cerr << "REFINING abstract type [" << (void*)this << " "
978 << *this << "] to [" << (void*)NewType << " "
979 << *NewType << "]!\n";
982 // Make sure to put the type to be refined to into a holder so that if IT gets
983 // refined, that we will not continue using a dead reference...
985 PATypeHolder NewTy(NewType);
987 // Any PATypeHolders referring to this type will now automatically forward to
988 // the type we are resolved to.
989 ForwardType = NewType;
990 if (NewType->isAbstract())
991 cast<DerivedType>(NewType)->addRef();
993 // Add a self use of the current type so that we don't delete ourself until
994 // after the function exits.
996 PATypeHolder CurrentTy(this);
998 // To make the situation simpler, we ask the subclass to remove this type from
999 // the type map, and to replace any type uses with uses of non-abstract types.
1000 // This dramatically limits the amount of recursive type trouble we can find
1004 // Iterate over all of the uses of this type, invoking callback. Each user
1005 // should remove itself from our use list automatically. We have to check to
1006 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1007 // will not cause users to drop off of the use list. If we resolve to ourself
1010 while (!AbstractTypeUsers.empty() && NewTy != this) {
1011 AbstractTypeUser *User = AbstractTypeUsers.back();
1013 unsigned OldSize = AbstractTypeUsers.size();
1014 #ifdef DEBUG_MERGE_TYPES
1015 std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
1016 << "] of abstract type [" << (void*)this << " "
1017 << *this << "] to [" << (void*)NewTy.get() << " "
1018 << *NewTy << "]!\n";
1020 User->refineAbstractType(this, NewTy);
1022 assert(AbstractTypeUsers.size() != OldSize &&
1023 "AbsTyUser did not remove self from user list!");
1026 // If we were successful removing all users from the type, 'this' will be
1027 // deleted when the last PATypeHolder is destroyed or updated from this type.
1028 // This may occur on exit of this function, as the CurrentTy object is
1032 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1033 // the current type has transitioned from being abstract to being concrete.
1035 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1036 #ifdef DEBUG_MERGE_TYPES
1037 std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1040 unsigned OldSize = AbstractTypeUsers.size();
1041 while (!AbstractTypeUsers.empty()) {
1042 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1043 ATU->typeBecameConcrete(this);
1045 assert(AbstractTypeUsers.size() < OldSize-- &&
1046 "AbstractTypeUser did not remove itself from the use list!");
1053 // refineAbstractType - Called when a contained type is found to be more
1054 // concrete - this could potentially change us from an abstract type to a
1057 void FunctionType::refineAbstractType(const DerivedType *OldType,
1058 const Type *NewType) {
1059 FunctionTypes.finishRefinement(this, OldType, NewType);
1062 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1063 refineAbstractType(AbsTy, AbsTy);
1067 // refineAbstractType - Called when a contained type is found to be more
1068 // concrete - this could potentially change us from an abstract type to a
1071 void ArrayType::refineAbstractType(const DerivedType *OldType,
1072 const Type *NewType) {
1073 ArrayTypes.finishRefinement(this, OldType, NewType);
1076 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1077 refineAbstractType(AbsTy, AbsTy);
1081 // refineAbstractType - Called when a contained type is found to be more
1082 // concrete - this could potentially change us from an abstract type to a
1085 void StructType::refineAbstractType(const DerivedType *OldType,
1086 const Type *NewType) {
1087 StructTypes.finishRefinement(this, OldType, NewType);
1090 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1091 refineAbstractType(AbsTy, AbsTy);
1094 // refineAbstractType - Called when a contained type is found to be more
1095 // concrete - this could potentially change us from an abstract type to a
1098 void PointerType::refineAbstractType(const DerivedType *OldType,
1099 const Type *NewType) {
1100 PointerTypes.finishRefinement(this, OldType, NewType);
1103 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1104 refineAbstractType(AbsTy, AbsTy);