1 //===-- Type.cpp - Implement the Type class -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Type class for the VMCore library.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/AbstractTypeUser.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/SymbolTable.h"
17 #include "llvm/Constants.h"
18 #include "llvm/ADT/DepthFirstIterator.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/SCCIterator.h"
21 #include "llvm/ADT/STLExtras.h"
26 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
27 // created and later destroyed, all in an effort to make sure that there is only
28 // a single canonical version of a type.
30 //#define DEBUG_MERGE_TYPES 1
32 AbstractTypeUser::~AbstractTypeUser() {}
34 //===----------------------------------------------------------------------===//
35 // Type Class Implementation
36 //===----------------------------------------------------------------------===//
38 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
39 // for types as they are needed. Because resolution of types must invalidate
40 // all of the abstract type descriptions, we keep them in a seperate map to make
42 static std::map<const Type*, std::string> ConcreteTypeDescriptions;
43 static std::map<const Type*, std::string> AbstractTypeDescriptions;
45 Type::Type( const std::string& name, TypeID id )
46 : RefCount(0), ForwardType(0) {
48 ConcreteTypeDescriptions[this] = name;
53 const Type *Type::getPrimitiveType(TypeID IDNumber) {
55 case VoidTyID : return VoidTy;
56 case BoolTyID : return BoolTy;
57 case UByteTyID : return UByteTy;
58 case SByteTyID : return SByteTy;
59 case UShortTyID: return UShortTy;
60 case ShortTyID : return ShortTy;
61 case UIntTyID : return UIntTy;
62 case IntTyID : return IntTy;
63 case ULongTyID : return ULongTy;
64 case LongTyID : return LongTy;
65 case FloatTyID : return FloatTy;
66 case DoubleTyID: return DoubleTy;
67 case LabelTyID : return LabelTy;
73 // isLosslesslyConvertibleTo - Return true if this type can be converted to
74 // 'Ty' without any reinterpretation of bits. For example, uint to int.
76 bool Type::isLosslesslyConvertibleTo(const Type *Ty) const {
77 if (this == Ty) return true;
78 if ((!isPrimitiveType() && !isa<PointerType>(this)) ||
79 (!isa<PointerType>(Ty) && !Ty->isPrimitiveType())) return false;
81 if (getTypeID() == Ty->getTypeID())
82 return true; // Handles identity cast, and cast of differing pointer types
84 // Now we know that they are two differing primitive or pointer types
85 switch (getTypeID()) {
86 case Type::UByteTyID: return Ty == Type::SByteTy;
87 case Type::SByteTyID: return Ty == Type::UByteTy;
88 case Type::UShortTyID: return Ty == Type::ShortTy;
89 case Type::ShortTyID: return Ty == Type::UShortTy;
90 case Type::UIntTyID: return Ty == Type::IntTy;
91 case Type::IntTyID: return Ty == Type::UIntTy;
92 case Type::ULongTyID: return Ty == Type::LongTy;
93 case Type::LongTyID: return Ty == Type::ULongTy;
94 case Type::PointerTyID: return isa<PointerType>(Ty);
96 return false; // Other types have no identity values
100 /// getUnsignedVersion - If this is an integer type, return the unsigned
101 /// variant of this type. For example int -> uint.
102 const Type *Type::getUnsignedVersion() const {
103 switch (getTypeID()) {
105 assert(isInteger()&&"Type::getUnsignedVersion is only valid for integers!");
106 case Type::UByteTyID:
107 case Type::SByteTyID: return Type::UByteTy;
108 case Type::UShortTyID:
109 case Type::ShortTyID: return Type::UShortTy;
111 case Type::IntTyID: return Type::UIntTy;
112 case Type::ULongTyID:
113 case Type::LongTyID: return Type::ULongTy;
117 /// getSignedVersion - If this is an integer type, return the signed variant
118 /// of this type. For example uint -> int.
119 const Type *Type::getSignedVersion() const {
120 switch (getTypeID()) {
122 assert(isInteger() && "Type::getSignedVersion is only valid for integers!");
123 case Type::UByteTyID:
124 case Type::SByteTyID: return Type::SByteTy;
125 case Type::UShortTyID:
126 case Type::ShortTyID: return Type::ShortTy;
128 case Type::IntTyID: return Type::IntTy;
129 case Type::ULongTyID:
130 case Type::LongTyID: return Type::LongTy;
135 // getPrimitiveSize - Return the basic size of this type if it is a primitive
136 // type. These are fixed by LLVM and are not target dependent. This will
137 // return zero if the type does not have a size or is not a primitive type.
139 unsigned Type::getPrimitiveSize() const {
140 switch (getTypeID()) {
141 #define HANDLE_PRIM_TYPE(TY,SIZE) case TY##TyID: return SIZE;
142 #include "llvm/Type.def"
147 /// isSizedDerivedType - Derived types like structures and arrays are sized
148 /// iff all of the members of the type are sized as well. Since asking for
149 /// their size is relatively uncommon, move this operation out of line.
150 bool Type::isSizedDerivedType() const {
151 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
152 return ATy->getElementType()->isSized();
154 if (const PackedType *PTy = dyn_cast<PackedType>(this))
155 return PTy->getElementType()->isSized();
157 if (!isa<StructType>(this)) return false;
159 // Okay, our struct is sized if all of the elements are...
160 for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
161 if (!(*I)->isSized()) return false;
166 /// getForwardedTypeInternal - This method is used to implement the union-find
167 /// algorithm for when a type is being forwarded to another type.
168 const Type *Type::getForwardedTypeInternal() const {
169 assert(ForwardType && "This type is not being forwarded to another type!");
171 // Check to see if the forwarded type has been forwarded on. If so, collapse
172 // the forwarding links.
173 const Type *RealForwardedType = ForwardType->getForwardedType();
174 if (!RealForwardedType)
175 return ForwardType; // No it's not forwarded again
177 // Yes, it is forwarded again. First thing, add the reference to the new
179 if (RealForwardedType->isAbstract())
180 cast<DerivedType>(RealForwardedType)->addRef();
182 // Now drop the old reference. This could cause ForwardType to get deleted.
183 cast<DerivedType>(ForwardType)->dropRef();
185 // Return the updated type.
186 ForwardType = RealForwardedType;
190 // getTypeDescription - This is a recursive function that walks a type hierarchy
191 // calculating the description for a type.
193 static std::string getTypeDescription(const Type *Ty,
194 std::vector<const Type *> &TypeStack) {
195 if (isa<OpaqueType>(Ty)) { // Base case for the recursion
196 std::map<const Type*, std::string>::iterator I =
197 AbstractTypeDescriptions.lower_bound(Ty);
198 if (I != AbstractTypeDescriptions.end() && I->first == Ty)
200 std::string Desc = "opaque";
201 AbstractTypeDescriptions.insert(std::make_pair(Ty, Desc));
205 if (!Ty->isAbstract()) { // Base case for the recursion
206 std::map<const Type*, std::string>::iterator I =
207 ConcreteTypeDescriptions.find(Ty);
208 if (I != ConcreteTypeDescriptions.end()) return I->second;
211 // Check to see if the Type is already on the stack...
212 unsigned Slot = 0, CurSize = TypeStack.size();
213 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
215 // This is another base case for the recursion. In this case, we know
216 // that we have looped back to a type that we have previously visited.
217 // Generate the appropriate upreference to handle this.
220 return "\\" + utostr(CurSize-Slot); // Here's the upreference
222 // Recursive case: derived types...
224 TypeStack.push_back(Ty); // Add us to the stack..
226 switch (Ty->getTypeID()) {
227 case Type::FunctionTyID: {
228 const FunctionType *FTy = cast<FunctionType>(Ty);
229 Result = getTypeDescription(FTy->getReturnType(), TypeStack) + " (";
230 for (FunctionType::param_iterator I = FTy->param_begin(),
231 E = FTy->param_end(); I != E; ++I) {
232 if (I != FTy->param_begin())
234 Result += getTypeDescription(*I, TypeStack);
236 if (FTy->isVarArg()) {
237 if (FTy->getNumParams()) Result += ", ";
243 case Type::StructTyID: {
244 const StructType *STy = cast<StructType>(Ty);
246 for (StructType::element_iterator I = STy->element_begin(),
247 E = STy->element_end(); I != E; ++I) {
248 if (I != STy->element_begin())
250 Result += getTypeDescription(*I, TypeStack);
255 case Type::PointerTyID: {
256 const PointerType *PTy = cast<PointerType>(Ty);
257 Result = getTypeDescription(PTy->getElementType(), TypeStack) + " *";
260 case Type::ArrayTyID: {
261 const ArrayType *ATy = cast<ArrayType>(Ty);
262 unsigned NumElements = ATy->getNumElements();
264 Result += utostr(NumElements) + " x ";
265 Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
268 case Type::PackedTyID: {
269 const PackedType *PTy = cast<PackedType>(Ty);
270 unsigned NumElements = PTy->getNumElements();
272 Result += utostr(NumElements) + " x ";
273 Result += getTypeDescription(PTy->getElementType(), TypeStack) + ">";
278 assert(0 && "Unhandled type in getTypeDescription!");
281 TypeStack.pop_back(); // Remove self from stack...
288 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
290 std::map<const Type*, std::string>::iterator I = Map.find(Ty);
291 if (I != Map.end()) return I->second;
293 std::vector<const Type *> TypeStack;
294 return Map[Ty] = getTypeDescription(Ty, TypeStack);
298 const std::string &Type::getDescription() const {
300 return getOrCreateDesc(AbstractTypeDescriptions, this);
302 return getOrCreateDesc(ConcreteTypeDescriptions, this);
306 bool StructType::indexValid(const Value *V) const {
307 // Structure indexes require unsigned integer constants.
308 if (V->getType() == Type::UIntTy)
309 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(V))
310 return CU->getValue() < ContainedTys.size();
314 // getTypeAtIndex - Given an index value into the type, return the type of the
315 // element. For a structure type, this must be a constant value...
317 const Type *StructType::getTypeAtIndex(const Value *V) const {
318 assert(indexValid(V) && "Invalid structure index!");
319 unsigned Idx = (unsigned)cast<ConstantUInt>(V)->getValue();
320 return ContainedTys[Idx];
324 //===----------------------------------------------------------------------===//
325 // Static 'Type' data
326 //===----------------------------------------------------------------------===//
329 struct PrimType : public Type {
330 PrimType(const char *S, TypeID ID) : Type(S, ID) {}
334 static PrimType TheVoidTy ("void" , Type::VoidTyID);
335 static PrimType TheBoolTy ("bool" , Type::BoolTyID);
336 static PrimType TheSByteTy ("sbyte" , Type::SByteTyID);
337 static PrimType TheUByteTy ("ubyte" , Type::UByteTyID);
338 static PrimType TheShortTy ("short" , Type::ShortTyID);
339 static PrimType TheUShortTy("ushort", Type::UShortTyID);
340 static PrimType TheIntTy ("int" , Type::IntTyID);
341 static PrimType TheUIntTy ("uint" , Type::UIntTyID);
342 static PrimType TheLongTy ("long" , Type::LongTyID);
343 static PrimType TheULongTy ("ulong" , Type::ULongTyID);
344 static PrimType TheFloatTy ("float" , Type::FloatTyID);
345 static PrimType TheDoubleTy("double", Type::DoubleTyID);
346 static PrimType TheLabelTy ("label" , Type::LabelTyID);
348 Type *Type::VoidTy = &TheVoidTy;
349 Type *Type::BoolTy = &TheBoolTy;
350 Type *Type::SByteTy = &TheSByteTy;
351 Type *Type::UByteTy = &TheUByteTy;
352 Type *Type::ShortTy = &TheShortTy;
353 Type *Type::UShortTy = &TheUShortTy;
354 Type *Type::IntTy = &TheIntTy;
355 Type *Type::UIntTy = &TheUIntTy;
356 Type *Type::LongTy = &TheLongTy;
357 Type *Type::ULongTy = &TheULongTy;
358 Type *Type::FloatTy = &TheFloatTy;
359 Type *Type::DoubleTy = &TheDoubleTy;
360 Type *Type::LabelTy = &TheLabelTy;
363 //===----------------------------------------------------------------------===//
364 // Derived Type Constructors
365 //===----------------------------------------------------------------------===//
367 FunctionType::FunctionType(const Type *Result,
368 const std::vector<const Type*> &Params,
369 bool IsVarArgs) : DerivedType(FunctionTyID),
370 isVarArgs(IsVarArgs) {
371 assert((Result->isFirstClassType() || Result == Type::VoidTy ||
372 isa<OpaqueType>(Result)) &&
373 "LLVM functions cannot return aggregates");
374 bool isAbstract = Result->isAbstract();
375 ContainedTys.reserve(Params.size()+1);
376 ContainedTys.push_back(PATypeHandle(Result, this));
378 for (unsigned i = 0; i != Params.size(); ++i) {
379 assert((Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])) &&
380 "Function arguments must be value types!");
382 ContainedTys.push_back(PATypeHandle(Params[i], this));
383 isAbstract |= Params[i]->isAbstract();
386 // Calculate whether or not this type is abstract
387 setAbstract(isAbstract);
390 StructType::StructType(const std::vector<const Type*> &Types)
391 : CompositeType(StructTyID) {
392 ContainedTys.reserve(Types.size());
393 bool isAbstract = false;
394 for (unsigned i = 0; i < Types.size(); ++i) {
395 assert(Types[i] != Type::VoidTy && "Void type for structure field!!");
396 ContainedTys.push_back(PATypeHandle(Types[i], this));
397 isAbstract |= Types[i]->isAbstract();
400 // Calculate whether or not this type is abstract
401 setAbstract(isAbstract);
404 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
405 : SequentialType(ArrayTyID, ElType) {
408 // Calculate whether or not this type is abstract
409 setAbstract(ElType->isAbstract());
412 PackedType::PackedType(const Type *ElType, unsigned NumEl)
413 : SequentialType(PackedTyID, ElType) {
416 assert(NumEl > 0 && "NumEl of a PackedType must be greater than 0");
417 assert((ElType->isIntegral() || ElType->isFloatingPoint()) &&
418 "Elements of a PackedType must be a primitive type");
422 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
423 // Calculate whether or not this type is abstract
424 setAbstract(E->isAbstract());
427 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
429 #ifdef DEBUG_MERGE_TYPES
430 std::cerr << "Derived new type: " << *this << "\n";
434 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
435 // another (more concrete) type, we must eliminate all references to other
436 // types, to avoid some circular reference problems.
437 void DerivedType::dropAllTypeUses() {
438 if (!ContainedTys.empty()) {
439 while (ContainedTys.size() > 1)
440 ContainedTys.pop_back();
442 // The type must stay abstract. To do this, we insert a pointer to a type
443 // that will never get resolved, thus will always be abstract.
444 static Type *AlwaysOpaqueTy = OpaqueType::get();
445 static PATypeHolder Holder(AlwaysOpaqueTy);
446 ContainedTys[0] = AlwaysOpaqueTy;
452 /// TypePromotionGraph and graph traits - this is designed to allow us to do
453 /// efficient SCC processing of type graphs. This is the exact same as
454 /// GraphTraits<Type*>, except that we pretend that concrete types have no
455 /// children to avoid processing them.
456 struct TypePromotionGraph {
458 TypePromotionGraph(Type *T) : Ty(T) {}
462 template <> struct GraphTraits<TypePromotionGraph> {
463 typedef Type NodeType;
464 typedef Type::subtype_iterator ChildIteratorType;
466 static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
467 static inline ChildIteratorType child_begin(NodeType *N) {
469 return N->subtype_begin();
470 else // No need to process children of concrete types.
471 return N->subtype_end();
473 static inline ChildIteratorType child_end(NodeType *N) {
474 return N->subtype_end();
480 // PromoteAbstractToConcrete - This is a recursive function that walks a type
481 // graph calculating whether or not a type is abstract.
483 // This method returns true if the type is found to still be abstract.
485 void Type::PromoteAbstractToConcrete() {
486 if (!isAbstract()) return;
488 scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
489 scc_iterator<TypePromotionGraph> SE = scc_end (TypePromotionGraph(this));
491 for (; SI != SE; ++SI) {
492 std::vector<Type*> &SCC = *SI;
494 // Concrete types are leaves in the tree. Since an SCC will either be all
495 // abstract or all concrete, we only need to check one type.
496 if (SCC[0]->isAbstract()) {
497 if (isa<OpaqueType>(SCC[0]))
498 return; // Not going to be concrete, sorry.
500 // If all of the children of all of the types in this SCC are concrete,
501 // then this SCC is now concrete as well. If not, neither this SCC, nor
502 // any parent SCCs will be concrete, so we might as well just exit.
503 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
504 for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
505 E = SCC[i]->subtype_end(); CI != E; ++CI)
506 if ((*CI)->isAbstract())
507 return; // Not going to be concrete, sorry.
509 // Okay, we just discovered this whole SCC is now concrete, mark it as
511 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
512 assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
514 SCC[i]->setAbstract(false);
515 // The type just became concrete, notify all users!
516 cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
523 //===----------------------------------------------------------------------===//
524 // Type Structural Equality Testing
525 //===----------------------------------------------------------------------===//
527 // TypesEqual - Two types are considered structurally equal if they have the
528 // same "shape": Every level and element of the types have identical primitive
529 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
530 // be pointer equals to be equivalent though. This uses an optimistic algorithm
531 // that assumes that two graphs are the same until proven otherwise.
533 static bool TypesEqual(const Type *Ty, const Type *Ty2,
534 std::map<const Type *, const Type *> &EqTypes) {
535 if (Ty == Ty2) return true;
536 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
537 if (isa<OpaqueType>(Ty))
538 return false; // Two unequal opaque types are never equal
540 std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
541 if (It != EqTypes.end() && It->first == Ty)
542 return It->second == Ty2; // Looping back on a type, check for equality
544 // Otherwise, add the mapping to the table to make sure we don't get
545 // recursion on the types...
546 EqTypes.insert(It, std::make_pair(Ty, Ty2));
548 // Two really annoying special cases that breaks an otherwise nice simple
549 // algorithm is the fact that arraytypes have sizes that differentiates types,
550 // and that function types can be varargs or not. Consider this now.
552 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
553 return TypesEqual(PTy->getElementType(),
554 cast<PointerType>(Ty2)->getElementType(), EqTypes);
555 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
556 const StructType *STy2 = cast<StructType>(Ty2);
557 if (STy->getNumElements() != STy2->getNumElements()) return false;
558 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
559 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
562 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
563 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
564 return ATy->getNumElements() == ATy2->getNumElements() &&
565 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
566 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
567 const PackedType *PTy2 = cast<PackedType>(Ty2);
568 return PTy->getNumElements() == PTy2->getNumElements() &&
569 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
570 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
571 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
572 if (FTy->isVarArg() != FTy2->isVarArg() ||
573 FTy->getNumParams() != FTy2->getNumParams() ||
574 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
576 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i)
577 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
581 assert(0 && "Unknown derived type!");
586 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
587 std::map<const Type *, const Type *> EqTypes;
588 return TypesEqual(Ty, Ty2, EqTypes);
591 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
592 // TargetTy in the type graph. We know that Ty is an abstract type, so if we
593 // ever reach a non-abstract type, we know that we don't need to search the
595 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
596 std::set<const Type*> &VisitedTypes) {
597 if (TargetTy == CurTy) return true;
598 if (!CurTy->isAbstract()) return false;
600 if (!VisitedTypes.insert(CurTy).second)
601 return false; // Already been here.
603 for (Type::subtype_iterator I = CurTy->subtype_begin(),
604 E = CurTy->subtype_end(); I != E; ++I)
605 if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
610 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
611 std::set<const Type*> &VisitedTypes) {
612 if (TargetTy == CurTy) return true;
614 if (!VisitedTypes.insert(CurTy).second)
615 return false; // Already been here.
617 for (Type::subtype_iterator I = CurTy->subtype_begin(),
618 E = CurTy->subtype_end(); I != E; ++I)
619 if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
624 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
626 static bool TypeHasCycleThroughItself(const Type *Ty) {
627 std::set<const Type*> VisitedTypes;
629 if (Ty->isAbstract()) { // Optimized case for abstract types.
630 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
632 if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
635 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
637 if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
644 //===----------------------------------------------------------------------===//
645 // Derived Type Factory Functions
646 //===----------------------------------------------------------------------===//
648 // TypeMap - Make sure that only one instance of a particular type may be
649 // created on any given run of the compiler... note that this involves updating
650 // our map if an abstract type gets refined somehow.
653 template<class ValType, class TypeClass>
655 std::map<ValType, PATypeHolder> Map;
657 /// TypesByHash - Keep track of types by their structure hash value. Note
658 /// that we only keep track of types that have cycles through themselves in
661 std::multimap<unsigned, PATypeHolder> TypesByHash;
663 friend void Type::clearAllTypeMaps();
666 void clear(std::vector<Type *> &DerivedTypes) {
667 for (typename std::map<ValType, PATypeHolder>::iterator I = Map.begin(),
668 E = Map.end(); I != E; ++I)
669 DerivedTypes.push_back(I->second.get());
674 typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
675 ~TypeMap() { print("ON EXIT"); }
677 inline TypeClass *get(const ValType &V) {
678 iterator I = Map.find(V);
679 return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
682 inline void add(const ValType &V, TypeClass *Ty) {
683 Map.insert(std::make_pair(V, Ty));
685 // If this type has a cycle, remember it.
686 TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
690 void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
691 std::multimap<unsigned, PATypeHolder>::iterator I =
692 TypesByHash.lower_bound(Hash);
693 while (I->second != Ty) {
695 assert(I != TypesByHash.end() && I->first == Hash);
697 TypesByHash.erase(I);
700 /// finishRefinement - This method is called after we have updated an existing
701 /// type with its new components. We must now either merge the type away with
702 /// some other type or reinstall it in the map with it's new configuration.
703 /// The specified iterator tells us what the type USED to look like.
704 void finishRefinement(TypeClass *Ty, const DerivedType *OldType,
705 const Type *NewType) {
706 assert((Ty->isAbstract() || !OldType->isAbstract()) &&
707 "Refining a non-abstract type!");
708 #ifdef DEBUG_MERGE_TYPES
709 std::cerr << "refineAbstractTy(" << (void*)OldType << "[" << *OldType
710 << "], " << (void*)NewType << " [" << *NewType << "])\n";
713 // Make a temporary type holder for the type so that it doesn't disappear on
714 // us when we erase the entry from the map.
715 PATypeHolder TyHolder = Ty;
717 // The old record is now out-of-date, because one of the children has been
718 // updated. Remove the obsolete entry from the map.
719 Map.erase(ValType::get(Ty));
721 // Remember the structural hash for the type before we start hacking on it,
722 // in case we need it later.
723 unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
725 // Find the type element we are refining... and change it now!
726 for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
727 if (Ty->ContainedTys[i] == OldType) {
728 Ty->ContainedTys[i].removeUserFromConcrete();
729 Ty->ContainedTys[i] = NewType;
732 unsigned TypeHash = ValType::hashTypeStructure(Ty);
734 // If there are no cycles going through this node, we can do a simple,
735 // efficient lookup in the map, instead of an inefficient nasty linear
737 if (!Ty->isAbstract() || !TypeHasCycleThroughItself(Ty)) {
738 typename std::map<ValType, PATypeHolder>::iterator I;
741 ValType V = ValType::get(Ty);
742 tie(I, Inserted) = Map.insert(std::make_pair(V, Ty));
744 // Refined to a different type altogether?
745 RemoveFromTypesByHash(TypeHash, Ty);
747 // We already have this type in the table. Get rid of the newly refined
749 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
750 Ty->refineAbstractTypeTo(NewTy);
755 // Now we check to see if there is an existing entry in the table which is
756 // structurally identical to the newly refined type. If so, this type
757 // gets refined to the pre-existing type.
759 std::multimap<unsigned, PATypeHolder>::iterator I, E, Entry;
760 tie(I, E) = TypesByHash.equal_range(OldTypeHash);
762 for (; I != E; ++I) {
763 if (I->second != Ty) {
764 if (TypesEqual(Ty, I->second)) {
765 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
766 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
769 // Find the location of Ty in the TypesByHash structure.
770 while (I->second != Ty) {
772 assert(I != E && "Structure doesn't contain type??");
777 TypesByHash.erase(Entry);
778 Ty->refineAbstractTypeTo(NewTy);
782 // Remember the position of
788 // If there is no existing type of the same structure, we reinsert an
789 // updated record into the map.
790 Map.insert(std::make_pair(ValType::get(Ty), Ty));
793 // If the hash codes differ, update TypesByHash
794 if (TypeHash != OldTypeHash) {
795 RemoveFromTypesByHash(OldTypeHash, Ty);
796 TypesByHash.insert(std::make_pair(TypeHash, Ty));
799 // If the type is currently thought to be abstract, rescan all of our
800 // subtypes to see if the type has just become concrete!
801 if (Ty->isAbstract())
802 Ty->PromoteAbstractToConcrete();
805 void print(const char *Arg) const {
806 #ifdef DEBUG_MERGE_TYPES
807 std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
809 for (typename std::map<ValType, PATypeHolder>::const_iterator I
810 = Map.begin(), E = Map.end(); I != E; ++I)
811 std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " "
812 << *I->second.get() << "\n";
816 void dump() const { print("dump output"); }
821 //===----------------------------------------------------------------------===//
822 // Function Type Factory and Value Class...
825 // FunctionValType - Define a class to hold the key that goes into the TypeMap
828 class FunctionValType {
830 std::vector<const Type*> ArgTypes;
833 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
834 bool IVA) : RetTy(ret), isVarArg(IVA) {
835 for (unsigned i = 0; i < args.size(); ++i)
836 ArgTypes.push_back(args[i]);
839 static FunctionValType get(const FunctionType *FT);
841 static unsigned hashTypeStructure(const FunctionType *FT) {
842 return FT->getNumParams()*2+FT->isVarArg();
845 // Subclass should override this... to update self as usual
846 void doRefinement(const DerivedType *OldType, const Type *NewType) {
847 if (RetTy == OldType) RetTy = NewType;
848 for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
849 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
852 inline bool operator<(const FunctionValType &MTV) const {
853 if (RetTy < MTV.RetTy) return true;
854 if (RetTy > MTV.RetTy) return false;
856 if (ArgTypes < MTV.ArgTypes) return true;
857 return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
862 // Define the actual map itself now...
863 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
865 FunctionValType FunctionValType::get(const FunctionType *FT) {
866 // Build up a FunctionValType
867 std::vector<const Type *> ParamTypes;
868 ParamTypes.reserve(FT->getNumParams());
869 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
870 ParamTypes.push_back(FT->getParamType(i));
871 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
875 // FunctionType::get - The factory function for the FunctionType class...
876 FunctionType *FunctionType::get(const Type *ReturnType,
877 const std::vector<const Type*> &Params,
879 FunctionValType VT(ReturnType, Params, isVarArg);
880 FunctionType *MT = FunctionTypes.get(VT);
883 FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
885 #ifdef DEBUG_MERGE_TYPES
886 std::cerr << "Derived new type: " << MT << "\n";
891 //===----------------------------------------------------------------------===//
892 // Array Type Factory...
899 ArrayValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
901 static ArrayValType get(const ArrayType *AT) {
902 return ArrayValType(AT->getElementType(), AT->getNumElements());
905 static unsigned hashTypeStructure(const ArrayType *AT) {
906 return AT->getNumElements();
909 // Subclass should override this... to update self as usual
910 void doRefinement(const DerivedType *OldType, const Type *NewType) {
911 assert(ValTy == OldType);
915 inline bool operator<(const ArrayValType &MTV) const {
916 if (Size < MTV.Size) return true;
917 return Size == MTV.Size && ValTy < MTV.ValTy;
921 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
924 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
925 assert(ElementType && "Can't get array of null types!");
927 ArrayValType AVT(ElementType, NumElements);
928 ArrayType *AT = ArrayTypes.get(AVT);
929 if (AT) return AT; // Found a match, return it!
931 // Value not found. Derive a new type!
932 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
934 #ifdef DEBUG_MERGE_TYPES
935 std::cerr << "Derived new type: " << *AT << "\n";
941 //===----------------------------------------------------------------------===//
942 // Packed Type Factory...
945 class PackedValType {
949 PackedValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
951 static PackedValType get(const PackedType *PT) {
952 return PackedValType(PT->getElementType(), PT->getNumElements());
955 static unsigned hashTypeStructure(const PackedType *PT) {
956 return PT->getNumElements();
959 // Subclass should override this... to update self as usual
960 void doRefinement(const DerivedType *OldType, const Type *NewType) {
961 assert(ValTy == OldType);
965 inline bool operator<(const PackedValType &MTV) const {
966 if (Size < MTV.Size) return true;
967 return Size == MTV.Size && ValTy < MTV.ValTy;
971 static TypeMap<PackedValType, PackedType> PackedTypes;
974 PackedType *PackedType::get(const Type *ElementType, unsigned NumElements) {
975 assert(ElementType && "Can't get packed of null types!");
977 PackedValType PVT(ElementType, NumElements);
978 PackedType *PT = PackedTypes.get(PVT);
979 if (PT) return PT; // Found a match, return it!
981 // Value not found. Derive a new type!
982 PackedTypes.add(PVT, PT = new PackedType(ElementType, NumElements));
984 #ifdef DEBUG_MERGE_TYPES
985 std::cerr << "Derived new type: " << *PT << "\n";
990 //===----------------------------------------------------------------------===//
991 // Struct Type Factory...
995 // StructValType - Define a class to hold the key that goes into the TypeMap
997 class StructValType {
998 std::vector<const Type*> ElTypes;
1000 StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
1002 static StructValType get(const StructType *ST) {
1003 std::vector<const Type *> ElTypes;
1004 ElTypes.reserve(ST->getNumElements());
1005 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
1006 ElTypes.push_back(ST->getElementType(i));
1008 return StructValType(ElTypes);
1011 static unsigned hashTypeStructure(const StructType *ST) {
1012 return ST->getNumElements();
1015 // Subclass should override this... to update self as usual
1016 void doRefinement(const DerivedType *OldType, const Type *NewType) {
1017 for (unsigned i = 0; i < ElTypes.size(); ++i)
1018 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
1021 inline bool operator<(const StructValType &STV) const {
1022 return ElTypes < STV.ElTypes;
1027 static TypeMap<StructValType, StructType> StructTypes;
1029 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
1030 StructValType STV(ETypes);
1031 StructType *ST = StructTypes.get(STV);
1034 // Value not found. Derive a new type!
1035 StructTypes.add(STV, ST = new StructType(ETypes));
1037 #ifdef DEBUG_MERGE_TYPES
1038 std::cerr << "Derived new type: " << *ST << "\n";
1045 //===----------------------------------------------------------------------===//
1046 // Pointer Type Factory...
1049 // PointerValType - Define a class to hold the key that goes into the TypeMap
1052 class PointerValType {
1055 PointerValType(const Type *val) : ValTy(val) {}
1057 static PointerValType get(const PointerType *PT) {
1058 return PointerValType(PT->getElementType());
1061 static unsigned hashTypeStructure(const PointerType *PT) {
1065 // Subclass should override this... to update self as usual
1066 void doRefinement(const DerivedType *OldType, const Type *NewType) {
1067 assert(ValTy == OldType);
1071 bool operator<(const PointerValType &MTV) const {
1072 return ValTy < MTV.ValTy;
1077 static TypeMap<PointerValType, PointerType> PointerTypes;
1079 PointerType *PointerType::get(const Type *ValueType) {
1080 assert(ValueType && "Can't get a pointer to <null> type!");
1081 PointerValType PVT(ValueType);
1083 PointerType *PT = PointerTypes.get(PVT);
1086 // Value not found. Derive a new type!
1087 PointerTypes.add(PVT, PT = new PointerType(ValueType));
1089 #ifdef DEBUG_MERGE_TYPES
1090 std::cerr << "Derived new type: " << *PT << "\n";
1096 //===----------------------------------------------------------------------===//
1097 // Derived Type Refinement Functions
1098 //===----------------------------------------------------------------------===//
1100 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1101 // no longer has a handle to the type. This function is called primarily by
1102 // the PATypeHandle class. When there are no users of the abstract type, it
1103 // is annihilated, because there is no way to get a reference to it ever again.
1105 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
1106 // Search from back to front because we will notify users from back to
1107 // front. Also, it is likely that there will be a stack like behavior to
1108 // users that register and unregister users.
1111 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1112 assert(i != 0 && "AbstractTypeUser not in user list!");
1114 --i; // Convert to be in range 0 <= i < size()
1115 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1117 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1119 #ifdef DEBUG_MERGE_TYPES
1120 std::cerr << " remAbstractTypeUser[" << (void*)this << ", "
1121 << *this << "][" << i << "] User = " << U << "\n";
1124 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1125 #ifdef DEBUG_MERGE_TYPES
1126 std::cerr << "DELETEing unused abstract type: <" << *this
1127 << ">[" << (void*)this << "]" << "\n";
1129 delete this; // No users of this abstract type!
1134 // refineAbstractTypeTo - This function is used to when it is discovered that
1135 // the 'this' abstract type is actually equivalent to the NewType specified.
1136 // This causes all users of 'this' to switch to reference the more concrete type
1137 // NewType and for 'this' to be deleted.
1139 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1140 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1141 assert(this != NewType && "Can't refine to myself!");
1142 assert(ForwardType == 0 && "This type has already been refined!");
1144 // The descriptions may be out of date. Conservatively clear them all!
1145 AbstractTypeDescriptions.clear();
1147 #ifdef DEBUG_MERGE_TYPES
1148 std::cerr << "REFINING abstract type [" << (void*)this << " "
1149 << *this << "] to [" << (void*)NewType << " "
1150 << *NewType << "]!\n";
1153 // Make sure to put the type to be refined to into a holder so that if IT gets
1154 // refined, that we will not continue using a dead reference...
1156 PATypeHolder NewTy(NewType);
1158 // Any PATypeHolders referring to this type will now automatically forward to
1159 // the type we are resolved to.
1160 ForwardType = NewType;
1161 if (NewType->isAbstract())
1162 cast<DerivedType>(NewType)->addRef();
1164 // Add a self use of the current type so that we don't delete ourself until
1165 // after the function exits.
1167 PATypeHolder CurrentTy(this);
1169 // To make the situation simpler, we ask the subclass to remove this type from
1170 // the type map, and to replace any type uses with uses of non-abstract types.
1171 // This dramatically limits the amount of recursive type trouble we can find
1175 // Iterate over all of the uses of this type, invoking callback. Each user
1176 // should remove itself from our use list automatically. We have to check to
1177 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1178 // will not cause users to drop off of the use list. If we resolve to ourself
1181 while (!AbstractTypeUsers.empty() && NewTy != this) {
1182 AbstractTypeUser *User = AbstractTypeUsers.back();
1184 unsigned OldSize = AbstractTypeUsers.size();
1185 #ifdef DEBUG_MERGE_TYPES
1186 std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
1187 << "] of abstract type [" << (void*)this << " "
1188 << *this << "] to [" << (void*)NewTy.get() << " "
1189 << *NewTy << "]!\n";
1191 User->refineAbstractType(this, NewTy);
1193 assert(AbstractTypeUsers.size() != OldSize &&
1194 "AbsTyUser did not remove self from user list!");
1197 // If we were successful removing all users from the type, 'this' will be
1198 // deleted when the last PATypeHolder is destroyed or updated from this type.
1199 // This may occur on exit of this function, as the CurrentTy object is
1203 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1204 // the current type has transitioned from being abstract to being concrete.
1206 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1207 #ifdef DEBUG_MERGE_TYPES
1208 std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1211 unsigned OldSize = AbstractTypeUsers.size();
1212 while (!AbstractTypeUsers.empty()) {
1213 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1214 ATU->typeBecameConcrete(this);
1216 assert(AbstractTypeUsers.size() < OldSize-- &&
1217 "AbstractTypeUser did not remove itself from the use list!");
1224 // refineAbstractType - Called when a contained type is found to be more
1225 // concrete - this could potentially change us from an abstract type to a
1228 void FunctionType::refineAbstractType(const DerivedType *OldType,
1229 const Type *NewType) {
1230 FunctionTypes.finishRefinement(this, OldType, NewType);
1233 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1234 refineAbstractType(AbsTy, AbsTy);
1238 // refineAbstractType - Called when a contained type is found to be more
1239 // concrete - this could potentially change us from an abstract type to a
1242 void ArrayType::refineAbstractType(const DerivedType *OldType,
1243 const Type *NewType) {
1244 ArrayTypes.finishRefinement(this, OldType, NewType);
1247 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1248 refineAbstractType(AbsTy, AbsTy);
1251 // refineAbstractType - Called when a contained type is found to be more
1252 // concrete - this could potentially change us from an abstract type to a
1255 void PackedType::refineAbstractType(const DerivedType *OldType,
1256 const Type *NewType) {
1257 PackedTypes.finishRefinement(this, OldType, NewType);
1260 void PackedType::typeBecameConcrete(const DerivedType *AbsTy) {
1261 refineAbstractType(AbsTy, AbsTy);
1264 // refineAbstractType - Called when a contained type is found to be more
1265 // concrete - this could potentially change us from an abstract type to a
1268 void StructType::refineAbstractType(const DerivedType *OldType,
1269 const Type *NewType) {
1270 StructTypes.finishRefinement(this, OldType, NewType);
1273 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1274 refineAbstractType(AbsTy, AbsTy);
1277 // refineAbstractType - Called when a contained type is found to be more
1278 // concrete - this could potentially change us from an abstract type to a
1281 void PointerType::refineAbstractType(const DerivedType *OldType,
1282 const Type *NewType) {
1283 PointerTypes.finishRefinement(this, OldType, NewType);
1286 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1287 refineAbstractType(AbsTy, AbsTy);
1290 bool SequentialType::indexValid(const Value *V) const {
1291 const Type *Ty = V->getType();
1292 switch (Ty->getTypeID()) {
1294 case Type::UIntTyID:
1295 case Type::LongTyID:
1296 case Type::ULongTyID:
1304 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1306 OS << "<null> value!\n";
1312 std::ostream &operator<<(std::ostream &OS, const Type &T) {
1318 /// clearAllTypeMaps - This method frees all internal memory used by the
1319 /// type subsystem, which can be used in environments where this memory is
1320 /// otherwise reported as a leak.
1321 void Type::clearAllTypeMaps() {
1322 std::vector<Type *> DerivedTypes;
1324 FunctionTypes.clear(DerivedTypes);
1325 PointerTypes.clear(DerivedTypes);
1326 StructTypes.clear(DerivedTypes);
1327 ArrayTypes.clear(DerivedTypes);
1328 PackedTypes.clear(DerivedTypes);
1330 for(std::vector<Type *>::iterator I = DerivedTypes.begin(),
1331 E = DerivedTypes.end(); I != E; ++I)
1332 (*I)->ContainedTys.clear();
1333 for(std::vector<Type *>::iterator I = DerivedTypes.begin(),
1334 E = DerivedTypes.end(); I != E; ++I)
1336 DerivedTypes.clear();