1 //===-- Type.cpp - Implement the Type class -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Type class for the VMCore library.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/AbstractTypeUser.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/SymbolTable.h"
17 #include "llvm/Constants.h"
18 #include "llvm/ADT/DepthFirstIterator.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/SCCIterator.h"
21 #include "llvm/ADT/STLExtras.h"
26 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
27 // created and later destroyed, all in an effort to make sure that there is only
28 // a single canonical version of a type.
30 //#define DEBUG_MERGE_TYPES 1
32 AbstractTypeUser::~AbstractTypeUser() {}
34 //===----------------------------------------------------------------------===//
35 // Type Class Implementation
36 //===----------------------------------------------------------------------===//
38 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
39 // for types as they are needed. Because resolution of types must invalidate
40 // all of the abstract type descriptions, we keep them in a seperate map to make
42 static std::map<const Type*, std::string> ConcreteTypeDescriptions;
43 static std::map<const Type*, std::string> AbstractTypeDescriptions;
45 Type::Type( const std::string& name, TypeID id )
46 : RefCount(0), ForwardType(0) {
48 ConcreteTypeDescriptions[this] = name;
53 const Type *Type::getPrimitiveType(TypeID IDNumber) {
55 case VoidTyID : return VoidTy;
56 case BoolTyID : return BoolTy;
57 case UByteTyID : return UByteTy;
58 case SByteTyID : return SByteTy;
59 case UShortTyID: return UShortTy;
60 case ShortTyID : return ShortTy;
61 case UIntTyID : return UIntTy;
62 case IntTyID : return IntTy;
63 case ULongTyID : return ULongTy;
64 case LongTyID : return LongTy;
65 case FloatTyID : return FloatTy;
66 case DoubleTyID: return DoubleTy;
67 case LabelTyID : return LabelTy;
73 // isLosslesslyConvertibleTo - Return true if this type can be converted to
74 // 'Ty' without any reinterpretation of bits. For example, uint to int.
76 bool Type::isLosslesslyConvertibleTo(const Type *Ty) const {
77 if (this == Ty) return true;
78 if ((!isPrimitiveType() && !isa<PointerType>(this)) ||
79 (!isa<PointerType>(Ty) && !Ty->isPrimitiveType())) return false;
81 if (getTypeID() == Ty->getTypeID())
82 return true; // Handles identity cast, and cast of differing pointer types
84 // Now we know that they are two differing primitive or pointer types
85 switch (getTypeID()) {
86 case Type::UByteTyID: return Ty == Type::SByteTy;
87 case Type::SByteTyID: return Ty == Type::UByteTy;
88 case Type::UShortTyID: return Ty == Type::ShortTy;
89 case Type::ShortTyID: return Ty == Type::UShortTy;
90 case Type::UIntTyID: return Ty == Type::IntTy;
91 case Type::IntTyID: return Ty == Type::UIntTy;
92 case Type::ULongTyID: return Ty == Type::LongTy;
93 case Type::LongTyID: return Ty == Type::ULongTy;
94 case Type::PointerTyID: return isa<PointerType>(Ty);
96 return false; // Other types have no identity values
100 /// getUnsignedVersion - If this is an integer type, return the unsigned
101 /// variant of this type. For example int -> uint.
102 const Type *Type::getUnsignedVersion() const {
103 switch (getTypeID()) {
105 assert(isInteger()&&"Type::getUnsignedVersion is only valid for integers!");
106 case Type::UByteTyID:
107 case Type::SByteTyID: return Type::UByteTy;
108 case Type::UShortTyID:
109 case Type::ShortTyID: return Type::UShortTy;
111 case Type::IntTyID: return Type::UIntTy;
112 case Type::ULongTyID:
113 case Type::LongTyID: return Type::ULongTy;
117 /// getSignedVersion - If this is an integer type, return the signed variant
118 /// of this type. For example uint -> int.
119 const Type *Type::getSignedVersion() const {
120 switch (getTypeID()) {
122 assert(isInteger() && "Type::getSignedVersion is only valid for integers!");
123 case Type::UByteTyID:
124 case Type::SByteTyID: return Type::SByteTy;
125 case Type::UShortTyID:
126 case Type::ShortTyID: return Type::ShortTy;
128 case Type::IntTyID: return Type::IntTy;
129 case Type::ULongTyID:
130 case Type::LongTyID: return Type::LongTy;
135 // getPrimitiveSize - Return the basic size of this type if it is a primitive
136 // type. These are fixed by LLVM and are not target dependent. This will
137 // return zero if the type does not have a size or is not a primitive type.
139 unsigned Type::getPrimitiveSize() const {
140 switch (getTypeID()) {
141 #define HANDLE_PRIM_TYPE(TY,SIZE) case TY##TyID: return SIZE;
142 #include "llvm/Type.def"
147 /// isSizedDerivedType - Derived types like structures and arrays are sized
148 /// iff all of the members of the type are sized as well. Since asking for
149 /// their size is relatively uncommon, move this operation out of line.
150 bool Type::isSizedDerivedType() const {
151 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
152 return ATy->getElementType()->isSized();
154 if (const PackedType *PTy = dyn_cast<PackedType>(this))
155 return PTy->getElementType()->isSized();
157 if (!isa<StructType>(this)) return false;
159 // Okay, our struct is sized if all of the elements are...
160 for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
161 if (!(*I)->isSized()) return false;
166 /// getForwardedTypeInternal - This method is used to implement the union-find
167 /// algorithm for when a type is being forwarded to another type.
168 const Type *Type::getForwardedTypeInternal() const {
169 assert(ForwardType && "This type is not being forwarded to another type!");
171 // Check to see if the forwarded type has been forwarded on. If so, collapse
172 // the forwarding links.
173 const Type *RealForwardedType = ForwardType->getForwardedType();
174 if (!RealForwardedType)
175 return ForwardType; // No it's not forwarded again
177 // Yes, it is forwarded again. First thing, add the reference to the new
179 if (RealForwardedType->isAbstract())
180 cast<DerivedType>(RealForwardedType)->addRef();
182 // Now drop the old reference. This could cause ForwardType to get deleted.
183 cast<DerivedType>(ForwardType)->dropRef();
185 // Return the updated type.
186 ForwardType = RealForwardedType;
190 // getTypeDescription - This is a recursive function that walks a type hierarchy
191 // calculating the description for a type.
193 static std::string getTypeDescription(const Type *Ty,
194 std::vector<const Type *> &TypeStack) {
195 if (isa<OpaqueType>(Ty)) { // Base case for the recursion
196 std::map<const Type*, std::string>::iterator I =
197 AbstractTypeDescriptions.lower_bound(Ty);
198 if (I != AbstractTypeDescriptions.end() && I->first == Ty)
200 std::string Desc = "opaque";
201 AbstractTypeDescriptions.insert(std::make_pair(Ty, Desc));
205 if (!Ty->isAbstract()) { // Base case for the recursion
206 std::map<const Type*, std::string>::iterator I =
207 ConcreteTypeDescriptions.find(Ty);
208 if (I != ConcreteTypeDescriptions.end()) return I->second;
211 // Check to see if the Type is already on the stack...
212 unsigned Slot = 0, CurSize = TypeStack.size();
213 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
215 // This is another base case for the recursion. In this case, we know
216 // that we have looped back to a type that we have previously visited.
217 // Generate the appropriate upreference to handle this.
220 return "\\" + utostr(CurSize-Slot); // Here's the upreference
222 // Recursive case: derived types...
224 TypeStack.push_back(Ty); // Add us to the stack..
226 switch (Ty->getTypeID()) {
227 case Type::FunctionTyID: {
228 const FunctionType *FTy = cast<FunctionType>(Ty);
229 Result = getTypeDescription(FTy->getReturnType(), TypeStack) + " (";
230 for (FunctionType::param_iterator I = FTy->param_begin(),
231 E = FTy->param_end(); I != E; ++I) {
232 if (I != FTy->param_begin())
234 Result += getTypeDescription(*I, TypeStack);
236 if (FTy->isVarArg()) {
237 if (FTy->getNumParams()) Result += ", ";
243 case Type::StructTyID: {
244 const StructType *STy = cast<StructType>(Ty);
246 for (StructType::element_iterator I = STy->element_begin(),
247 E = STy->element_end(); I != E; ++I) {
248 if (I != STy->element_begin())
250 Result += getTypeDescription(*I, TypeStack);
255 case Type::PointerTyID: {
256 const PointerType *PTy = cast<PointerType>(Ty);
257 Result = getTypeDescription(PTy->getElementType(), TypeStack) + " *";
260 case Type::ArrayTyID: {
261 const ArrayType *ATy = cast<ArrayType>(Ty);
262 unsigned NumElements = ATy->getNumElements();
264 Result += utostr(NumElements) + " x ";
265 Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
268 case Type::PackedTyID: {
269 const PackedType *PTy = cast<PackedType>(Ty);
270 unsigned NumElements = PTy->getNumElements();
272 Result += utostr(NumElements) + " x ";
273 Result += getTypeDescription(PTy->getElementType(), TypeStack) + ">";
278 assert(0 && "Unhandled type in getTypeDescription!");
281 TypeStack.pop_back(); // Remove self from stack...
288 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
290 std::map<const Type*, std::string>::iterator I = Map.find(Ty);
291 if (I != Map.end()) return I->second;
293 std::vector<const Type *> TypeStack;
294 std::string Result = getTypeDescription(Ty, TypeStack);
295 return Map[Ty] = Result;
299 const std::string &Type::getDescription() const {
301 return getOrCreateDesc(AbstractTypeDescriptions, this);
303 return getOrCreateDesc(ConcreteTypeDescriptions, this);
307 bool StructType::indexValid(const Value *V) const {
308 // Structure indexes require unsigned integer constants.
309 if (V->getType() == Type::UIntTy)
310 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(V))
311 return CU->getValue() < ContainedTys.size();
315 // getTypeAtIndex - Given an index value into the type, return the type of the
316 // element. For a structure type, this must be a constant value...
318 const Type *StructType::getTypeAtIndex(const Value *V) const {
319 assert(indexValid(V) && "Invalid structure index!");
320 unsigned Idx = (unsigned)cast<ConstantUInt>(V)->getValue();
321 return ContainedTys[Idx];
325 //===----------------------------------------------------------------------===//
326 // Static 'Type' data
327 //===----------------------------------------------------------------------===//
330 struct PrimType : public Type {
331 PrimType(const char *S, TypeID ID) : Type(S, ID) {}
335 static PrimType TheVoidTy ("void" , Type::VoidTyID);
336 static PrimType TheBoolTy ("bool" , Type::BoolTyID);
337 static PrimType TheSByteTy ("sbyte" , Type::SByteTyID);
338 static PrimType TheUByteTy ("ubyte" , Type::UByteTyID);
339 static PrimType TheShortTy ("short" , Type::ShortTyID);
340 static PrimType TheUShortTy("ushort", Type::UShortTyID);
341 static PrimType TheIntTy ("int" , Type::IntTyID);
342 static PrimType TheUIntTy ("uint" , Type::UIntTyID);
343 static PrimType TheLongTy ("long" , Type::LongTyID);
344 static PrimType TheULongTy ("ulong" , Type::ULongTyID);
345 static PrimType TheFloatTy ("float" , Type::FloatTyID);
346 static PrimType TheDoubleTy("double", Type::DoubleTyID);
347 static PrimType TheLabelTy ("label" , Type::LabelTyID);
349 Type *Type::VoidTy = &TheVoidTy;
350 Type *Type::BoolTy = &TheBoolTy;
351 Type *Type::SByteTy = &TheSByteTy;
352 Type *Type::UByteTy = &TheUByteTy;
353 Type *Type::ShortTy = &TheShortTy;
354 Type *Type::UShortTy = &TheUShortTy;
355 Type *Type::IntTy = &TheIntTy;
356 Type *Type::UIntTy = &TheUIntTy;
357 Type *Type::LongTy = &TheLongTy;
358 Type *Type::ULongTy = &TheULongTy;
359 Type *Type::FloatTy = &TheFloatTy;
360 Type *Type::DoubleTy = &TheDoubleTy;
361 Type *Type::LabelTy = &TheLabelTy;
364 //===----------------------------------------------------------------------===//
365 // Derived Type Constructors
366 //===----------------------------------------------------------------------===//
368 FunctionType::FunctionType(const Type *Result,
369 const std::vector<const Type*> &Params,
370 bool IsVarArgs) : DerivedType(FunctionTyID),
371 isVarArgs(IsVarArgs) {
372 assert((Result->isFirstClassType() || Result == Type::VoidTy ||
373 isa<OpaqueType>(Result)) &&
374 "LLVM functions cannot return aggregates");
375 bool isAbstract = Result->isAbstract();
376 ContainedTys.reserve(Params.size()+1);
377 ContainedTys.push_back(PATypeHandle(Result, this));
379 for (unsigned i = 0; i != Params.size(); ++i) {
380 assert((Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])) &&
381 "Function arguments must be value types!");
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, uint64_t NumEl)
406 : SequentialType(ArrayTyID, ElType) {
409 // Calculate whether or not this type is abstract
410 setAbstract(ElType->isAbstract());
413 PackedType::PackedType(const Type *ElType, unsigned NumEl)
414 : SequentialType(PackedTyID, ElType) {
417 assert(NumEl > 0 && "NumEl of a PackedType must be greater than 0");
418 assert((ElType->isIntegral() || ElType->isFloatingPoint()) &&
419 "Elements of a PackedType must be a primitive type");
423 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
424 // Calculate whether or not this type is abstract
425 setAbstract(E->isAbstract());
428 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
430 #ifdef DEBUG_MERGE_TYPES
431 std::cerr << "Derived new type: " << *this << "\n";
435 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
436 // another (more concrete) type, we must eliminate all references to other
437 // types, to avoid some circular reference problems.
438 void DerivedType::dropAllTypeUses() {
439 if (!ContainedTys.empty()) {
440 while (ContainedTys.size() > 1)
441 ContainedTys.pop_back();
443 // The type must stay abstract. To do this, we insert a pointer to a type
444 // that will never get resolved, thus will always be abstract.
445 static Type *AlwaysOpaqueTy = OpaqueType::get();
446 static PATypeHolder Holder(AlwaysOpaqueTy);
447 ContainedTys[0] = AlwaysOpaqueTy;
453 /// TypePromotionGraph and graph traits - this is designed to allow us to do
454 /// efficient SCC processing of type graphs. This is the exact same as
455 /// GraphTraits<Type*>, except that we pretend that concrete types have no
456 /// children to avoid processing them.
457 struct TypePromotionGraph {
459 TypePromotionGraph(Type *T) : Ty(T) {}
463 template <> struct GraphTraits<TypePromotionGraph> {
464 typedef Type NodeType;
465 typedef Type::subtype_iterator ChildIteratorType;
467 static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
468 static inline ChildIteratorType child_begin(NodeType *N) {
470 return N->subtype_begin();
471 else // No need to process children of concrete types.
472 return N->subtype_end();
474 static inline ChildIteratorType child_end(NodeType *N) {
475 return N->subtype_end();
481 // PromoteAbstractToConcrete - This is a recursive function that walks a type
482 // graph calculating whether or not a type is abstract.
484 // This method returns true if the type is found to still be abstract.
486 void Type::PromoteAbstractToConcrete() {
487 if (!isAbstract()) return;
489 scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
490 scc_iterator<TypePromotionGraph> SE = scc_end (TypePromotionGraph(this));
492 for (; SI != SE; ++SI) {
493 std::vector<Type*> &SCC = *SI;
495 // Concrete types are leaves in the tree. Since an SCC will either be all
496 // abstract or all concrete, we only need to check one type.
497 if (SCC[0]->isAbstract()) {
498 if (isa<OpaqueType>(SCC[0]))
499 return; // Not going to be concrete, sorry.
501 // If all of the children of all of the types in this SCC are concrete,
502 // then this SCC is now concrete as well. If not, neither this SCC, nor
503 // any parent SCCs will be concrete, so we might as well just exit.
504 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
505 for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
506 E = SCC[i]->subtype_end(); CI != E; ++CI)
507 if ((*CI)->isAbstract())
508 return; // Not going to be concrete, sorry.
510 // Okay, we just discovered this whole SCC is now concrete, mark it as
512 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
513 assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
515 SCC[i]->setAbstract(false);
516 // The type just became concrete, notify all users!
517 cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
524 //===----------------------------------------------------------------------===//
525 // Type Structural Equality Testing
526 //===----------------------------------------------------------------------===//
528 // TypesEqual - Two types are considered structurally equal if they have the
529 // same "shape": Every level and element of the types have identical primitive
530 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
531 // be pointer equals to be equivalent though. This uses an optimistic algorithm
532 // that assumes that two graphs are the same until proven otherwise.
534 static bool TypesEqual(const Type *Ty, const Type *Ty2,
535 std::map<const Type *, const Type *> &EqTypes) {
536 if (Ty == Ty2) return true;
537 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
538 if (isa<OpaqueType>(Ty))
539 return false; // Two unequal opaque types are never equal
541 std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
542 if (It != EqTypes.end() && It->first == Ty)
543 return It->second == Ty2; // Looping back on a type, check for equality
545 // Otherwise, add the mapping to the table to make sure we don't get
546 // recursion on the types...
547 EqTypes.insert(It, std::make_pair(Ty, Ty2));
549 // Two really annoying special cases that breaks an otherwise nice simple
550 // algorithm is the fact that arraytypes have sizes that differentiates types,
551 // and that function types can be varargs or not. Consider this now.
553 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
554 return TypesEqual(PTy->getElementType(),
555 cast<PointerType>(Ty2)->getElementType(), EqTypes);
556 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
557 const StructType *STy2 = cast<StructType>(Ty2);
558 if (STy->getNumElements() != STy2->getNumElements()) return false;
559 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
560 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
563 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
564 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
565 return ATy->getNumElements() == ATy2->getNumElements() &&
566 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
567 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
568 const PackedType *PTy2 = cast<PackedType>(Ty2);
569 return PTy->getNumElements() == PTy2->getNumElements() &&
570 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
571 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
572 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
573 if (FTy->isVarArg() != FTy2->isVarArg() ||
574 FTy->getNumParams() != FTy2->getNumParams() ||
575 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
577 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i)
578 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
582 assert(0 && "Unknown derived type!");
587 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
588 std::map<const Type *, const Type *> EqTypes;
589 return TypesEqual(Ty, Ty2, EqTypes);
592 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
593 // TargetTy in the type graph. We know that Ty is an abstract type, so if we
594 // ever reach a non-abstract type, we know that we don't need to search the
596 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
597 std::set<const Type*> &VisitedTypes) {
598 if (TargetTy == CurTy) return true;
599 if (!CurTy->isAbstract()) return false;
601 if (!VisitedTypes.insert(CurTy).second)
602 return false; // Already been here.
604 for (Type::subtype_iterator I = CurTy->subtype_begin(),
605 E = CurTy->subtype_end(); I != E; ++I)
606 if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
611 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
612 std::set<const Type*> &VisitedTypes) {
613 if (TargetTy == CurTy) return true;
615 if (!VisitedTypes.insert(CurTy).second)
616 return false; // Already been here.
618 for (Type::subtype_iterator I = CurTy->subtype_begin(),
619 E = CurTy->subtype_end(); I != E; ++I)
620 if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
625 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
627 static bool TypeHasCycleThroughItself(const Type *Ty) {
628 std::set<const Type*> VisitedTypes;
630 if (Ty->isAbstract()) { // Optimized case for abstract types.
631 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
633 if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
636 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
638 if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
645 //===----------------------------------------------------------------------===//
646 // Derived Type Factory Functions
647 //===----------------------------------------------------------------------===//
649 // TypeMap - Make sure that only one instance of a particular type may be
650 // created on any given run of the compiler... note that this involves updating
651 // our map if an abstract type gets refined somehow.
654 template<class ValType, class TypeClass>
656 std::map<ValType, PATypeHolder> Map;
658 /// TypesByHash - Keep track of types by their structure hash value. Note
659 /// that we only keep track of types that have cycles through themselves in
662 std::multimap<unsigned, PATypeHolder> TypesByHash;
664 friend void Type::clearAllTypeMaps();
667 void clear(std::vector<Type *> &DerivedTypes) {
668 for (typename std::map<ValType, PATypeHolder>::iterator I = Map.begin(),
669 E = Map.end(); I != E; ++I)
670 DerivedTypes.push_back(I->second.get());
675 typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
676 ~TypeMap() { print("ON EXIT"); }
678 inline TypeClass *get(const ValType &V) {
679 iterator I = Map.find(V);
680 return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
683 inline void add(const ValType &V, TypeClass *Ty) {
684 Map.insert(std::make_pair(V, Ty));
686 // If this type has a cycle, remember it.
687 TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
691 void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
692 std::multimap<unsigned, PATypeHolder>::iterator I =
693 TypesByHash.lower_bound(Hash);
694 while (I->second != Ty) {
696 assert(I != TypesByHash.end() && I->first == Hash);
698 TypesByHash.erase(I);
701 /// finishRefinement - This method is called after we have updated an existing
702 /// type with its new components. We must now either merge the type away with
703 /// some other type or reinstall it in the map with it's new configuration.
704 /// The specified iterator tells us what the type USED to look like.
705 void finishRefinement(TypeClass *Ty, const DerivedType *OldType,
706 const Type *NewType) {
707 assert((Ty->isAbstract() || !OldType->isAbstract()) &&
708 "Refining a non-abstract type!");
709 #ifdef DEBUG_MERGE_TYPES
710 std::cerr << "refineAbstractTy(" << (void*)OldType << "[" << *OldType
711 << "], " << (void*)NewType << " [" << *NewType << "])\n";
714 // Make a temporary type holder for the type so that it doesn't disappear on
715 // us when we erase the entry from the map.
716 PATypeHolder TyHolder = Ty;
718 // The old record is now out-of-date, because one of the children has been
719 // updated. Remove the obsolete entry from the map.
720 Map.erase(ValType::get(Ty));
722 // Remember the structural hash for the type before we start hacking on it,
723 // in case we need it later.
724 unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
726 // Find the type element we are refining... and change it now!
727 for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
728 if (Ty->ContainedTys[i] == OldType) {
729 Ty->ContainedTys[i].removeUserFromConcrete();
730 Ty->ContainedTys[i] = NewType;
733 unsigned TypeHash = ValType::hashTypeStructure(Ty);
735 // If there are no cycles going through this node, we can do a simple,
736 // efficient lookup in the map, instead of an inefficient nasty linear
738 if (!Ty->isAbstract() || !TypeHasCycleThroughItself(Ty)) {
739 typename std::map<ValType, PATypeHolder>::iterator I;
742 ValType V = ValType::get(Ty);
743 tie(I, Inserted) = Map.insert(std::make_pair(V, Ty));
745 // Refined to a different type altogether?
746 RemoveFromTypesByHash(TypeHash, Ty);
748 // We already have this type in the table. Get rid of the newly refined
750 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
751 Ty->refineAbstractTypeTo(NewTy);
756 // Now we check to see if there is an existing entry in the table which is
757 // structurally identical to the newly refined type. If so, this type
758 // gets refined to the pre-existing type.
760 std::multimap<unsigned, PATypeHolder>::iterator I, E, Entry;
761 tie(I, E) = TypesByHash.equal_range(OldTypeHash);
763 for (; I != E; ++I) {
764 if (I->second != Ty) {
765 if (TypesEqual(Ty, I->second)) {
766 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
767 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
770 // Find the location of Ty in the TypesByHash structure.
771 while (I->second != Ty) {
773 assert(I != E && "Structure doesn't contain type??");
778 TypesByHash.erase(Entry);
779 Ty->refineAbstractTypeTo(NewTy);
783 // Remember the position of
789 // If there is no existing type of the same structure, we reinsert an
790 // updated record into the map.
791 Map.insert(std::make_pair(ValType::get(Ty), Ty));
794 // If the hash codes differ, update TypesByHash
795 if (TypeHash != OldTypeHash) {
796 RemoveFromTypesByHash(OldTypeHash, Ty);
797 TypesByHash.insert(std::make_pair(TypeHash, Ty));
800 // If the type is currently thought to be abstract, rescan all of our
801 // subtypes to see if the type has just become concrete!
802 if (Ty->isAbstract())
803 Ty->PromoteAbstractToConcrete();
806 void print(const char *Arg) const {
807 #ifdef DEBUG_MERGE_TYPES
808 std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
810 for (typename std::map<ValType, PATypeHolder>::const_iterator I
811 = Map.begin(), E = Map.end(); I != E; ++I)
812 std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " "
813 << *I->second.get() << "\n";
817 void dump() const { print("dump output"); }
822 //===----------------------------------------------------------------------===//
823 // Function Type Factory and Value Class...
826 // FunctionValType - Define a class to hold the key that goes into the TypeMap
829 class FunctionValType {
831 std::vector<const Type*> ArgTypes;
834 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
835 bool IVA) : RetTy(ret), isVarArg(IVA) {
836 for (unsigned i = 0; i < args.size(); ++i)
837 ArgTypes.push_back(args[i]);
840 static FunctionValType get(const FunctionType *FT);
842 static unsigned hashTypeStructure(const FunctionType *FT) {
843 return FT->getNumParams()*2+FT->isVarArg();
846 // Subclass should override this... to update self as usual
847 void doRefinement(const DerivedType *OldType, const Type *NewType) {
848 if (RetTy == OldType) RetTy = NewType;
849 for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
850 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
853 inline bool operator<(const FunctionValType &MTV) const {
854 if (RetTy < MTV.RetTy) return true;
855 if (RetTy > MTV.RetTy) return false;
857 if (ArgTypes < MTV.ArgTypes) return true;
858 return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
863 // Define the actual map itself now...
864 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
866 FunctionValType FunctionValType::get(const FunctionType *FT) {
867 // Build up a FunctionValType
868 std::vector<const Type *> ParamTypes;
869 ParamTypes.reserve(FT->getNumParams());
870 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
871 ParamTypes.push_back(FT->getParamType(i));
872 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
876 // FunctionType::get - The factory function for the FunctionType class...
877 FunctionType *FunctionType::get(const Type *ReturnType,
878 const std::vector<const Type*> &Params,
880 FunctionValType VT(ReturnType, Params, isVarArg);
881 FunctionType *MT = FunctionTypes.get(VT);
884 FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
886 #ifdef DEBUG_MERGE_TYPES
887 std::cerr << "Derived new type: " << MT << "\n";
892 //===----------------------------------------------------------------------===//
893 // Array Type Factory...
900 ArrayValType(const Type *val, uint64_t sz) : ValTy(val), Size(sz) {}
902 static ArrayValType get(const ArrayType *AT) {
903 return ArrayValType(AT->getElementType(), AT->getNumElements());
906 static unsigned hashTypeStructure(const ArrayType *AT) {
907 return (unsigned)AT->getNumElements();
910 // Subclass should override this... to update self as usual
911 void doRefinement(const DerivedType *OldType, const Type *NewType) {
912 assert(ValTy == OldType);
916 inline bool operator<(const ArrayValType &MTV) const {
917 if (Size < MTV.Size) return true;
918 return Size == MTV.Size && ValTy < MTV.ValTy;
922 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
925 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
926 assert(ElementType && "Can't get array of null types!");
928 ArrayValType AVT(ElementType, NumElements);
929 ArrayType *AT = ArrayTypes.get(AVT);
930 if (AT) return AT; // Found a match, return it!
932 // Value not found. Derive a new type!
933 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
935 #ifdef DEBUG_MERGE_TYPES
936 std::cerr << "Derived new type: " << *AT << "\n";
942 //===----------------------------------------------------------------------===//
943 // Packed Type Factory...
946 class PackedValType {
950 PackedValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
952 static PackedValType get(const PackedType *PT) {
953 return PackedValType(PT->getElementType(), PT->getNumElements());
956 static unsigned hashTypeStructure(const PackedType *PT) {
957 return PT->getNumElements();
960 // Subclass should override this... to update self as usual
961 void doRefinement(const DerivedType *OldType, const Type *NewType) {
962 assert(ValTy == OldType);
966 inline bool operator<(const PackedValType &MTV) const {
967 if (Size < MTV.Size) return true;
968 return Size == MTV.Size && ValTy < MTV.ValTy;
972 static TypeMap<PackedValType, PackedType> PackedTypes;
975 PackedType *PackedType::get(const Type *ElementType, unsigned NumElements) {
976 assert(ElementType && "Can't get packed of null types!");
978 PackedValType PVT(ElementType, NumElements);
979 PackedType *PT = PackedTypes.get(PVT);
980 if (PT) return PT; // Found a match, return it!
982 // Value not found. Derive a new type!
983 PackedTypes.add(PVT, PT = new PackedType(ElementType, NumElements));
985 #ifdef DEBUG_MERGE_TYPES
986 std::cerr << "Derived new type: " << *PT << "\n";
991 //===----------------------------------------------------------------------===//
992 // Struct Type Factory...
996 // StructValType - Define a class to hold the key that goes into the TypeMap
998 class StructValType {
999 std::vector<const Type*> ElTypes;
1001 StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
1003 static StructValType get(const StructType *ST) {
1004 std::vector<const Type *> ElTypes;
1005 ElTypes.reserve(ST->getNumElements());
1006 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
1007 ElTypes.push_back(ST->getElementType(i));
1009 return StructValType(ElTypes);
1012 static unsigned hashTypeStructure(const StructType *ST) {
1013 return ST->getNumElements();
1016 // Subclass should override this... to update self as usual
1017 void doRefinement(const DerivedType *OldType, const Type *NewType) {
1018 for (unsigned i = 0; i < ElTypes.size(); ++i)
1019 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
1022 inline bool operator<(const StructValType &STV) const {
1023 return ElTypes < STV.ElTypes;
1028 static TypeMap<StructValType, StructType> StructTypes;
1030 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
1031 StructValType STV(ETypes);
1032 StructType *ST = StructTypes.get(STV);
1035 // Value not found. Derive a new type!
1036 StructTypes.add(STV, ST = new StructType(ETypes));
1038 #ifdef DEBUG_MERGE_TYPES
1039 std::cerr << "Derived new type: " << *ST << "\n";
1046 //===----------------------------------------------------------------------===//
1047 // Pointer Type Factory...
1050 // PointerValType - Define a class to hold the key that goes into the TypeMap
1053 class PointerValType {
1056 PointerValType(const Type *val) : ValTy(val) {}
1058 static PointerValType get(const PointerType *PT) {
1059 return PointerValType(PT->getElementType());
1062 static unsigned hashTypeStructure(const PointerType *PT) {
1066 // Subclass should override this... to update self as usual
1067 void doRefinement(const DerivedType *OldType, const Type *NewType) {
1068 assert(ValTy == OldType);
1072 bool operator<(const PointerValType &MTV) const {
1073 return ValTy < MTV.ValTy;
1078 static TypeMap<PointerValType, PointerType> PointerTypes;
1080 PointerType *PointerType::get(const Type *ValueType) {
1081 assert(ValueType && "Can't get a pointer to <null> type!");
1082 PointerValType PVT(ValueType);
1084 PointerType *PT = PointerTypes.get(PVT);
1087 // Value not found. Derive a new type!
1088 PointerTypes.add(PVT, PT = new PointerType(ValueType));
1090 #ifdef DEBUG_MERGE_TYPES
1091 std::cerr << "Derived new type: " << *PT << "\n";
1097 //===----------------------------------------------------------------------===//
1098 // Derived Type Refinement Functions
1099 //===----------------------------------------------------------------------===//
1101 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1102 // no longer has a handle to the type. This function is called primarily by
1103 // the PATypeHandle class. When there are no users of the abstract type, it
1104 // is annihilated, because there is no way to get a reference to it ever again.
1106 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
1107 // Search from back to front because we will notify users from back to
1108 // front. Also, it is likely that there will be a stack like behavior to
1109 // users that register and unregister users.
1112 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1113 assert(i != 0 && "AbstractTypeUser not in user list!");
1115 --i; // Convert to be in range 0 <= i < size()
1116 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1118 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1120 #ifdef DEBUG_MERGE_TYPES
1121 std::cerr << " remAbstractTypeUser[" << (void*)this << ", "
1122 << *this << "][" << i << "] User = " << U << "\n";
1125 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1126 #ifdef DEBUG_MERGE_TYPES
1127 std::cerr << "DELETEing unused abstract type: <" << *this
1128 << ">[" << (void*)this << "]" << "\n";
1130 delete this; // No users of this abstract type!
1135 // refineAbstractTypeTo - This function is used to when it is discovered that
1136 // the 'this' abstract type is actually equivalent to the NewType specified.
1137 // This causes all users of 'this' to switch to reference the more concrete type
1138 // NewType and for 'this' to be deleted.
1140 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1141 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1142 assert(this != NewType && "Can't refine to myself!");
1143 assert(ForwardType == 0 && "This type has already been refined!");
1145 // The descriptions may be out of date. Conservatively clear them all!
1146 AbstractTypeDescriptions.clear();
1148 #ifdef DEBUG_MERGE_TYPES
1149 std::cerr << "REFINING abstract type [" << (void*)this << " "
1150 << *this << "] to [" << (void*)NewType << " "
1151 << *NewType << "]!\n";
1154 // Make sure to put the type to be refined to into a holder so that if IT gets
1155 // refined, that we will not continue using a dead reference...
1157 PATypeHolder NewTy(NewType);
1159 // Any PATypeHolders referring to this type will now automatically forward to
1160 // the type we are resolved to.
1161 ForwardType = NewType;
1162 if (NewType->isAbstract())
1163 cast<DerivedType>(NewType)->addRef();
1165 // Add a self use of the current type so that we don't delete ourself until
1166 // after the function exits.
1168 PATypeHolder CurrentTy(this);
1170 // To make the situation simpler, we ask the subclass to remove this type from
1171 // the type map, and to replace any type uses with uses of non-abstract types.
1172 // This dramatically limits the amount of recursive type trouble we can find
1176 // Iterate over all of the uses of this type, invoking callback. Each user
1177 // should remove itself from our use list automatically. We have to check to
1178 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1179 // will not cause users to drop off of the use list. If we resolve to ourself
1182 while (!AbstractTypeUsers.empty() && NewTy != this) {
1183 AbstractTypeUser *User = AbstractTypeUsers.back();
1185 unsigned OldSize = AbstractTypeUsers.size();
1186 #ifdef DEBUG_MERGE_TYPES
1187 std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
1188 << "] of abstract type [" << (void*)this << " "
1189 << *this << "] to [" << (void*)NewTy.get() << " "
1190 << *NewTy << "]!\n";
1192 User->refineAbstractType(this, NewTy);
1194 assert(AbstractTypeUsers.size() != OldSize &&
1195 "AbsTyUser did not remove self from user list!");
1198 // If we were successful removing all users from the type, 'this' will be
1199 // deleted when the last PATypeHolder is destroyed or updated from this type.
1200 // This may occur on exit of this function, as the CurrentTy object is
1204 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1205 // the current type has transitioned from being abstract to being concrete.
1207 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1208 #ifdef DEBUG_MERGE_TYPES
1209 std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1212 unsigned OldSize = AbstractTypeUsers.size();
1213 while (!AbstractTypeUsers.empty()) {
1214 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1215 ATU->typeBecameConcrete(this);
1217 assert(AbstractTypeUsers.size() < OldSize-- &&
1218 "AbstractTypeUser did not remove itself from the use list!");
1225 // refineAbstractType - Called when a contained type is found to be more
1226 // concrete - this could potentially change us from an abstract type to a
1229 void FunctionType::refineAbstractType(const DerivedType *OldType,
1230 const Type *NewType) {
1231 FunctionTypes.finishRefinement(this, OldType, NewType);
1234 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1235 refineAbstractType(AbsTy, AbsTy);
1239 // refineAbstractType - Called when a contained type is found to be more
1240 // concrete - this could potentially change us from an abstract type to a
1243 void ArrayType::refineAbstractType(const DerivedType *OldType,
1244 const Type *NewType) {
1245 ArrayTypes.finishRefinement(this, OldType, NewType);
1248 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1249 refineAbstractType(AbsTy, AbsTy);
1252 // refineAbstractType - Called when a contained type is found to be more
1253 // concrete - this could potentially change us from an abstract type to a
1256 void PackedType::refineAbstractType(const DerivedType *OldType,
1257 const Type *NewType) {
1258 PackedTypes.finishRefinement(this, OldType, NewType);
1261 void PackedType::typeBecameConcrete(const DerivedType *AbsTy) {
1262 refineAbstractType(AbsTy, AbsTy);
1265 // refineAbstractType - Called when a contained type is found to be more
1266 // concrete - this could potentially change us from an abstract type to a
1269 void StructType::refineAbstractType(const DerivedType *OldType,
1270 const Type *NewType) {
1271 StructTypes.finishRefinement(this, OldType, NewType);
1274 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1275 refineAbstractType(AbsTy, AbsTy);
1278 // refineAbstractType - Called when a contained type is found to be more
1279 // concrete - this could potentially change us from an abstract type to a
1282 void PointerType::refineAbstractType(const DerivedType *OldType,
1283 const Type *NewType) {
1284 PointerTypes.finishRefinement(this, OldType, NewType);
1287 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1288 refineAbstractType(AbsTy, AbsTy);
1291 bool SequentialType::indexValid(const Value *V) const {
1292 const Type *Ty = V->getType();
1293 switch (Ty->getTypeID()) {
1295 case Type::UIntTyID:
1296 case Type::LongTyID:
1297 case Type::ULongTyID:
1305 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1307 OS << "<null> value!\n";
1313 std::ostream &operator<<(std::ostream &OS, const Type &T) {
1319 /// clearAllTypeMaps - This method frees all internal memory used by the
1320 /// type subsystem, which can be used in environments where this memory is
1321 /// otherwise reported as a leak.
1322 void Type::clearAllTypeMaps() {
1323 std::vector<Type *> DerivedTypes;
1325 FunctionTypes.clear(DerivedTypes);
1326 PointerTypes.clear(DerivedTypes);
1327 StructTypes.clear(DerivedTypes);
1328 ArrayTypes.clear(DerivedTypes);
1329 PackedTypes.clear(DerivedTypes);
1331 for(std::vector<Type *>::iterator I = DerivedTypes.begin(),
1332 E = DerivedTypes.end(); I != E; ++I)
1333 (*I)->ContainedTys.clear();
1334 for(std::vector<Type *>::iterator I = DerivedTypes.begin(),
1335 E = DerivedTypes.end(); I != E; ++I)
1337 DerivedTypes.clear();