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 /// finishRefinement - This method is called after we have updated an existing
734 /// type with its new components. We must now either merge the type away with
735 /// some other type or reinstall it in the map with it's new configuration.
736 /// The specified iterator tells us what the type USED to look like.
737 void finishRefinement(TypeClass *Ty, const DerivedType *OldType,
738 const Type *NewType) {
739 #ifdef DEBUG_MERGE_TYPES
740 std::cerr << "refineAbstractTy(" << (void*)OldType << "[" << *OldType
741 << "], " << (void*)NewType << " [" << *NewType << "])\n";
743 // If NewTy == OldTy, then the type just became concrete. In this case, we
744 // don't need to change the current type, we just need to drop uses of the
745 // type and potentially mark Ty as concrete now too.
746 if (OldType == NewType) {
747 // If the element just became concrete, remove 'ty' from the abstract
748 // type user list for the type. Do this for as many times as Ty uses
750 for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
751 if (Ty->ContainedTys[i] == OldType)
752 OldType->removeAbstractTypeUser(Ty);
754 // If the type is currently thought to be abstract, rescan all of our
755 // subtypes to see if the type has just become concrete! Note that this
756 // may send out notifications to AbstractTypeUsers that types become
758 if (Ty->isAbstract())
759 Ty->PromoteAbstractToConcrete();
764 // Otherwise, we are changing one subelement type into another. Clearly the
765 // OldType must have been abstract, making us abstract.
766 assert(Ty->isAbstract() && "Refining a non-abstract type!");
768 // Make a temporary type holder for the type so that it doesn't disappear on
769 // us when we erase the entry from the map.
770 PATypeHolder TyHolder = Ty;
772 // The old record is now out-of-date, because one of the children has been
773 // updated. Remove the obsolete entry from the map.
774 unsigned NumErased = Map.erase(ValType::get(Ty));
775 assert(NumErased && "Element not found!");
777 // Remember the structural hash for the type before we start hacking on it,
778 // in case we need it later.
779 unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
781 // Find the type element we are refining... and change it now!
782 for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
783 if (Ty->ContainedTys[i] == OldType)
784 Ty->ContainedTys[i] = NewType;
785 unsigned NewTypeHash = ValType::hashTypeStructure(Ty);
787 // If there are no cycles going through this node, we can do a simple,
788 // efficient lookup in the map, instead of an inefficient nasty linear
790 if (!TypeHasCycleThroughItself(Ty)) {
791 typename std::map<ValType, PATypeHolder>::iterator I;
794 tie(I, Inserted) = Map.insert(std::make_pair(ValType::get(Ty), Ty));
796 assert(OldType != NewType);
797 // Refined to a different type altogether?
798 RemoveFromTypesByHash(OldTypeHash, Ty);
800 // We already have this type in the table. Get rid of the newly refined
802 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
803 Ty->refineAbstractTypeTo(NewTy);
807 // Now we check to see if there is an existing entry in the table which is
808 // structurally identical to the newly refined type. If so, this type
809 // gets refined to the pre-existing type.
811 std::multimap<unsigned, PATypeHolder>::iterator I, E, Entry;
812 tie(I, E) = TypesByHash.equal_range(OldTypeHash);
814 for (; I != E; ++I) {
815 if (I->second == Ty) {
816 // Remember the position of the old type if we see it in our scan.
819 if (TypesEqual(Ty, I->second)) {
820 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
823 // Find the location of Ty in the TypesByHash structure if we
824 // haven't seen it already.
825 while (I->second != Ty) {
827 assert(I != E && "Structure doesn't contain type??");
832 TypesByHash.erase(Entry);
833 Ty->refineAbstractTypeTo(NewTy);
839 // If there is no existing type of the same structure, we reinsert an
840 // updated record into the map.
841 Map.insert(std::make_pair(ValType::get(Ty), Ty));
844 // If the hash codes differ, update TypesByHash
845 if (NewTypeHash != OldTypeHash) {
846 RemoveFromTypesByHash(OldTypeHash, Ty);
847 TypesByHash.insert(std::make_pair(NewTypeHash, Ty));
850 // If the type is currently thought to be abstract, rescan all of our
851 // subtypes to see if the type has just become concrete! Note that this
852 // may send out notifications to AbstractTypeUsers that types become
854 if (Ty->isAbstract())
855 Ty->PromoteAbstractToConcrete();
858 void print(const char *Arg) const {
859 #ifdef DEBUG_MERGE_TYPES
860 std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
862 for (typename std::map<ValType, PATypeHolder>::const_iterator I
863 = Map.begin(), E = Map.end(); I != E; ++I)
864 std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " "
865 << *I->second.get() << "\n";
869 void dump() const { print("dump output"); }
874 //===----------------------------------------------------------------------===//
875 // Function Type Factory and Value Class...
878 // FunctionValType - Define a class to hold the key that goes into the TypeMap
881 class FunctionValType {
883 std::vector<const Type*> ArgTypes;
886 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
887 bool IVA) : RetTy(ret), isVarArg(IVA) {
888 for (unsigned i = 0; i < args.size(); ++i)
889 ArgTypes.push_back(args[i]);
892 static FunctionValType get(const FunctionType *FT);
894 static unsigned hashTypeStructure(const FunctionType *FT) {
895 return FT->getNumParams()*2+FT->isVarArg();
898 // Subclass should override this... to update self as usual
899 void doRefinement(const DerivedType *OldType, const Type *NewType) {
900 if (RetTy == OldType) RetTy = NewType;
901 for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
902 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
905 inline bool operator<(const FunctionValType &MTV) const {
906 if (RetTy < MTV.RetTy) return true;
907 if (RetTy > MTV.RetTy) return false;
909 if (ArgTypes < MTV.ArgTypes) return true;
910 return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
915 // Define the actual map itself now...
916 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
918 FunctionValType FunctionValType::get(const FunctionType *FT) {
919 // Build up a FunctionValType
920 std::vector<const Type *> ParamTypes;
921 ParamTypes.reserve(FT->getNumParams());
922 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
923 ParamTypes.push_back(FT->getParamType(i));
924 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
928 // FunctionType::get - The factory function for the FunctionType class...
929 FunctionType *FunctionType::get(const Type *ReturnType,
930 const std::vector<const Type*> &Params,
932 FunctionValType VT(ReturnType, Params, isVarArg);
933 FunctionType *MT = FunctionTypes.get(VT);
936 FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
938 #ifdef DEBUG_MERGE_TYPES
939 std::cerr << "Derived new type: " << MT << "\n";
944 //===----------------------------------------------------------------------===//
945 // Array Type Factory...
952 ArrayValType(const Type *val, uint64_t sz) : ValTy(val), Size(sz) {}
954 static ArrayValType get(const ArrayType *AT) {
955 return ArrayValType(AT->getElementType(), AT->getNumElements());
958 static unsigned hashTypeStructure(const ArrayType *AT) {
959 return (unsigned)AT->getNumElements();
962 // Subclass should override this... to update self as usual
963 void doRefinement(const DerivedType *OldType, const Type *NewType) {
964 assert(ValTy == OldType);
968 inline bool operator<(const ArrayValType &MTV) const {
969 if (Size < MTV.Size) return true;
970 return Size == MTV.Size && ValTy < MTV.ValTy;
974 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
977 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
978 assert(ElementType && "Can't get array of null types!");
980 ArrayValType AVT(ElementType, NumElements);
981 ArrayType *AT = ArrayTypes.get(AVT);
982 if (AT) return AT; // Found a match, return it!
984 // Value not found. Derive a new type!
985 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
987 #ifdef DEBUG_MERGE_TYPES
988 std::cerr << "Derived new type: " << *AT << "\n";
994 //===----------------------------------------------------------------------===//
995 // Packed Type Factory...
998 class PackedValType {
1002 PackedValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
1004 static PackedValType get(const PackedType *PT) {
1005 return PackedValType(PT->getElementType(), PT->getNumElements());
1008 static unsigned hashTypeStructure(const PackedType *PT) {
1009 return PT->getNumElements();
1012 // Subclass should override this... to update self as usual
1013 void doRefinement(const DerivedType *OldType, const Type *NewType) {
1014 assert(ValTy == OldType);
1018 inline bool operator<(const PackedValType &MTV) const {
1019 if (Size < MTV.Size) return true;
1020 return Size == MTV.Size && ValTy < MTV.ValTy;
1024 static TypeMap<PackedValType, PackedType> PackedTypes;
1027 PackedType *PackedType::get(const Type *ElementType, unsigned NumElements) {
1028 assert(ElementType && "Can't get packed of null types!");
1029 assert(isPowerOf2_32(NumElements) && "Vector length should be a power of 2!");
1031 PackedValType PVT(ElementType, NumElements);
1032 PackedType *PT = PackedTypes.get(PVT);
1033 if (PT) return PT; // Found a match, return it!
1035 // Value not found. Derive a new type!
1036 PackedTypes.add(PVT, PT = new PackedType(ElementType, NumElements));
1038 #ifdef DEBUG_MERGE_TYPES
1039 std::cerr << "Derived new type: " << *PT << "\n";
1044 //===----------------------------------------------------------------------===//
1045 // Struct Type Factory...
1049 // StructValType - Define a class to hold the key that goes into the TypeMap
1051 class StructValType {
1052 std::vector<const Type*> ElTypes;
1054 StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
1056 static StructValType get(const StructType *ST) {
1057 std::vector<const Type *> ElTypes;
1058 ElTypes.reserve(ST->getNumElements());
1059 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
1060 ElTypes.push_back(ST->getElementType(i));
1062 return StructValType(ElTypes);
1065 static unsigned hashTypeStructure(const StructType *ST) {
1066 return ST->getNumElements();
1069 // Subclass should override this... to update self as usual
1070 void doRefinement(const DerivedType *OldType, const Type *NewType) {
1071 for (unsigned i = 0; i < ElTypes.size(); ++i)
1072 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
1075 inline bool operator<(const StructValType &STV) const {
1076 return ElTypes < STV.ElTypes;
1081 static TypeMap<StructValType, StructType> StructTypes;
1083 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
1084 StructValType STV(ETypes);
1085 StructType *ST = StructTypes.get(STV);
1088 // Value not found. Derive a new type!
1089 StructTypes.add(STV, ST = new StructType(ETypes));
1091 #ifdef DEBUG_MERGE_TYPES
1092 std::cerr << "Derived new type: " << *ST << "\n";
1099 //===----------------------------------------------------------------------===//
1100 // Pointer Type Factory...
1103 // PointerValType - Define a class to hold the key that goes into the TypeMap
1106 class PointerValType {
1109 PointerValType(const Type *val) : ValTy(val) {}
1111 static PointerValType get(const PointerType *PT) {
1112 return PointerValType(PT->getElementType());
1115 static unsigned hashTypeStructure(const PointerType *PT) {
1119 // Subclass should override this... to update self as usual
1120 void doRefinement(const DerivedType *OldType, const Type *NewType) {
1121 assert(ValTy == OldType);
1125 bool operator<(const PointerValType &MTV) const {
1126 return ValTy < MTV.ValTy;
1131 static TypeMap<PointerValType, PointerType> PointerTypes;
1133 PointerType *PointerType::get(const Type *ValueType) {
1134 assert(ValueType && "Can't get a pointer to <null> type!");
1135 // FIXME: The sparc backend makes void pointers, which is horribly broken.
1136 // "Fix" it, then reenable this assertion.
1137 //assert(ValueType != Type::VoidTy &&
1138 // "Pointer to void is not valid, use sbyte* instead!");
1139 PointerValType PVT(ValueType);
1141 PointerType *PT = PointerTypes.get(PVT);
1144 // Value not found. Derive a new type!
1145 PointerTypes.add(PVT, PT = new PointerType(ValueType));
1147 #ifdef DEBUG_MERGE_TYPES
1148 std::cerr << "Derived new type: " << *PT << "\n";
1154 //===----------------------------------------------------------------------===//
1155 // Derived Type Refinement Functions
1156 //===----------------------------------------------------------------------===//
1158 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1159 // no longer has a handle to the type. This function is called primarily by
1160 // the PATypeHandle class. When there are no users of the abstract type, it
1161 // is annihilated, because there is no way to get a reference to it ever again.
1163 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
1164 // Search from back to front because we will notify users from back to
1165 // front. Also, it is likely that there will be a stack like behavior to
1166 // users that register and unregister users.
1169 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1170 assert(i != 0 && "AbstractTypeUser not in user list!");
1172 --i; // Convert to be in range 0 <= i < size()
1173 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1175 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1177 #ifdef DEBUG_MERGE_TYPES
1178 std::cerr << " remAbstractTypeUser[" << (void*)this << ", "
1179 << *this << "][" << i << "] User = " << U << "\n";
1182 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1183 #ifdef DEBUG_MERGE_TYPES
1184 std::cerr << "DELETEing unused abstract type: <" << *this
1185 << ">[" << (void*)this << "]" << "\n";
1187 delete this; // No users of this abstract type!
1192 // refineAbstractTypeTo - This function is used to when it is discovered that
1193 // the 'this' abstract type is actually equivalent to the NewType specified.
1194 // This causes all users of 'this' to switch to reference the more concrete type
1195 // NewType and for 'this' to be deleted.
1197 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1198 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1199 assert(this != NewType && "Can't refine to myself!");
1200 assert(ForwardType == 0 && "This type has already been refined!");
1202 // The descriptions may be out of date. Conservatively clear them all!
1203 AbstractTypeDescriptions.clear();
1205 #ifdef DEBUG_MERGE_TYPES
1206 std::cerr << "REFINING abstract type [" << (void*)this << " "
1207 << *this << "] to [" << (void*)NewType << " "
1208 << *NewType << "]!\n";
1211 // Make sure to put the type to be refined to into a holder so that if IT gets
1212 // refined, that we will not continue using a dead reference...
1214 PATypeHolder NewTy(NewType);
1216 // Any PATypeHolders referring to this type will now automatically forward to
1217 // the type we are resolved to.
1218 ForwardType = NewType;
1219 if (NewType->isAbstract())
1220 cast<DerivedType>(NewType)->addRef();
1222 // Add a self use of the current type so that we don't delete ourself until
1223 // after the function exits.
1225 PATypeHolder CurrentTy(this);
1227 // To make the situation simpler, we ask the subclass to remove this type from
1228 // the type map, and to replace any type uses with uses of non-abstract types.
1229 // This dramatically limits the amount of recursive type trouble we can find
1233 // Iterate over all of the uses of this type, invoking callback. Each user
1234 // should remove itself from our use list automatically. We have to check to
1235 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1236 // will not cause users to drop off of the use list. If we resolve to ourself
1239 while (!AbstractTypeUsers.empty() && NewTy != this) {
1240 AbstractTypeUser *User = AbstractTypeUsers.back();
1242 unsigned OldSize = AbstractTypeUsers.size();
1243 #ifdef DEBUG_MERGE_TYPES
1244 std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
1245 << "] of abstract type [" << (void*)this << " "
1246 << *this << "] to [" << (void*)NewTy.get() << " "
1247 << *NewTy << "]!\n";
1249 User->refineAbstractType(this, NewTy);
1251 assert(AbstractTypeUsers.size() != OldSize &&
1252 "AbsTyUser did not remove self from user list!");
1255 // If we were successful removing all users from the type, 'this' will be
1256 // deleted when the last PATypeHolder is destroyed or updated from this type.
1257 // This may occur on exit of this function, as the CurrentTy object is
1261 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1262 // the current type has transitioned from being abstract to being concrete.
1264 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1265 #ifdef DEBUG_MERGE_TYPES
1266 std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1269 unsigned OldSize = AbstractTypeUsers.size();
1270 while (!AbstractTypeUsers.empty()) {
1271 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1272 ATU->typeBecameConcrete(this);
1274 assert(AbstractTypeUsers.size() < OldSize-- &&
1275 "AbstractTypeUser did not remove itself from the use list!");
1282 // refineAbstractType - Called when a contained type is found to be more
1283 // concrete - this could potentially change us from an abstract type to a
1286 void FunctionType::refineAbstractType(const DerivedType *OldType,
1287 const Type *NewType) {
1288 FunctionTypes.finishRefinement(this, OldType, NewType);
1291 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1292 refineAbstractType(AbsTy, AbsTy);
1296 // refineAbstractType - Called when a contained type is found to be more
1297 // concrete - this could potentially change us from an abstract type to a
1300 void ArrayType::refineAbstractType(const DerivedType *OldType,
1301 const Type *NewType) {
1302 ArrayTypes.finishRefinement(this, OldType, NewType);
1305 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1306 refineAbstractType(AbsTy, AbsTy);
1309 // refineAbstractType - Called when a contained type is found to be more
1310 // concrete - this could potentially change us from an abstract type to a
1313 void PackedType::refineAbstractType(const DerivedType *OldType,
1314 const Type *NewType) {
1315 PackedTypes.finishRefinement(this, OldType, NewType);
1318 void PackedType::typeBecameConcrete(const DerivedType *AbsTy) {
1319 refineAbstractType(AbsTy, AbsTy);
1322 // refineAbstractType - Called when a contained type is found to be more
1323 // concrete - this could potentially change us from an abstract type to a
1326 void StructType::refineAbstractType(const DerivedType *OldType,
1327 const Type *NewType) {
1328 StructTypes.finishRefinement(this, OldType, NewType);
1331 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1332 refineAbstractType(AbsTy, AbsTy);
1335 // refineAbstractType - Called when a contained type is found to be more
1336 // concrete - this could potentially change us from an abstract type to a
1339 void PointerType::refineAbstractType(const DerivedType *OldType,
1340 const Type *NewType) {
1341 PointerTypes.finishRefinement(this, OldType, NewType);
1344 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1345 refineAbstractType(AbsTy, AbsTy);
1348 bool SequentialType::indexValid(const Value *V) const {
1349 const Type *Ty = V->getType();
1350 switch (Ty->getTypeID()) {
1352 case Type::UIntTyID:
1353 case Type::LongTyID:
1354 case Type::ULongTyID:
1362 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1364 OS << "<null> value!\n";
1370 std::ostream &operator<<(std::ostream &OS, const Type &T) {
1376 /// clearAllTypeMaps - This method frees all internal memory used by the
1377 /// type subsystem, which can be used in environments where this memory is
1378 /// otherwise reported as a leak.
1379 void Type::clearAllTypeMaps() {
1380 std::vector<Type *> DerivedTypes;
1382 FunctionTypes.clear(DerivedTypes);
1383 PointerTypes.clear(DerivedTypes);
1384 StructTypes.clear(DerivedTypes);
1385 ArrayTypes.clear(DerivedTypes);
1386 PackedTypes.clear(DerivedTypes);
1388 for(std::vector<Type *>::iterator I = DerivedTypes.begin(),
1389 E = DerivedTypes.end(); I != E; ++I)
1390 (*I)->ContainedTys.clear();
1391 for(std::vector<Type *>::iterator I = DerivedTypes.begin(),
1392 E = DerivedTypes.end(); I != E; ++I)
1394 DerivedTypes.clear();