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()) {
142 case Type::SByteTyID:
143 case Type::UByteTyID: return 1;
144 case Type::UShortTyID:
145 case Type::ShortTyID: return 2;
146 case Type::FloatTyID:
148 case Type::UIntTyID: return 4;
150 case Type::ULongTyID:
151 case Type::DoubleTyID: return 8;
156 unsigned Type::getPrimitiveSizeInBits() const {
157 switch (getTypeID()) {
158 case Type::BoolTyID: return 1;
159 case Type::SByteTyID:
160 case Type::UByteTyID: return 8;
161 case Type::UShortTyID:
162 case Type::ShortTyID: return 16;
163 case Type::FloatTyID:
165 case Type::UIntTyID: return 32;
167 case Type::ULongTyID:
168 case Type::DoubleTyID: return 64;
173 /// isSizedDerivedType - Derived types like structures and arrays are sized
174 /// iff all of the members of the type are sized as well. Since asking for
175 /// their size is relatively uncommon, move this operation out of line.
176 bool Type::isSizedDerivedType() const {
177 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
178 return ATy->getElementType()->isSized();
180 if (const PackedType *PTy = dyn_cast<PackedType>(this))
181 return PTy->getElementType()->isSized();
183 if (!isa<StructType>(this)) return false;
185 // Okay, our struct is sized if all of the elements are...
186 for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
187 if (!(*I)->isSized()) return false;
192 /// getForwardedTypeInternal - This method is used to implement the union-find
193 /// algorithm for when a type is being forwarded to another type.
194 const Type *Type::getForwardedTypeInternal() const {
195 assert(ForwardType && "This type is not being forwarded to another type!");
197 // Check to see if the forwarded type has been forwarded on. If so, collapse
198 // the forwarding links.
199 const Type *RealForwardedType = ForwardType->getForwardedType();
200 if (!RealForwardedType)
201 return ForwardType; // No it's not forwarded again
203 // Yes, it is forwarded again. First thing, add the reference to the new
205 if (RealForwardedType->isAbstract())
206 cast<DerivedType>(RealForwardedType)->addRef();
208 // Now drop the old reference. This could cause ForwardType to get deleted.
209 cast<DerivedType>(ForwardType)->dropRef();
211 // Return the updated type.
212 ForwardType = RealForwardedType;
216 // getTypeDescription - This is a recursive function that walks a type hierarchy
217 // calculating the description for a type.
219 static std::string getTypeDescription(const Type *Ty,
220 std::vector<const Type *> &TypeStack) {
221 if (isa<OpaqueType>(Ty)) { // Base case for the recursion
222 std::map<const Type*, std::string>::iterator I =
223 AbstractTypeDescriptions.lower_bound(Ty);
224 if (I != AbstractTypeDescriptions.end() && I->first == Ty)
226 std::string Desc = "opaque";
227 AbstractTypeDescriptions.insert(std::make_pair(Ty, Desc));
231 if (!Ty->isAbstract()) { // Base case for the recursion
232 std::map<const Type*, std::string>::iterator I =
233 ConcreteTypeDescriptions.find(Ty);
234 if (I != ConcreteTypeDescriptions.end()) return I->second;
237 // Check to see if the Type is already on the stack...
238 unsigned Slot = 0, CurSize = TypeStack.size();
239 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
241 // This is another base case for the recursion. In this case, we know
242 // that we have looped back to a type that we have previously visited.
243 // Generate the appropriate upreference to handle this.
246 return "\\" + utostr(CurSize-Slot); // Here's the upreference
248 // Recursive case: derived types...
250 TypeStack.push_back(Ty); // Add us to the stack..
252 switch (Ty->getTypeID()) {
253 case Type::FunctionTyID: {
254 const FunctionType *FTy = cast<FunctionType>(Ty);
255 Result = getTypeDescription(FTy->getReturnType(), TypeStack) + " (";
256 for (FunctionType::param_iterator I = FTy->param_begin(),
257 E = FTy->param_end(); I != E; ++I) {
258 if (I != FTy->param_begin())
260 Result += getTypeDescription(*I, TypeStack);
262 if (FTy->isVarArg()) {
263 if (FTy->getNumParams()) Result += ", ";
269 case Type::StructTyID: {
270 const StructType *STy = cast<StructType>(Ty);
272 for (StructType::element_iterator I = STy->element_begin(),
273 E = STy->element_end(); I != E; ++I) {
274 if (I != STy->element_begin())
276 Result += getTypeDescription(*I, TypeStack);
281 case Type::PointerTyID: {
282 const PointerType *PTy = cast<PointerType>(Ty);
283 Result = getTypeDescription(PTy->getElementType(), TypeStack) + " *";
286 case Type::ArrayTyID: {
287 const ArrayType *ATy = cast<ArrayType>(Ty);
288 unsigned NumElements = ATy->getNumElements();
290 Result += utostr(NumElements) + " x ";
291 Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
294 case Type::PackedTyID: {
295 const PackedType *PTy = cast<PackedType>(Ty);
296 unsigned NumElements = PTy->getNumElements();
298 Result += utostr(NumElements) + " x ";
299 Result += getTypeDescription(PTy->getElementType(), TypeStack) + ">";
304 assert(0 && "Unhandled type in getTypeDescription!");
307 TypeStack.pop_back(); // Remove self from stack...
314 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
316 std::map<const Type*, std::string>::iterator I = Map.find(Ty);
317 if (I != Map.end()) return I->second;
319 std::vector<const Type *> TypeStack;
320 std::string Result = getTypeDescription(Ty, TypeStack);
321 return Map[Ty] = Result;
325 const std::string &Type::getDescription() const {
327 return getOrCreateDesc(AbstractTypeDescriptions, this);
329 return getOrCreateDesc(ConcreteTypeDescriptions, this);
333 bool StructType::indexValid(const Value *V) const {
334 // Structure indexes require unsigned integer constants.
335 if (V->getType() == Type::UIntTy)
336 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(V))
337 return CU->getValue() < ContainedTys.size();
341 // getTypeAtIndex - Given an index value into the type, return the type of the
342 // element. For a structure type, this must be a constant value...
344 const Type *StructType::getTypeAtIndex(const Value *V) const {
345 assert(indexValid(V) && "Invalid structure index!");
346 unsigned Idx = (unsigned)cast<ConstantUInt>(V)->getValue();
347 return ContainedTys[Idx];
351 //===----------------------------------------------------------------------===//
352 // Static 'Type' data
353 //===----------------------------------------------------------------------===//
356 struct PrimType : public Type {
357 PrimType(const char *S, TypeID ID) : Type(S, ID) {}
361 static PrimType TheVoidTy ("void" , Type::VoidTyID);
362 static PrimType TheBoolTy ("bool" , Type::BoolTyID);
363 static PrimType TheSByteTy ("sbyte" , Type::SByteTyID);
364 static PrimType TheUByteTy ("ubyte" , Type::UByteTyID);
365 static PrimType TheShortTy ("short" , Type::ShortTyID);
366 static PrimType TheUShortTy("ushort", Type::UShortTyID);
367 static PrimType TheIntTy ("int" , Type::IntTyID);
368 static PrimType TheUIntTy ("uint" , Type::UIntTyID);
369 static PrimType TheLongTy ("long" , Type::LongTyID);
370 static PrimType TheULongTy ("ulong" , Type::ULongTyID);
371 static PrimType TheFloatTy ("float" , Type::FloatTyID);
372 static PrimType TheDoubleTy("double", Type::DoubleTyID);
373 static PrimType TheLabelTy ("label" , Type::LabelTyID);
375 Type *Type::VoidTy = &TheVoidTy;
376 Type *Type::BoolTy = &TheBoolTy;
377 Type *Type::SByteTy = &TheSByteTy;
378 Type *Type::UByteTy = &TheUByteTy;
379 Type *Type::ShortTy = &TheShortTy;
380 Type *Type::UShortTy = &TheUShortTy;
381 Type *Type::IntTy = &TheIntTy;
382 Type *Type::UIntTy = &TheUIntTy;
383 Type *Type::LongTy = &TheLongTy;
384 Type *Type::ULongTy = &TheULongTy;
385 Type *Type::FloatTy = &TheFloatTy;
386 Type *Type::DoubleTy = &TheDoubleTy;
387 Type *Type::LabelTy = &TheLabelTy;
390 //===----------------------------------------------------------------------===//
391 // Derived Type Constructors
392 //===----------------------------------------------------------------------===//
394 FunctionType::FunctionType(const Type *Result,
395 const std::vector<const Type*> &Params,
396 bool IsVarArgs) : DerivedType(FunctionTyID),
397 isVarArgs(IsVarArgs) {
398 assert((Result->isFirstClassType() || Result == Type::VoidTy ||
399 isa<OpaqueType>(Result)) &&
400 "LLVM functions cannot return aggregates");
401 bool isAbstract = Result->isAbstract();
402 ContainedTys.reserve(Params.size()+1);
403 ContainedTys.push_back(PATypeHandle(Result, this));
405 for (unsigned i = 0; i != Params.size(); ++i) {
406 assert((Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])) &&
407 "Function arguments must be value types!");
409 ContainedTys.push_back(PATypeHandle(Params[i], this));
410 isAbstract |= Params[i]->isAbstract();
413 // Calculate whether or not this type is abstract
414 setAbstract(isAbstract);
417 StructType::StructType(const std::vector<const Type*> &Types)
418 : CompositeType(StructTyID) {
419 ContainedTys.reserve(Types.size());
420 bool isAbstract = false;
421 for (unsigned i = 0; i < Types.size(); ++i) {
422 assert(Types[i] != Type::VoidTy && "Void type for structure field!!");
423 ContainedTys.push_back(PATypeHandle(Types[i], this));
424 isAbstract |= Types[i]->isAbstract();
427 // Calculate whether or not this type is abstract
428 setAbstract(isAbstract);
431 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
432 : SequentialType(ArrayTyID, ElType) {
435 // Calculate whether or not this type is abstract
436 setAbstract(ElType->isAbstract());
439 PackedType::PackedType(const Type *ElType, unsigned NumEl)
440 : SequentialType(PackedTyID, ElType) {
443 assert(NumEl > 0 && "NumEl of a PackedType must be greater than 0");
444 assert((ElType->isIntegral() || ElType->isFloatingPoint()) &&
445 "Elements of a PackedType must be a primitive type");
449 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
450 // Calculate whether or not this type is abstract
451 setAbstract(E->isAbstract());
454 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
456 #ifdef DEBUG_MERGE_TYPES
457 std::cerr << "Derived new type: " << *this << "\n";
461 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
462 // another (more concrete) type, we must eliminate all references to other
463 // types, to avoid some circular reference problems.
464 void DerivedType::dropAllTypeUses() {
465 if (!ContainedTys.empty()) {
466 while (ContainedTys.size() > 1)
467 ContainedTys.pop_back();
469 // The type must stay abstract. To do this, we insert a pointer to a type
470 // that will never get resolved, thus will always be abstract.
471 static Type *AlwaysOpaqueTy = OpaqueType::get();
472 static PATypeHolder Holder(AlwaysOpaqueTy);
473 ContainedTys[0] = AlwaysOpaqueTy;
479 /// TypePromotionGraph and graph traits - this is designed to allow us to do
480 /// efficient SCC processing of type graphs. This is the exact same as
481 /// GraphTraits<Type*>, except that we pretend that concrete types have no
482 /// children to avoid processing them.
483 struct TypePromotionGraph {
485 TypePromotionGraph(Type *T) : Ty(T) {}
489 template <> struct GraphTraits<TypePromotionGraph> {
490 typedef Type NodeType;
491 typedef Type::subtype_iterator ChildIteratorType;
493 static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
494 static inline ChildIteratorType child_begin(NodeType *N) {
496 return N->subtype_begin();
497 else // No need to process children of concrete types.
498 return N->subtype_end();
500 static inline ChildIteratorType child_end(NodeType *N) {
501 return N->subtype_end();
507 // PromoteAbstractToConcrete - This is a recursive function that walks a type
508 // graph calculating whether or not a type is abstract.
510 void Type::PromoteAbstractToConcrete() {
511 if (!isAbstract()) return;
513 scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
514 scc_iterator<TypePromotionGraph> SE = scc_end (TypePromotionGraph(this));
516 for (; SI != SE; ++SI) {
517 std::vector<Type*> &SCC = *SI;
519 // Concrete types are leaves in the tree. Since an SCC will either be all
520 // abstract or all concrete, we only need to check one type.
521 if (SCC[0]->isAbstract()) {
522 if (isa<OpaqueType>(SCC[0]))
523 return; // Not going to be concrete, sorry.
525 // If all of the children of all of the types in this SCC are concrete,
526 // then this SCC is now concrete as well. If not, neither this SCC, nor
527 // any parent SCCs will be concrete, so we might as well just exit.
528 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
529 for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
530 E = SCC[i]->subtype_end(); CI != E; ++CI)
531 if ((*CI)->isAbstract())
532 // If the child type is in our SCC, it doesn't make the entire SCC
533 // abstract unless there is a non-SCC abstract type.
534 if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
535 return; // Not going to be concrete, sorry.
537 // Okay, we just discovered this whole SCC is now concrete, mark it as
539 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
540 assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
542 SCC[i]->setAbstract(false);
545 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
546 assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
547 // The type just became concrete, notify all users!
548 cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
555 //===----------------------------------------------------------------------===//
556 // Type Structural Equality Testing
557 //===----------------------------------------------------------------------===//
559 // TypesEqual - Two types are considered structurally equal if they have the
560 // same "shape": Every level and element of the types have identical primitive
561 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
562 // be pointer equals to be equivalent though. This uses an optimistic algorithm
563 // that assumes that two graphs are the same until proven otherwise.
565 static bool TypesEqual(const Type *Ty, const Type *Ty2,
566 std::map<const Type *, const Type *> &EqTypes) {
567 if (Ty == Ty2) return true;
568 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
569 if (isa<OpaqueType>(Ty))
570 return false; // Two unequal opaque types are never equal
572 std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
573 if (It != EqTypes.end() && It->first == Ty)
574 return It->second == Ty2; // Looping back on a type, check for equality
576 // Otherwise, add the mapping to the table to make sure we don't get
577 // recursion on the types...
578 EqTypes.insert(It, std::make_pair(Ty, Ty2));
580 // Two really annoying special cases that breaks an otherwise nice simple
581 // algorithm is the fact that arraytypes have sizes that differentiates types,
582 // and that function types can be varargs or not. Consider this now.
584 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
585 return TypesEqual(PTy->getElementType(),
586 cast<PointerType>(Ty2)->getElementType(), EqTypes);
587 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
588 const StructType *STy2 = cast<StructType>(Ty2);
589 if (STy->getNumElements() != STy2->getNumElements()) return false;
590 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
591 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
594 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
595 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
596 return ATy->getNumElements() == ATy2->getNumElements() &&
597 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
598 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
599 const PackedType *PTy2 = cast<PackedType>(Ty2);
600 return PTy->getNumElements() == PTy2->getNumElements() &&
601 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
602 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
603 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
604 if (FTy->isVarArg() != FTy2->isVarArg() ||
605 FTy->getNumParams() != FTy2->getNumParams() ||
606 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
608 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i)
609 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
613 assert(0 && "Unknown derived type!");
618 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
619 std::map<const Type *, const Type *> EqTypes;
620 return TypesEqual(Ty, Ty2, EqTypes);
623 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
624 // TargetTy in the type graph. We know that Ty is an abstract type, so if we
625 // ever reach a non-abstract type, we know that we don't need to search the
627 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
628 std::set<const Type*> &VisitedTypes) {
629 if (TargetTy == CurTy) return true;
630 if (!CurTy->isAbstract()) return false;
632 if (!VisitedTypes.insert(CurTy).second)
633 return false; // Already been here.
635 for (Type::subtype_iterator I = CurTy->subtype_begin(),
636 E = CurTy->subtype_end(); I != E; ++I)
637 if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
642 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
643 std::set<const Type*> &VisitedTypes) {
644 if (TargetTy == CurTy) return true;
646 if (!VisitedTypes.insert(CurTy).second)
647 return false; // Already been here.
649 for (Type::subtype_iterator I = CurTy->subtype_begin(),
650 E = CurTy->subtype_end(); I != E; ++I)
651 if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
656 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
658 static bool TypeHasCycleThroughItself(const Type *Ty) {
659 std::set<const Type*> VisitedTypes;
661 if (Ty->isAbstract()) { // Optimized case for abstract types.
662 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
664 if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
667 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
669 if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
676 //===----------------------------------------------------------------------===//
677 // Derived Type Factory Functions
678 //===----------------------------------------------------------------------===//
680 // TypeMap - Make sure that only one instance of a particular type may be
681 // created on any given run of the compiler... note that this involves updating
682 // our map if an abstract type gets refined somehow.
685 template<class ValType, class TypeClass>
687 std::map<ValType, PATypeHolder> Map;
689 /// TypesByHash - Keep track of types by their structure hash value. Note
690 /// that we only keep track of types that have cycles through themselves in
693 std::multimap<unsigned, PATypeHolder> TypesByHash;
695 friend void Type::clearAllTypeMaps();
698 void clear(std::vector<Type *> &DerivedTypes) {
699 for (typename std::map<ValType, PATypeHolder>::iterator I = Map.begin(),
700 E = Map.end(); I != E; ++I)
701 DerivedTypes.push_back(I->second.get());
706 typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
707 ~TypeMap() { print("ON EXIT"); }
709 inline TypeClass *get(const ValType &V) {
710 iterator I = Map.find(V);
711 return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
714 inline void add(const ValType &V, TypeClass *Ty) {
715 Map.insert(std::make_pair(V, Ty));
717 // If this type has a cycle, remember it.
718 TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
722 void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
723 std::multimap<unsigned, PATypeHolder>::iterator I =
724 TypesByHash.lower_bound(Hash);
725 while (I->second != Ty) {
727 assert(I != TypesByHash.end() && I->first == Hash);
729 TypesByHash.erase(I);
732 /// finishRefinement - This method is called after we have updated an existing
733 /// type with its new components. We must now either merge the type away with
734 /// some other type or reinstall it in the map with it's new configuration.
735 /// The specified iterator tells us what the type USED to look like.
736 void finishRefinement(TypeClass *Ty, const DerivedType *OldType,
737 const Type *NewType) {
738 assert((Ty->isAbstract() || !OldType->isAbstract()) &&
739 "Refining a non-abstract type!");
740 #ifdef DEBUG_MERGE_TYPES
741 std::cerr << "refineAbstractTy(" << (void*)OldType << "[" << *OldType
742 << "], " << (void*)NewType << " [" << *NewType << "])\n";
745 // Make a temporary type holder for the type so that it doesn't disappear on
746 // us when we erase the entry from the map.
747 PATypeHolder TyHolder = Ty;
749 // The old record is now out-of-date, because one of the children has been
750 // updated. Remove the obsolete entry from the map.
751 Map.erase(ValType::get(Ty));
753 // Remember the structural hash for the type before we start hacking on it,
754 // in case we need it later.
755 unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
757 // Find the type element we are refining... and change it now!
758 for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
759 if (Ty->ContainedTys[i] == OldType) {
760 Ty->ContainedTys[i].removeUserFromConcrete();
761 Ty->ContainedTys[i] = NewType;
764 unsigned TypeHash = ValType::hashTypeStructure(Ty);
766 // If there are no cycles going through this node, we can do a simple,
767 // efficient lookup in the map, instead of an inefficient nasty linear
769 if (!Ty->isAbstract() || !TypeHasCycleThroughItself(Ty)) {
770 typename std::map<ValType, PATypeHolder>::iterator I;
773 ValType V = ValType::get(Ty);
774 tie(I, Inserted) = Map.insert(std::make_pair(V, Ty));
776 // Refined to a different type altogether?
777 RemoveFromTypesByHash(TypeHash, Ty);
779 // We already have this type in the table. Get rid of the newly refined
781 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
782 Ty->refineAbstractTypeTo(NewTy);
787 // Now we check to see if there is an existing entry in the table which is
788 // structurally identical to the newly refined type. If so, this type
789 // gets refined to the pre-existing type.
791 std::multimap<unsigned, PATypeHolder>::iterator I, E, Entry;
792 tie(I, E) = TypesByHash.equal_range(OldTypeHash);
794 for (; I != E; ++I) {
795 if (I->second != Ty) {
796 if (TypesEqual(Ty, I->second)) {
797 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
798 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
801 // Find the location of Ty in the TypesByHash structure.
802 while (I->second != Ty) {
804 assert(I != E && "Structure doesn't contain type??");
809 TypesByHash.erase(Entry);
810 Ty->refineAbstractTypeTo(NewTy);
814 // Remember the position of
820 // If there is no existing type of the same structure, we reinsert an
821 // updated record into the map.
822 Map.insert(std::make_pair(ValType::get(Ty), Ty));
825 // If the hash codes differ, update TypesByHash
826 if (TypeHash != OldTypeHash) {
827 RemoveFromTypesByHash(OldTypeHash, Ty);
828 TypesByHash.insert(std::make_pair(TypeHash, Ty));
831 // If the type is currently thought to be abstract, rescan all of our
832 // subtypes to see if the type has just become concrete!
833 if (Ty->isAbstract())
834 Ty->PromoteAbstractToConcrete();
837 void print(const char *Arg) const {
838 #ifdef DEBUG_MERGE_TYPES
839 std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
841 for (typename std::map<ValType, PATypeHolder>::const_iterator I
842 = Map.begin(), E = Map.end(); I != E; ++I)
843 std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " "
844 << *I->second.get() << "\n";
848 void dump() const { print("dump output"); }
853 //===----------------------------------------------------------------------===//
854 // Function Type Factory and Value Class...
857 // FunctionValType - Define a class to hold the key that goes into the TypeMap
860 class FunctionValType {
862 std::vector<const Type*> ArgTypes;
865 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
866 bool IVA) : RetTy(ret), isVarArg(IVA) {
867 for (unsigned i = 0; i < args.size(); ++i)
868 ArgTypes.push_back(args[i]);
871 static FunctionValType get(const FunctionType *FT);
873 static unsigned hashTypeStructure(const FunctionType *FT) {
874 return FT->getNumParams()*2+FT->isVarArg();
877 // Subclass should override this... to update self as usual
878 void doRefinement(const DerivedType *OldType, const Type *NewType) {
879 if (RetTy == OldType) RetTy = NewType;
880 for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
881 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
884 inline bool operator<(const FunctionValType &MTV) const {
885 if (RetTy < MTV.RetTy) return true;
886 if (RetTy > MTV.RetTy) return false;
888 if (ArgTypes < MTV.ArgTypes) return true;
889 return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
894 // Define the actual map itself now...
895 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
897 FunctionValType FunctionValType::get(const FunctionType *FT) {
898 // Build up a FunctionValType
899 std::vector<const Type *> ParamTypes;
900 ParamTypes.reserve(FT->getNumParams());
901 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
902 ParamTypes.push_back(FT->getParamType(i));
903 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
907 // FunctionType::get - The factory function for the FunctionType class...
908 FunctionType *FunctionType::get(const Type *ReturnType,
909 const std::vector<const Type*> &Params,
911 FunctionValType VT(ReturnType, Params, isVarArg);
912 FunctionType *MT = FunctionTypes.get(VT);
915 FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
917 #ifdef DEBUG_MERGE_TYPES
918 std::cerr << "Derived new type: " << MT << "\n";
923 //===----------------------------------------------------------------------===//
924 // Array Type Factory...
931 ArrayValType(const Type *val, uint64_t sz) : ValTy(val), Size(sz) {}
933 static ArrayValType get(const ArrayType *AT) {
934 return ArrayValType(AT->getElementType(), AT->getNumElements());
937 static unsigned hashTypeStructure(const ArrayType *AT) {
938 return (unsigned)AT->getNumElements();
941 // Subclass should override this... to update self as usual
942 void doRefinement(const DerivedType *OldType, const Type *NewType) {
943 assert(ValTy == OldType);
947 inline bool operator<(const ArrayValType &MTV) const {
948 if (Size < MTV.Size) return true;
949 return Size == MTV.Size && ValTy < MTV.ValTy;
953 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
956 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
957 assert(ElementType && "Can't get array of null types!");
959 ArrayValType AVT(ElementType, NumElements);
960 ArrayType *AT = ArrayTypes.get(AVT);
961 if (AT) return AT; // Found a match, return it!
963 // Value not found. Derive a new type!
964 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
966 #ifdef DEBUG_MERGE_TYPES
967 std::cerr << "Derived new type: " << *AT << "\n";
973 //===----------------------------------------------------------------------===//
974 // Packed Type Factory...
977 class PackedValType {
981 PackedValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
983 static PackedValType get(const PackedType *PT) {
984 return PackedValType(PT->getElementType(), PT->getNumElements());
987 static unsigned hashTypeStructure(const PackedType *PT) {
988 return PT->getNumElements();
991 // Subclass should override this... to update self as usual
992 void doRefinement(const DerivedType *OldType, const Type *NewType) {
993 assert(ValTy == OldType);
997 inline bool operator<(const PackedValType &MTV) const {
998 if (Size < MTV.Size) return true;
999 return Size == MTV.Size && ValTy < MTV.ValTy;
1003 static TypeMap<PackedValType, PackedType> PackedTypes;
1006 PackedType *PackedType::get(const Type *ElementType, unsigned NumElements) {
1007 assert(ElementType && "Can't get packed of null types!");
1009 PackedValType PVT(ElementType, NumElements);
1010 PackedType *PT = PackedTypes.get(PVT);
1011 if (PT) return PT; // Found a match, return it!
1013 // Value not found. Derive a new type!
1014 PackedTypes.add(PVT, PT = new PackedType(ElementType, NumElements));
1016 #ifdef DEBUG_MERGE_TYPES
1017 std::cerr << "Derived new type: " << *PT << "\n";
1022 //===----------------------------------------------------------------------===//
1023 // Struct Type Factory...
1027 // StructValType - Define a class to hold the key that goes into the TypeMap
1029 class StructValType {
1030 std::vector<const Type*> ElTypes;
1032 StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
1034 static StructValType get(const StructType *ST) {
1035 std::vector<const Type *> ElTypes;
1036 ElTypes.reserve(ST->getNumElements());
1037 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
1038 ElTypes.push_back(ST->getElementType(i));
1040 return StructValType(ElTypes);
1043 static unsigned hashTypeStructure(const StructType *ST) {
1044 return ST->getNumElements();
1047 // Subclass should override this... to update self as usual
1048 void doRefinement(const DerivedType *OldType, const Type *NewType) {
1049 for (unsigned i = 0; i < ElTypes.size(); ++i)
1050 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
1053 inline bool operator<(const StructValType &STV) const {
1054 return ElTypes < STV.ElTypes;
1059 static TypeMap<StructValType, StructType> StructTypes;
1061 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
1062 StructValType STV(ETypes);
1063 StructType *ST = StructTypes.get(STV);
1066 // Value not found. Derive a new type!
1067 StructTypes.add(STV, ST = new StructType(ETypes));
1069 #ifdef DEBUG_MERGE_TYPES
1070 std::cerr << "Derived new type: " << *ST << "\n";
1077 //===----------------------------------------------------------------------===//
1078 // Pointer Type Factory...
1081 // PointerValType - Define a class to hold the key that goes into the TypeMap
1084 class PointerValType {
1087 PointerValType(const Type *val) : ValTy(val) {}
1089 static PointerValType get(const PointerType *PT) {
1090 return PointerValType(PT->getElementType());
1093 static unsigned hashTypeStructure(const PointerType *PT) {
1097 // Subclass should override this... to update self as usual
1098 void doRefinement(const DerivedType *OldType, const Type *NewType) {
1099 assert(ValTy == OldType);
1103 bool operator<(const PointerValType &MTV) const {
1104 return ValTy < MTV.ValTy;
1109 static TypeMap<PointerValType, PointerType> PointerTypes;
1111 PointerType *PointerType::get(const Type *ValueType) {
1112 assert(ValueType && "Can't get a pointer to <null> type!");
1113 // FIXME: The sparc backend makes void pointers, which is horribly broken.
1114 // "Fix" it, then reenable this assertion.
1115 //assert(ValueType != Type::VoidTy &&
1116 // "Pointer to void is not valid, use sbyte* instead!");
1117 PointerValType PVT(ValueType);
1119 PointerType *PT = PointerTypes.get(PVT);
1122 // Value not found. Derive a new type!
1123 PointerTypes.add(PVT, PT = new PointerType(ValueType));
1125 #ifdef DEBUG_MERGE_TYPES
1126 std::cerr << "Derived new type: " << *PT << "\n";
1132 //===----------------------------------------------------------------------===//
1133 // Derived Type Refinement Functions
1134 //===----------------------------------------------------------------------===//
1136 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1137 // no longer has a handle to the type. This function is called primarily by
1138 // the PATypeHandle class. When there are no users of the abstract type, it
1139 // is annihilated, because there is no way to get a reference to it ever again.
1141 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
1142 // Search from back to front because we will notify users from back to
1143 // front. Also, it is likely that there will be a stack like behavior to
1144 // users that register and unregister users.
1147 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1148 assert(i != 0 && "AbstractTypeUser not in user list!");
1150 --i; // Convert to be in range 0 <= i < size()
1151 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1153 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1155 #ifdef DEBUG_MERGE_TYPES
1156 std::cerr << " remAbstractTypeUser[" << (void*)this << ", "
1157 << *this << "][" << i << "] User = " << U << "\n";
1160 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1161 #ifdef DEBUG_MERGE_TYPES
1162 std::cerr << "DELETEing unused abstract type: <" << *this
1163 << ">[" << (void*)this << "]" << "\n";
1165 delete this; // No users of this abstract type!
1170 // refineAbstractTypeTo - This function is used to when it is discovered that
1171 // the 'this' abstract type is actually equivalent to the NewType specified.
1172 // This causes all users of 'this' to switch to reference the more concrete type
1173 // NewType and for 'this' to be deleted.
1175 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1176 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1177 assert(this != NewType && "Can't refine to myself!");
1178 assert(ForwardType == 0 && "This type has already been refined!");
1180 // The descriptions may be out of date. Conservatively clear them all!
1181 AbstractTypeDescriptions.clear();
1183 #ifdef DEBUG_MERGE_TYPES
1184 std::cerr << "REFINING abstract type [" << (void*)this << " "
1185 << *this << "] to [" << (void*)NewType << " "
1186 << *NewType << "]!\n";
1189 // Make sure to put the type to be refined to into a holder so that if IT gets
1190 // refined, that we will not continue using a dead reference...
1192 PATypeHolder NewTy(NewType);
1194 // Any PATypeHolders referring to this type will now automatically forward to
1195 // the type we are resolved to.
1196 ForwardType = NewType;
1197 if (NewType->isAbstract())
1198 cast<DerivedType>(NewType)->addRef();
1200 // Add a self use of the current type so that we don't delete ourself until
1201 // after the function exits.
1203 PATypeHolder CurrentTy(this);
1205 // To make the situation simpler, we ask the subclass to remove this type from
1206 // the type map, and to replace any type uses with uses of non-abstract types.
1207 // This dramatically limits the amount of recursive type trouble we can find
1211 // Iterate over all of the uses of this type, invoking callback. Each user
1212 // should remove itself from our use list automatically. We have to check to
1213 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1214 // will not cause users to drop off of the use list. If we resolve to ourself
1217 while (!AbstractTypeUsers.empty() && NewTy != this) {
1218 AbstractTypeUser *User = AbstractTypeUsers.back();
1220 unsigned OldSize = AbstractTypeUsers.size();
1221 #ifdef DEBUG_MERGE_TYPES
1222 std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
1223 << "] of abstract type [" << (void*)this << " "
1224 << *this << "] to [" << (void*)NewTy.get() << " "
1225 << *NewTy << "]!\n";
1227 User->refineAbstractType(this, NewTy);
1229 assert(AbstractTypeUsers.size() != OldSize &&
1230 "AbsTyUser did not remove self from user list!");
1233 // If we were successful removing all users from the type, 'this' will be
1234 // deleted when the last PATypeHolder is destroyed or updated from this type.
1235 // This may occur on exit of this function, as the CurrentTy object is
1239 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1240 // the current type has transitioned from being abstract to being concrete.
1242 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1243 #ifdef DEBUG_MERGE_TYPES
1244 std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1247 unsigned OldSize = AbstractTypeUsers.size();
1248 while (!AbstractTypeUsers.empty()) {
1249 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1250 ATU->typeBecameConcrete(this);
1252 assert(AbstractTypeUsers.size() < OldSize-- &&
1253 "AbstractTypeUser did not remove itself from the use list!");
1260 // refineAbstractType - Called when a contained type is found to be more
1261 // concrete - this could potentially change us from an abstract type to a
1264 void FunctionType::refineAbstractType(const DerivedType *OldType,
1265 const Type *NewType) {
1266 FunctionTypes.finishRefinement(this, OldType, NewType);
1269 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1270 refineAbstractType(AbsTy, AbsTy);
1274 // refineAbstractType - Called when a contained type is found to be more
1275 // concrete - this could potentially change us from an abstract type to a
1278 void ArrayType::refineAbstractType(const DerivedType *OldType,
1279 const Type *NewType) {
1280 ArrayTypes.finishRefinement(this, OldType, NewType);
1283 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1284 refineAbstractType(AbsTy, AbsTy);
1287 // refineAbstractType - Called when a contained type is found to be more
1288 // concrete - this could potentially change us from an abstract type to a
1291 void PackedType::refineAbstractType(const DerivedType *OldType,
1292 const Type *NewType) {
1293 PackedTypes.finishRefinement(this, OldType, NewType);
1296 void PackedType::typeBecameConcrete(const DerivedType *AbsTy) {
1297 refineAbstractType(AbsTy, AbsTy);
1300 // refineAbstractType - Called when a contained type is found to be more
1301 // concrete - this could potentially change us from an abstract type to a
1304 void StructType::refineAbstractType(const DerivedType *OldType,
1305 const Type *NewType) {
1306 StructTypes.finishRefinement(this, OldType, NewType);
1309 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1310 refineAbstractType(AbsTy, AbsTy);
1313 // refineAbstractType - Called when a contained type is found to be more
1314 // concrete - this could potentially change us from an abstract type to a
1317 void PointerType::refineAbstractType(const DerivedType *OldType,
1318 const Type *NewType) {
1319 PointerTypes.finishRefinement(this, OldType, NewType);
1322 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1323 refineAbstractType(AbsTy, AbsTy);
1326 bool SequentialType::indexValid(const Value *V) const {
1327 const Type *Ty = V->getType();
1328 switch (Ty->getTypeID()) {
1330 case Type::UIntTyID:
1331 case Type::LongTyID:
1332 case Type::ULongTyID:
1340 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1342 OS << "<null> value!\n";
1348 std::ostream &operator<<(std::ostream &OS, const Type &T) {
1354 /// clearAllTypeMaps - This method frees all internal memory used by the
1355 /// type subsystem, which can be used in environments where this memory is
1356 /// otherwise reported as a leak.
1357 void Type::clearAllTypeMaps() {
1358 std::vector<Type *> DerivedTypes;
1360 FunctionTypes.clear(DerivedTypes);
1361 PointerTypes.clear(DerivedTypes);
1362 StructTypes.clear(DerivedTypes);
1363 ArrayTypes.clear(DerivedTypes);
1364 PackedTypes.clear(DerivedTypes);
1366 for(std::vector<Type *>::iterator I = DerivedTypes.begin(),
1367 E = DerivedTypes.end(); I != E; ++I)
1368 (*I)->ContainedTys.clear();
1369 for(std::vector<Type *>::iterator I = DerivedTypes.begin(),
1370 E = DerivedTypes.end(); I != E; ++I)
1372 DerivedTypes.clear();