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"
22 #include "llvm/Support/MathExtras.h"
27 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
28 // created and later destroyed, all in an effort to make sure that there is only
29 // a single canonical version of a type.
31 //#define DEBUG_MERGE_TYPES 1
33 AbstractTypeUser::~AbstractTypeUser() {}
35 //===----------------------------------------------------------------------===//
36 // Type Class Implementation
37 //===----------------------------------------------------------------------===//
39 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
40 // for types as they are needed. Because resolution of types must invalidate
41 // all of the abstract type descriptions, we keep them in a seperate map to make
43 static std::map<const Type*, std::string> ConcreteTypeDescriptions;
44 static std::map<const Type*, std::string> AbstractTypeDescriptions;
46 Type::Type( const std::string& name, TypeID id )
47 : RefCount(0), ForwardType(0) {
49 ConcreteTypeDescriptions[this] = name;
54 const Type *Type::getPrimitiveType(TypeID IDNumber) {
56 case VoidTyID : return VoidTy;
57 case BoolTyID : return BoolTy;
58 case UByteTyID : return UByteTy;
59 case SByteTyID : return SByteTy;
60 case UShortTyID: return UShortTy;
61 case ShortTyID : return ShortTy;
62 case UIntTyID : return UIntTy;
63 case IntTyID : return IntTy;
64 case ULongTyID : return ULongTy;
65 case LongTyID : return LongTy;
66 case FloatTyID : return FloatTy;
67 case DoubleTyID: return DoubleTy;
68 case LabelTyID : return LabelTy;
74 // isLosslesslyConvertibleTo - Return true if this type can be converted to
75 // 'Ty' without any reinterpretation of bits. For example, uint to int.
77 bool Type::isLosslesslyConvertibleTo(const Type *Ty) const {
78 if (this == Ty) return true;
79 if ((!isPrimitiveType() && !isa<PointerType>(this)) ||
80 (!isa<PointerType>(Ty) && !Ty->isPrimitiveType())) return false;
82 if (getTypeID() == Ty->getTypeID())
83 return true; // Handles identity cast, and cast of differing pointer types
85 // Now we know that they are two differing primitive or pointer types
86 switch (getTypeID()) {
87 case Type::UByteTyID: return Ty == Type::SByteTy;
88 case Type::SByteTyID: return Ty == Type::UByteTy;
89 case Type::UShortTyID: return Ty == Type::ShortTy;
90 case Type::ShortTyID: return Ty == Type::UShortTy;
91 case Type::UIntTyID: return Ty == Type::IntTy;
92 case Type::IntTyID: return Ty == Type::UIntTy;
93 case Type::ULongTyID: return Ty == Type::LongTy;
94 case Type::LongTyID: return Ty == Type::ULongTy;
95 case Type::PointerTyID: return isa<PointerType>(Ty);
97 return false; // Other types have no identity values
101 /// getUnsignedVersion - If this is an integer type, return the unsigned
102 /// variant of this type. For example int -> uint.
103 const Type *Type::getUnsignedVersion() const {
104 switch (getTypeID()) {
106 assert(isInteger()&&"Type::getUnsignedVersion is only valid for integers!");
107 case Type::UByteTyID:
108 case Type::SByteTyID: return Type::UByteTy;
109 case Type::UShortTyID:
110 case Type::ShortTyID: return Type::UShortTy;
112 case Type::IntTyID: return Type::UIntTy;
113 case Type::ULongTyID:
114 case Type::LongTyID: return Type::ULongTy;
118 /// getSignedVersion - If this is an integer type, return the signed variant
119 /// of this type. For example uint -> int.
120 const Type *Type::getSignedVersion() const {
121 switch (getTypeID()) {
123 assert(isInteger() && "Type::getSignedVersion is only valid for integers!");
124 case Type::UByteTyID:
125 case Type::SByteTyID: return Type::SByteTy;
126 case Type::UShortTyID:
127 case Type::ShortTyID: return Type::ShortTy;
129 case Type::IntTyID: return Type::IntTy;
130 case Type::ULongTyID:
131 case Type::LongTyID: return Type::LongTy;
136 // getPrimitiveSize - Return the basic size of this type if it is a primitive
137 // type. These are fixed by LLVM and are not target dependent. This will
138 // return zero if the type does not have a size or is not a primitive type.
140 unsigned Type::getPrimitiveSize() const {
141 switch (getTypeID()) {
143 case Type::SByteTyID:
144 case Type::UByteTyID: return 1;
145 case Type::UShortTyID:
146 case Type::ShortTyID: return 2;
147 case Type::FloatTyID:
149 case Type::UIntTyID: return 4;
151 case Type::ULongTyID:
152 case Type::DoubleTyID: return 8;
157 unsigned Type::getPrimitiveSizeInBits() const {
158 switch (getTypeID()) {
159 case Type::BoolTyID: return 1;
160 case Type::SByteTyID:
161 case Type::UByteTyID: return 8;
162 case Type::UShortTyID:
163 case Type::ShortTyID: return 16;
164 case Type::FloatTyID:
166 case Type::UIntTyID: return 32;
168 case Type::ULongTyID:
169 case Type::DoubleTyID: return 64;
174 /// isSizedDerivedType - Derived types like structures and arrays are sized
175 /// iff all of the members of the type are sized as well. Since asking for
176 /// their size is relatively uncommon, move this operation out of line.
177 bool Type::isSizedDerivedType() const {
178 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
179 return ATy->getElementType()->isSized();
181 if (const PackedType *PTy = dyn_cast<PackedType>(this))
182 return PTy->getElementType()->isSized();
184 if (!isa<StructType>(this)) return false;
186 // Okay, our struct is sized if all of the elements are...
187 for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
188 if (!(*I)->isSized()) return false;
193 /// getForwardedTypeInternal - This method is used to implement the union-find
194 /// algorithm for when a type is being forwarded to another type.
195 const Type *Type::getForwardedTypeInternal() const {
196 assert(ForwardType && "This type is not being forwarded to another type!");
198 // Check to see if the forwarded type has been forwarded on. If so, collapse
199 // the forwarding links.
200 const Type *RealForwardedType = ForwardType->getForwardedType();
201 if (!RealForwardedType)
202 return ForwardType; // No it's not forwarded again
204 // Yes, it is forwarded again. First thing, add the reference to the new
206 if (RealForwardedType->isAbstract())
207 cast<DerivedType>(RealForwardedType)->addRef();
209 // Now drop the old reference. This could cause ForwardType to get deleted.
210 cast<DerivedType>(ForwardType)->dropRef();
212 // Return the updated type.
213 ForwardType = RealForwardedType;
217 // getTypeDescription - This is a recursive function that walks a type hierarchy
218 // calculating the description for a type.
220 static std::string getTypeDescription(const Type *Ty,
221 std::vector<const Type *> &TypeStack) {
222 if (isa<OpaqueType>(Ty)) { // Base case for the recursion
223 std::map<const Type*, std::string>::iterator I =
224 AbstractTypeDescriptions.lower_bound(Ty);
225 if (I != AbstractTypeDescriptions.end() && I->first == Ty)
227 std::string Desc = "opaque";
228 AbstractTypeDescriptions.insert(std::make_pair(Ty, Desc));
232 if (!Ty->isAbstract()) { // Base case for the recursion
233 std::map<const Type*, std::string>::iterator I =
234 ConcreteTypeDescriptions.find(Ty);
235 if (I != ConcreteTypeDescriptions.end()) return I->second;
238 // Check to see if the Type is already on the stack...
239 unsigned Slot = 0, CurSize = TypeStack.size();
240 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
242 // This is another base case for the recursion. In this case, we know
243 // that we have looped back to a type that we have previously visited.
244 // Generate the appropriate upreference to handle this.
247 return "\\" + utostr(CurSize-Slot); // Here's the upreference
249 // Recursive case: derived types...
251 TypeStack.push_back(Ty); // Add us to the stack..
253 switch (Ty->getTypeID()) {
254 case Type::FunctionTyID: {
255 const FunctionType *FTy = cast<FunctionType>(Ty);
256 Result = getTypeDescription(FTy->getReturnType(), TypeStack) + " (";
257 for (FunctionType::param_iterator I = FTy->param_begin(),
258 E = FTy->param_end(); I != E; ++I) {
259 if (I != FTy->param_begin())
261 Result += getTypeDescription(*I, TypeStack);
263 if (FTy->isVarArg()) {
264 if (FTy->getNumParams()) Result += ", ";
270 case Type::StructTyID: {
271 const StructType *STy = cast<StructType>(Ty);
273 for (StructType::element_iterator I = STy->element_begin(),
274 E = STy->element_end(); I != E; ++I) {
275 if (I != STy->element_begin())
277 Result += getTypeDescription(*I, TypeStack);
282 case Type::PointerTyID: {
283 const PointerType *PTy = cast<PointerType>(Ty);
284 Result = getTypeDescription(PTy->getElementType(), TypeStack) + " *";
287 case Type::ArrayTyID: {
288 const ArrayType *ATy = cast<ArrayType>(Ty);
289 unsigned NumElements = ATy->getNumElements();
291 Result += utostr(NumElements) + " x ";
292 Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
295 case Type::PackedTyID: {
296 const PackedType *PTy = cast<PackedType>(Ty);
297 unsigned NumElements = PTy->getNumElements();
299 Result += utostr(NumElements) + " x ";
300 Result += getTypeDescription(PTy->getElementType(), TypeStack) + ">";
305 assert(0 && "Unhandled type in getTypeDescription!");
308 TypeStack.pop_back(); // Remove self from stack...
315 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
317 std::map<const Type*, std::string>::iterator I = Map.find(Ty);
318 if (I != Map.end()) return I->second;
320 std::vector<const Type *> TypeStack;
321 std::string Result = getTypeDescription(Ty, TypeStack);
322 return Map[Ty] = Result;
326 const std::string &Type::getDescription() const {
328 return getOrCreateDesc(AbstractTypeDescriptions, this);
330 return getOrCreateDesc(ConcreteTypeDescriptions, this);
334 bool StructType::indexValid(const Value *V) const {
335 // Structure indexes require unsigned integer constants.
336 if (V->getType() == Type::UIntTy)
337 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(V))
338 return CU->getValue() < ContainedTys.size();
342 // getTypeAtIndex - Given an index value into the type, return the type of the
343 // element. For a structure type, this must be a constant value...
345 const Type *StructType::getTypeAtIndex(const Value *V) const {
346 assert(indexValid(V) && "Invalid structure index!");
347 unsigned Idx = (unsigned)cast<ConstantUInt>(V)->getValue();
348 return ContainedTys[Idx];
352 //===----------------------------------------------------------------------===//
353 // Static 'Type' data
354 //===----------------------------------------------------------------------===//
357 struct PrimType : public Type {
358 PrimType(const char *S, TypeID ID) : Type(S, ID) {}
362 static PrimType TheVoidTy ("void" , Type::VoidTyID);
363 static PrimType TheBoolTy ("bool" , Type::BoolTyID);
364 static PrimType TheSByteTy ("sbyte" , Type::SByteTyID);
365 static PrimType TheUByteTy ("ubyte" , Type::UByteTyID);
366 static PrimType TheShortTy ("short" , Type::ShortTyID);
367 static PrimType TheUShortTy("ushort", Type::UShortTyID);
368 static PrimType TheIntTy ("int" , Type::IntTyID);
369 static PrimType TheUIntTy ("uint" , Type::UIntTyID);
370 static PrimType TheLongTy ("long" , Type::LongTyID);
371 static PrimType TheULongTy ("ulong" , Type::ULongTyID);
372 static PrimType TheFloatTy ("float" , Type::FloatTyID);
373 static PrimType TheDoubleTy("double", Type::DoubleTyID);
374 static PrimType TheLabelTy ("label" , Type::LabelTyID);
376 Type *Type::VoidTy = &TheVoidTy;
377 Type *Type::BoolTy = &TheBoolTy;
378 Type *Type::SByteTy = &TheSByteTy;
379 Type *Type::UByteTy = &TheUByteTy;
380 Type *Type::ShortTy = &TheShortTy;
381 Type *Type::UShortTy = &TheUShortTy;
382 Type *Type::IntTy = &TheIntTy;
383 Type *Type::UIntTy = &TheUIntTy;
384 Type *Type::LongTy = &TheLongTy;
385 Type *Type::ULongTy = &TheULongTy;
386 Type *Type::FloatTy = &TheFloatTy;
387 Type *Type::DoubleTy = &TheDoubleTy;
388 Type *Type::LabelTy = &TheLabelTy;
391 //===----------------------------------------------------------------------===//
392 // Derived Type Constructors
393 //===----------------------------------------------------------------------===//
395 FunctionType::FunctionType(const Type *Result,
396 const std::vector<const Type*> &Params,
397 bool IsVarArgs) : DerivedType(FunctionTyID),
398 isVarArgs(IsVarArgs) {
399 assert((Result->isFirstClassType() || Result == Type::VoidTy ||
400 isa<OpaqueType>(Result)) &&
401 "LLVM functions cannot return aggregates");
402 bool isAbstract = Result->isAbstract();
403 ContainedTys.reserve(Params.size()+1);
404 ContainedTys.push_back(PATypeHandle(Result, this));
406 for (unsigned i = 0; i != Params.size(); ++i) {
407 assert((Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])) &&
408 "Function arguments must be value types!");
410 ContainedTys.push_back(PATypeHandle(Params[i], this));
411 isAbstract |= Params[i]->isAbstract();
414 // Calculate whether or not this type is abstract
415 setAbstract(isAbstract);
418 StructType::StructType(const std::vector<const Type*> &Types)
419 : CompositeType(StructTyID) {
420 ContainedTys.reserve(Types.size());
421 bool isAbstract = false;
422 for (unsigned i = 0; i < Types.size(); ++i) {
423 assert(Types[i] != Type::VoidTy && "Void type for structure field!!");
424 ContainedTys.push_back(PATypeHandle(Types[i], this));
425 isAbstract |= Types[i]->isAbstract();
428 // Calculate whether or not this type is abstract
429 setAbstract(isAbstract);
432 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
433 : SequentialType(ArrayTyID, ElType) {
436 // Calculate whether or not this type is abstract
437 setAbstract(ElType->isAbstract());
440 PackedType::PackedType(const Type *ElType, unsigned NumEl)
441 : SequentialType(PackedTyID, ElType) {
444 assert(NumEl > 0 && "NumEl of a PackedType must be greater than 0");
445 assert((ElType->isIntegral() || ElType->isFloatingPoint()) &&
446 "Elements of a PackedType must be a primitive type");
450 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
451 // Calculate whether or not this type is abstract
452 setAbstract(E->isAbstract());
455 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
457 #ifdef DEBUG_MERGE_TYPES
458 std::cerr << "Derived new type: " << *this << "\n";
462 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
463 // another (more concrete) type, we must eliminate all references to other
464 // types, to avoid some circular reference problems.
465 void DerivedType::dropAllTypeUses() {
466 if (!ContainedTys.empty()) {
467 while (ContainedTys.size() > 1)
468 ContainedTys.pop_back();
470 // The type must stay abstract. To do this, we insert a pointer to a type
471 // that will never get resolved, thus will always be abstract.
472 static Type *AlwaysOpaqueTy = OpaqueType::get();
473 static PATypeHolder Holder(AlwaysOpaqueTy);
474 ContainedTys[0] = AlwaysOpaqueTy;
480 /// TypePromotionGraph and graph traits - this is designed to allow us to do
481 /// efficient SCC processing of type graphs. This is the exact same as
482 /// GraphTraits<Type*>, except that we pretend that concrete types have no
483 /// children to avoid processing them.
484 struct TypePromotionGraph {
486 TypePromotionGraph(Type *T) : Ty(T) {}
490 template <> struct GraphTraits<TypePromotionGraph> {
491 typedef Type NodeType;
492 typedef Type::subtype_iterator ChildIteratorType;
494 static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
495 static inline ChildIteratorType child_begin(NodeType *N) {
497 return N->subtype_begin();
498 else // No need to process children of concrete types.
499 return N->subtype_end();
501 static inline ChildIteratorType child_end(NodeType *N) {
502 return N->subtype_end();
508 // PromoteAbstractToConcrete - This is a recursive function that walks a type
509 // graph calculating whether or not a type is abstract.
511 void Type::PromoteAbstractToConcrete() {
512 if (!isAbstract()) return;
514 scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
515 scc_iterator<TypePromotionGraph> SE = scc_end (TypePromotionGraph(this));
517 for (; SI != SE; ++SI) {
518 std::vector<Type*> &SCC = *SI;
520 // Concrete types are leaves in the tree. Since an SCC will either be all
521 // abstract or all concrete, we only need to check one type.
522 if (SCC[0]->isAbstract()) {
523 if (isa<OpaqueType>(SCC[0]))
524 return; // Not going to be concrete, sorry.
526 // If all of the children of all of the types in this SCC are concrete,
527 // then this SCC is now concrete as well. If not, neither this SCC, nor
528 // any parent SCCs will be concrete, so we might as well just exit.
529 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
530 for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
531 E = SCC[i]->subtype_end(); CI != E; ++CI)
532 if ((*CI)->isAbstract())
533 // If the child type is in our SCC, it doesn't make the entire SCC
534 // abstract unless there is a non-SCC abstract type.
535 if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
536 return; // Not going to be concrete, sorry.
538 // Okay, we just discovered this whole SCC is now concrete, mark it as
540 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
541 assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
543 SCC[i]->setAbstract(false);
546 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
547 assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
548 // The type just became concrete, notify all users!
549 cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
556 //===----------------------------------------------------------------------===//
557 // Type Structural Equality Testing
558 //===----------------------------------------------------------------------===//
560 // TypesEqual - Two types are considered structurally equal if they have the
561 // same "shape": Every level and element of the types have identical primitive
562 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
563 // be pointer equals to be equivalent though. This uses an optimistic algorithm
564 // that assumes that two graphs are the same until proven otherwise.
566 static bool TypesEqual(const Type *Ty, const Type *Ty2,
567 std::map<const Type *, const Type *> &EqTypes) {
568 if (Ty == Ty2) return true;
569 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
570 if (isa<OpaqueType>(Ty))
571 return false; // Two unequal opaque types are never equal
573 std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
574 if (It != EqTypes.end() && It->first == Ty)
575 return It->second == Ty2; // Looping back on a type, check for equality
577 // Otherwise, add the mapping to the table to make sure we don't get
578 // recursion on the types...
579 EqTypes.insert(It, std::make_pair(Ty, Ty2));
581 // Two really annoying special cases that breaks an otherwise nice simple
582 // algorithm is the fact that arraytypes have sizes that differentiates types,
583 // and that function types can be varargs or not. Consider this now.
585 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
586 return TypesEqual(PTy->getElementType(),
587 cast<PointerType>(Ty2)->getElementType(), EqTypes);
588 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
589 const StructType *STy2 = cast<StructType>(Ty2);
590 if (STy->getNumElements() != STy2->getNumElements()) return false;
591 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
592 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
595 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
596 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
597 return ATy->getNumElements() == ATy2->getNumElements() &&
598 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
599 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
600 const PackedType *PTy2 = cast<PackedType>(Ty2);
601 return PTy->getNumElements() == PTy2->getNumElements() &&
602 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
603 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
604 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
605 if (FTy->isVarArg() != FTy2->isVarArg() ||
606 FTy->getNumParams() != FTy2->getNumParams() ||
607 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
609 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i)
610 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
614 assert(0 && "Unknown derived type!");
619 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
620 std::map<const Type *, const Type *> EqTypes;
621 return TypesEqual(Ty, Ty2, EqTypes);
624 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
625 // TargetTy in the type graph. We know that Ty is an abstract type, so if we
626 // ever reach a non-abstract type, we know that we don't need to search the
628 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
629 std::set<const Type*> &VisitedTypes) {
630 if (TargetTy == CurTy) return true;
631 if (!CurTy->isAbstract()) return false;
633 if (!VisitedTypes.insert(CurTy).second)
634 return false; // Already been here.
636 for (Type::subtype_iterator I = CurTy->subtype_begin(),
637 E = CurTy->subtype_end(); I != E; ++I)
638 if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
643 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
644 std::set<const Type*> &VisitedTypes) {
645 if (TargetTy == CurTy) return true;
647 if (!VisitedTypes.insert(CurTy).second)
648 return false; // Already been here.
650 for (Type::subtype_iterator I = CurTy->subtype_begin(),
651 E = CurTy->subtype_end(); I != E; ++I)
652 if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
657 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
659 static bool TypeHasCycleThroughItself(const Type *Ty) {
660 std::set<const Type*> VisitedTypes;
662 if (Ty->isAbstract()) { // Optimized case for abstract types.
663 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
665 if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
668 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
670 if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
677 //===----------------------------------------------------------------------===//
678 // Derived Type Factory Functions
679 //===----------------------------------------------------------------------===//
681 // TypeMap - Make sure that only one instance of a particular type may be
682 // created on any given run of the compiler... note that this involves updating
683 // our map if an abstract type gets refined somehow.
686 template<class ValType, class TypeClass>
688 std::map<ValType, PATypeHolder> Map;
690 /// TypesByHash - Keep track of types by their structure hash value. Note
691 /// that we only keep track of types that have cycles through themselves in
694 std::multimap<unsigned, PATypeHolder> TypesByHash;
696 friend void Type::clearAllTypeMaps();
699 void clear(std::vector<Type *> &DerivedTypes) {
700 for (typename std::map<ValType, PATypeHolder>::iterator I = Map.begin(),
701 E = Map.end(); I != E; ++I)
702 DerivedTypes.push_back(I->second.get());
707 typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
708 ~TypeMap() { print("ON EXIT"); }
710 inline TypeClass *get(const ValType &V) {
711 iterator I = Map.find(V);
712 return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
715 inline void add(const ValType &V, TypeClass *Ty) {
716 Map.insert(std::make_pair(V, Ty));
718 // If this type has a cycle, remember it.
719 TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
723 void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
724 std::multimap<unsigned, PATypeHolder>::iterator I =
725 TypesByHash.lower_bound(Hash);
726 while (I->second != Ty) {
728 assert(I != TypesByHash.end() && I->first == Hash);
730 TypesByHash.erase(I);
733 /// TypeBecameConcrete - When Ty gets a notification that TheType just became
734 /// concrete, drop uses and make Ty non-abstract if we should.
735 void TypeBecameConcrete(TypeClass *Ty, const DerivedType *TheType) {
736 // If the element just became concrete, remove 'ty' from the abstract
737 // type user list for the type. Do this for as many times as Ty uses
739 for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
740 if (Ty->ContainedTys[i] == TheType)
741 TheType->removeAbstractTypeUser(Ty);
743 // If the type is currently thought to be abstract, rescan all of our
744 // subtypes to see if the type has just become concrete! Note that this
745 // may send out notifications to AbstractTypeUsers that types become
747 if (Ty->isAbstract())
748 Ty->PromoteAbstractToConcrete();
751 /// RefineAbstractType - This method is called after we have merged a type
752 /// with another one. We must now either merge the type away with
753 /// some other type or reinstall it in the map with it's new configuration.
754 void RefineAbstractType(TypeClass *Ty, const DerivedType *OldType,
755 const Type *NewType) {
756 #ifdef DEBUG_MERGE_TYPES
757 std::cerr << "RefineAbstractType(" << (void*)OldType << "[" << *OldType
758 << "], " << (void*)NewType << " [" << *NewType << "])\n";
761 // Otherwise, we are changing one subelement type into another. Clearly the
762 // OldType must have been abstract, making us abstract.
763 assert(Ty->isAbstract() && "Refining a non-abstract type!");
764 assert(OldType != NewType);
766 // Make a temporary type holder for the type so that it doesn't disappear on
767 // us when we erase the entry from the map.
768 PATypeHolder TyHolder = Ty;
770 // The old record is now out-of-date, because one of the children has been
771 // updated. Remove the obsolete entry from the map.
772 unsigned NumErased = Map.erase(ValType::get(Ty));
773 assert(NumErased && "Element not found!");
775 // Remember the structural hash for the type before we start hacking on it,
776 // in case we need it later.
777 unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
779 // Find the type element we are refining... and change it now!
780 for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
781 if (Ty->ContainedTys[i] == OldType)
782 Ty->ContainedTys[i] = NewType;
783 unsigned NewTypeHash = ValType::hashTypeStructure(Ty);
785 // If there are no cycles going through this node, we can do a simple,
786 // efficient lookup in the map, instead of an inefficient nasty linear
788 if (!TypeHasCycleThroughItself(Ty)) {
789 typename std::map<ValType, PATypeHolder>::iterator I;
792 tie(I, Inserted) = Map.insert(std::make_pair(ValType::get(Ty), Ty));
794 assert(OldType != NewType);
795 // Refined to a different type altogether?
796 RemoveFromTypesByHash(OldTypeHash, Ty);
798 // We already have this type in the table. Get rid of the newly refined
800 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
801 Ty->refineAbstractTypeTo(NewTy);
805 // Now we check to see if there is an existing entry in the table which is
806 // structurally identical to the newly refined type. If so, this type
807 // gets refined to the pre-existing type.
809 std::multimap<unsigned, PATypeHolder>::iterator I, E, Entry;
810 tie(I, E) = TypesByHash.equal_range(OldTypeHash);
812 for (; I != E; ++I) {
813 if (I->second == Ty) {
814 // Remember the position of the old type if we see it in our scan.
817 if (TypesEqual(Ty, I->second)) {
818 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
821 // Find the location of Ty in the TypesByHash structure if we
822 // haven't seen it already.
823 while (I->second != Ty) {
825 assert(I != E && "Structure doesn't contain type??");
830 TypesByHash.erase(Entry);
831 Ty->refineAbstractTypeTo(NewTy);
837 // If there is no existing type of the same structure, we reinsert an
838 // updated record into the map.
839 Map.insert(std::make_pair(ValType::get(Ty), Ty));
842 // If the hash codes differ, update TypesByHash
843 if (NewTypeHash != OldTypeHash) {
844 RemoveFromTypesByHash(OldTypeHash, Ty);
845 TypesByHash.insert(std::make_pair(NewTypeHash, Ty));
848 // If the type is currently thought to be abstract, rescan all of our
849 // subtypes to see if the type has just become concrete! Note that this
850 // may send out notifications to AbstractTypeUsers that types become
852 if (Ty->isAbstract())
853 Ty->PromoteAbstractToConcrete();
856 void print(const char *Arg) const {
857 #ifdef DEBUG_MERGE_TYPES
858 std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
860 for (typename std::map<ValType, PATypeHolder>::const_iterator I
861 = Map.begin(), E = Map.end(); I != E; ++I)
862 std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " "
863 << *I->second.get() << "\n";
867 void dump() const { print("dump output"); }
872 //===----------------------------------------------------------------------===//
873 // Function Type Factory and Value Class...
876 // FunctionValType - Define a class to hold the key that goes into the TypeMap
879 class FunctionValType {
881 std::vector<const Type*> ArgTypes;
884 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
885 bool IVA) : RetTy(ret), isVarArg(IVA) {
886 for (unsigned i = 0; i < args.size(); ++i)
887 ArgTypes.push_back(args[i]);
890 static FunctionValType get(const FunctionType *FT);
892 static unsigned hashTypeStructure(const FunctionType *FT) {
893 return FT->getNumParams()*2+FT->isVarArg();
896 // Subclass should override this... to update self as usual
897 void doRefinement(const DerivedType *OldType, const Type *NewType) {
898 if (RetTy == OldType) RetTy = NewType;
899 for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
900 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
903 inline bool operator<(const FunctionValType &MTV) const {
904 if (RetTy < MTV.RetTy) return true;
905 if (RetTy > MTV.RetTy) return false;
907 if (ArgTypes < MTV.ArgTypes) return true;
908 return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
913 // Define the actual map itself now...
914 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
916 FunctionValType FunctionValType::get(const FunctionType *FT) {
917 // Build up a FunctionValType
918 std::vector<const Type *> ParamTypes;
919 ParamTypes.reserve(FT->getNumParams());
920 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
921 ParamTypes.push_back(FT->getParamType(i));
922 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
926 // FunctionType::get - The factory function for the FunctionType class...
927 FunctionType *FunctionType::get(const Type *ReturnType,
928 const std::vector<const Type*> &Params,
930 FunctionValType VT(ReturnType, Params, isVarArg);
931 FunctionType *MT = FunctionTypes.get(VT);
934 FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
936 #ifdef DEBUG_MERGE_TYPES
937 std::cerr << "Derived new type: " << MT << "\n";
942 //===----------------------------------------------------------------------===//
943 // Array Type Factory...
950 ArrayValType(const Type *val, uint64_t sz) : ValTy(val), Size(sz) {}
952 static ArrayValType get(const ArrayType *AT) {
953 return ArrayValType(AT->getElementType(), AT->getNumElements());
956 static unsigned hashTypeStructure(const ArrayType *AT) {
957 return (unsigned)AT->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 ArrayValType &MTV) const {
967 if (Size < MTV.Size) return true;
968 return Size == MTV.Size && ValTy < MTV.ValTy;
972 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
975 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
976 assert(ElementType && "Can't get array of null types!");
978 ArrayValType AVT(ElementType, NumElements);
979 ArrayType *AT = ArrayTypes.get(AVT);
980 if (AT) return AT; // Found a match, return it!
982 // Value not found. Derive a new type!
983 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
985 #ifdef DEBUG_MERGE_TYPES
986 std::cerr << "Derived new type: " << *AT << "\n";
992 //===----------------------------------------------------------------------===//
993 // Packed Type Factory...
996 class PackedValType {
1000 PackedValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
1002 static PackedValType get(const PackedType *PT) {
1003 return PackedValType(PT->getElementType(), PT->getNumElements());
1006 static unsigned hashTypeStructure(const PackedType *PT) {
1007 return PT->getNumElements();
1010 // Subclass should override this... to update self as usual
1011 void doRefinement(const DerivedType *OldType, const Type *NewType) {
1012 assert(ValTy == OldType);
1016 inline bool operator<(const PackedValType &MTV) const {
1017 if (Size < MTV.Size) return true;
1018 return Size == MTV.Size && ValTy < MTV.ValTy;
1022 static TypeMap<PackedValType, PackedType> PackedTypes;
1025 PackedType *PackedType::get(const Type *ElementType, unsigned NumElements) {
1026 assert(ElementType && "Can't get packed of null types!");
1027 assert(isPowerOf2_32(NumElements) && "Vector length should be a power of 2!");
1029 PackedValType PVT(ElementType, NumElements);
1030 PackedType *PT = PackedTypes.get(PVT);
1031 if (PT) return PT; // Found a match, return it!
1033 // Value not found. Derive a new type!
1034 PackedTypes.add(PVT, PT = new PackedType(ElementType, NumElements));
1036 #ifdef DEBUG_MERGE_TYPES
1037 std::cerr << "Derived new type: " << *PT << "\n";
1042 //===----------------------------------------------------------------------===//
1043 // Struct Type Factory...
1047 // StructValType - Define a class to hold the key that goes into the TypeMap
1049 class StructValType {
1050 std::vector<const Type*> ElTypes;
1052 StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
1054 static StructValType get(const StructType *ST) {
1055 std::vector<const Type *> ElTypes;
1056 ElTypes.reserve(ST->getNumElements());
1057 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
1058 ElTypes.push_back(ST->getElementType(i));
1060 return StructValType(ElTypes);
1063 static unsigned hashTypeStructure(const StructType *ST) {
1064 return ST->getNumElements();
1067 // Subclass should override this... to update self as usual
1068 void doRefinement(const DerivedType *OldType, const Type *NewType) {
1069 for (unsigned i = 0; i < ElTypes.size(); ++i)
1070 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
1073 inline bool operator<(const StructValType &STV) const {
1074 return ElTypes < STV.ElTypes;
1079 static TypeMap<StructValType, StructType> StructTypes;
1081 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
1082 StructValType STV(ETypes);
1083 StructType *ST = StructTypes.get(STV);
1086 // Value not found. Derive a new type!
1087 StructTypes.add(STV, ST = new StructType(ETypes));
1089 #ifdef DEBUG_MERGE_TYPES
1090 std::cerr << "Derived new type: " << *ST << "\n";
1097 //===----------------------------------------------------------------------===//
1098 // Pointer Type Factory...
1101 // PointerValType - Define a class to hold the key that goes into the TypeMap
1104 class PointerValType {
1107 PointerValType(const Type *val) : ValTy(val) {}
1109 static PointerValType get(const PointerType *PT) {
1110 return PointerValType(PT->getElementType());
1113 static unsigned hashTypeStructure(const PointerType *PT) {
1117 // Subclass should override this... to update self as usual
1118 void doRefinement(const DerivedType *OldType, const Type *NewType) {
1119 assert(ValTy == OldType);
1123 bool operator<(const PointerValType &MTV) const {
1124 return ValTy < MTV.ValTy;
1129 static TypeMap<PointerValType, PointerType> PointerTypes;
1131 PointerType *PointerType::get(const Type *ValueType) {
1132 assert(ValueType && "Can't get a pointer to <null> type!");
1133 // FIXME: The sparc backend makes void pointers, which is horribly broken.
1134 // "Fix" it, then reenable this assertion.
1135 //assert(ValueType != Type::VoidTy &&
1136 // "Pointer to void is not valid, use sbyte* instead!");
1137 PointerValType PVT(ValueType);
1139 PointerType *PT = PointerTypes.get(PVT);
1142 // Value not found. Derive a new type!
1143 PointerTypes.add(PVT, PT = new PointerType(ValueType));
1145 #ifdef DEBUG_MERGE_TYPES
1146 std::cerr << "Derived new type: " << *PT << "\n";
1152 //===----------------------------------------------------------------------===//
1153 // Derived Type Refinement Functions
1154 //===----------------------------------------------------------------------===//
1156 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1157 // no longer has a handle to the type. This function is called primarily by
1158 // the PATypeHandle class. When there are no users of the abstract type, it
1159 // is annihilated, because there is no way to get a reference to it ever again.
1161 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
1162 // Search from back to front because we will notify users from back to
1163 // front. Also, it is likely that there will be a stack like behavior to
1164 // users that register and unregister users.
1167 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1168 assert(i != 0 && "AbstractTypeUser not in user list!");
1170 --i; // Convert to be in range 0 <= i < size()
1171 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1173 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1175 #ifdef DEBUG_MERGE_TYPES
1176 std::cerr << " remAbstractTypeUser[" << (void*)this << ", "
1177 << *this << "][" << i << "] User = " << U << "\n";
1180 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1181 #ifdef DEBUG_MERGE_TYPES
1182 std::cerr << "DELETEing unused abstract type: <" << *this
1183 << ">[" << (void*)this << "]" << "\n";
1185 delete this; // No users of this abstract type!
1190 // refineAbstractTypeTo - This function is used to when it is discovered that
1191 // the 'this' abstract type is actually equivalent to the NewType specified.
1192 // This causes all users of 'this' to switch to reference the more concrete type
1193 // NewType and for 'this' to be deleted.
1195 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1196 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1197 assert(this != NewType && "Can't refine to myself!");
1198 assert(ForwardType == 0 && "This type has already been refined!");
1200 // The descriptions may be out of date. Conservatively clear them all!
1201 AbstractTypeDescriptions.clear();
1203 #ifdef DEBUG_MERGE_TYPES
1204 std::cerr << "REFINING abstract type [" << (void*)this << " "
1205 << *this << "] to [" << (void*)NewType << " "
1206 << *NewType << "]!\n";
1209 // Make sure to put the type to be refined to into a holder so that if IT gets
1210 // refined, that we will not continue using a dead reference...
1212 PATypeHolder NewTy(NewType);
1214 // Any PATypeHolders referring to this type will now automatically forward to
1215 // the type we are resolved to.
1216 ForwardType = NewType;
1217 if (NewType->isAbstract())
1218 cast<DerivedType>(NewType)->addRef();
1220 // Add a self use of the current type so that we don't delete ourself until
1221 // after the function exits.
1223 PATypeHolder CurrentTy(this);
1225 // To make the situation simpler, we ask the subclass to remove this type from
1226 // the type map, and to replace any type uses with uses of non-abstract types.
1227 // This dramatically limits the amount of recursive type trouble we can find
1231 // Iterate over all of the uses of this type, invoking callback. Each user
1232 // should remove itself from our use list automatically. We have to check to
1233 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1234 // will not cause users to drop off of the use list. If we resolve to ourself
1237 while (!AbstractTypeUsers.empty() && NewTy != this) {
1238 AbstractTypeUser *User = AbstractTypeUsers.back();
1240 unsigned OldSize = AbstractTypeUsers.size();
1241 #ifdef DEBUG_MERGE_TYPES
1242 std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
1243 << "] of abstract type [" << (void*)this << " "
1244 << *this << "] to [" << (void*)NewTy.get() << " "
1245 << *NewTy << "]!\n";
1247 User->refineAbstractType(this, NewTy);
1249 assert(AbstractTypeUsers.size() != OldSize &&
1250 "AbsTyUser did not remove self from user list!");
1253 // If we were successful removing all users from the type, 'this' will be
1254 // deleted when the last PATypeHolder is destroyed or updated from this type.
1255 // This may occur on exit of this function, as the CurrentTy object is
1259 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1260 // the current type has transitioned from being abstract to being concrete.
1262 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1263 #ifdef DEBUG_MERGE_TYPES
1264 std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1267 unsigned OldSize = AbstractTypeUsers.size();
1268 while (!AbstractTypeUsers.empty()) {
1269 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1270 ATU->typeBecameConcrete(this);
1272 assert(AbstractTypeUsers.size() < OldSize-- &&
1273 "AbstractTypeUser did not remove itself from the use list!");
1280 // refineAbstractType - Called when a contained type is found to be more
1281 // concrete - this could potentially change us from an abstract type to a
1284 void FunctionType::refineAbstractType(const DerivedType *OldType,
1285 const Type *NewType) {
1286 FunctionTypes.RefineAbstractType(this, OldType, NewType);
1289 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1290 FunctionTypes.TypeBecameConcrete(this, AbsTy);
1294 // refineAbstractType - Called when a contained type is found to be more
1295 // concrete - this could potentially change us from an abstract type to a
1298 void ArrayType::refineAbstractType(const DerivedType *OldType,
1299 const Type *NewType) {
1300 ArrayTypes.RefineAbstractType(this, OldType, NewType);
1303 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1304 ArrayTypes.TypeBecameConcrete(this, AbsTy);
1307 // refineAbstractType - Called when a contained type is found to be more
1308 // concrete - this could potentially change us from an abstract type to a
1311 void PackedType::refineAbstractType(const DerivedType *OldType,
1312 const Type *NewType) {
1313 PackedTypes.RefineAbstractType(this, OldType, NewType);
1316 void PackedType::typeBecameConcrete(const DerivedType *AbsTy) {
1317 PackedTypes.TypeBecameConcrete(this, AbsTy);
1320 // refineAbstractType - Called when a contained type is found to be more
1321 // concrete - this could potentially change us from an abstract type to a
1324 void StructType::refineAbstractType(const DerivedType *OldType,
1325 const Type *NewType) {
1326 StructTypes.RefineAbstractType(this, OldType, NewType);
1329 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1330 StructTypes.TypeBecameConcrete(this, AbsTy);
1333 // refineAbstractType - Called when a contained type is found to be more
1334 // concrete - this could potentially change us from an abstract type to a
1337 void PointerType::refineAbstractType(const DerivedType *OldType,
1338 const Type *NewType) {
1339 PointerTypes.RefineAbstractType(this, OldType, NewType);
1342 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1343 PointerTypes.TypeBecameConcrete(this, AbsTy);
1346 bool SequentialType::indexValid(const Value *V) const {
1347 const Type *Ty = V->getType();
1348 switch (Ty->getTypeID()) {
1350 case Type::UIntTyID:
1351 case Type::LongTyID:
1352 case Type::ULongTyID:
1360 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1362 OS << "<null> value!\n";
1368 std::ostream &operator<<(std::ostream &OS, const Type &T) {
1374 /// clearAllTypeMaps - This method frees all internal memory used by the
1375 /// type subsystem, which can be used in environments where this memory is
1376 /// otherwise reported as a leak.
1377 void Type::clearAllTypeMaps() {
1378 std::vector<Type *> DerivedTypes;
1380 FunctionTypes.clear(DerivedTypes);
1381 PointerTypes.clear(DerivedTypes);
1382 StructTypes.clear(DerivedTypes);
1383 ArrayTypes.clear(DerivedTypes);
1384 PackedTypes.clear(DerivedTypes);
1386 for(std::vector<Type *>::iterator I = DerivedTypes.begin(),
1387 E = DerivedTypes.end(); I != E; ++I)
1388 (*I)->ContainedTys.clear();
1389 for(std::vector<Type *>::iterator I = DerivedTypes.begin(),
1390 E = DerivedTypes.end(); I != E; ++I)
1392 DerivedTypes.clear();