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/ParameterAttributes.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"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/Debug.h"
29 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
30 // created and later destroyed, all in an effort to make sure that there is only
31 // a single canonical version of a type.
33 // #define DEBUG_MERGE_TYPES 1
35 AbstractTypeUser::~AbstractTypeUser() {}
38 //===----------------------------------------------------------------------===//
39 // Type PATypeHolder Implementation
40 //===----------------------------------------------------------------------===//
42 /// get - This implements the forwarding part of the union-find algorithm for
43 /// abstract types. Before every access to the Type*, we check to see if the
44 /// type we are pointing to is forwarding to a new type. If so, we drop our
45 /// reference to the type.
47 Type* PATypeHolder::get() const {
48 const Type *NewTy = Ty->getForwardedType();
49 if (!NewTy) return const_cast<Type*>(Ty);
50 return *const_cast<PATypeHolder*>(this) = NewTy;
53 //===----------------------------------------------------------------------===//
54 // Type Class Implementation
55 //===----------------------------------------------------------------------===//
57 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
58 // for types as they are needed. Because resolution of types must invalidate
59 // all of the abstract type descriptions, we keep them in a seperate map to make
61 static ManagedStatic<std::map<const Type*,
62 std::string> > ConcreteTypeDescriptions;
63 static ManagedStatic<std::map<const Type*,
64 std::string> > AbstractTypeDescriptions;
66 Type::Type(const char *Name, TypeID id)
67 : ID(id), Abstract(false), SubclassData(0), RefCount(0), ForwardType(0),
68 NumContainedTys(0), ContainedTys(0) {
69 assert(Name && Name[0] && "Should use other ctor if no name!");
70 (*ConcreteTypeDescriptions)[this] = Name;
73 /// Because of the way Type subclasses are allocated, this function is necessary
74 /// to use the correct kind of "delete" operator to deallocate the Type object.
75 /// Some type objects (FunctionTy, StructTy) allocate additional space after
76 /// the space for their derived type to hold the contained types array of
77 /// PATypeHandles. Using this allocation scheme means all the PATypeHandles are
78 /// allocated with the type object, decreasing allocations and eliminating the
79 /// need for a std::vector to be used in the Type class itself.
80 /// @brief Type destruction function
81 void Type::destroy() const {
83 // Structures and Functions allocate their contained types past the end of
84 // the type object itself. These need to be destroyed differently than the
86 if (isa<FunctionType>(this) || isa<StructType>(this)) {
87 // First, make sure we destruct any PATypeHandles allocated by these
88 // subclasses. They must be manually destructed.
89 for (unsigned i = 0; i < NumContainedTys; ++i)
90 ContainedTys[i].PATypeHandle::~PATypeHandle();
92 // Now call the destructor for the subclass directly because we're going
93 // to delete this as an array of char.
94 if (isa<FunctionType>(this))
95 ((FunctionType*)this)->FunctionType::~FunctionType();
97 ((StructType*)this)->StructType::~StructType();
99 // Finally, remove the memory as an array deallocation of the chars it was
101 delete [] reinterpret_cast<const char*>(this);
106 // For all the other type subclasses, there is either no contained types or
107 // just one (all Sequentials). For Sequentials, the PATypeHandle is not
108 // allocated past the type object, its included directly in the SequentialType
109 // class. This means we can safely just do "normal" delete of this object and
110 // all the destructors that need to run will be run.
114 const Type *Type::getPrimitiveType(TypeID IDNumber) {
116 case VoidTyID : return VoidTy;
117 case FloatTyID : return FloatTy;
118 case DoubleTyID: return DoubleTy;
119 case LabelTyID : return LabelTy;
125 const Type *Type::getVAArgsPromotedType() const {
126 if (ID == IntegerTyID && getSubclassData() < 32)
127 return Type::Int32Ty;
128 else if (ID == FloatTyID)
129 return Type::DoubleTy;
134 /// isFPOrFPVector - Return true if this is a FP type or a vector of FP types.
136 bool Type::isFPOrFPVector() const {
137 if (ID == Type::FloatTyID || ID == Type::DoubleTyID) return true;
138 if (ID != Type::VectorTyID) return false;
140 return cast<VectorType>(this)->getElementType()->isFloatingPoint();
143 // canLosslesllyBitCastTo - Return true if this type can be converted to
144 // 'Ty' without any reinterpretation of bits. For example, uint to int.
146 bool Type::canLosslesslyBitCastTo(const Type *Ty) const {
147 // Identity cast means no change so return true
151 // They are not convertible unless they are at least first class types
152 if (!this->isFirstClassType() || !Ty->isFirstClassType())
155 // Vector -> Vector conversions are always lossless if the two vector types
156 // have the same size, otherwise not.
157 if (const VectorType *thisPTy = dyn_cast<VectorType>(this))
158 if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
159 return thisPTy->getBitWidth() == thatPTy->getBitWidth();
161 // At this point we have only various mismatches of the first class types
162 // remaining and ptr->ptr. Just select the lossless conversions. Everything
163 // else is not lossless.
164 if (isa<PointerType>(this))
165 return isa<PointerType>(Ty);
166 return false; // Other types have no identity values
169 unsigned Type::getPrimitiveSizeInBits() const {
170 switch (getTypeID()) {
171 case Type::FloatTyID: return 32;
172 case Type::DoubleTyID: return 64;
173 case Type::IntegerTyID: return cast<IntegerType>(this)->getBitWidth();
174 case Type::VectorTyID: return cast<VectorType>(this)->getBitWidth();
179 /// isSizedDerivedType - Derived types like structures and arrays are sized
180 /// iff all of the members of the type are sized as well. Since asking for
181 /// their size is relatively uncommon, move this operation out of line.
182 bool Type::isSizedDerivedType() const {
183 if (isa<IntegerType>(this))
186 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
187 return ATy->getElementType()->isSized();
189 if (const VectorType *PTy = dyn_cast<VectorType>(this))
190 return PTy->getElementType()->isSized();
192 if (!isa<StructType>(this))
195 // Okay, our struct is sized if all of the elements are...
196 for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
197 if (!(*I)->isSized())
203 /// getForwardedTypeInternal - This method is used to implement the union-find
204 /// algorithm for when a type is being forwarded to another type.
205 const Type *Type::getForwardedTypeInternal() const {
206 assert(ForwardType && "This type is not being forwarded to another type!");
208 // Check to see if the forwarded type has been forwarded on. If so, collapse
209 // the forwarding links.
210 const Type *RealForwardedType = ForwardType->getForwardedType();
211 if (!RealForwardedType)
212 return ForwardType; // No it's not forwarded again
214 // Yes, it is forwarded again. First thing, add the reference to the new
216 if (RealForwardedType->isAbstract())
217 cast<DerivedType>(RealForwardedType)->addRef();
219 // Now drop the old reference. This could cause ForwardType to get deleted.
220 cast<DerivedType>(ForwardType)->dropRef();
222 // Return the updated type.
223 ForwardType = RealForwardedType;
227 void Type::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
230 void Type::typeBecameConcrete(const DerivedType *AbsTy) {
235 // getTypeDescription - This is a recursive function that walks a type hierarchy
236 // calculating the description for a type.
238 static std::string getTypeDescription(const Type *Ty,
239 std::vector<const Type *> &TypeStack) {
240 if (isa<OpaqueType>(Ty)) { // Base case for the recursion
241 std::map<const Type*, std::string>::iterator I =
242 AbstractTypeDescriptions->lower_bound(Ty);
243 if (I != AbstractTypeDescriptions->end() && I->first == Ty)
245 std::string Desc = "opaque";
246 AbstractTypeDescriptions->insert(std::make_pair(Ty, Desc));
250 if (!Ty->isAbstract()) { // Base case for the recursion
251 std::map<const Type*, std::string>::iterator I =
252 ConcreteTypeDescriptions->find(Ty);
253 if (I != ConcreteTypeDescriptions->end()) return I->second;
256 // Check to see if the Type is already on the stack...
257 unsigned Slot = 0, CurSize = TypeStack.size();
258 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
260 // This is another base case for the recursion. In this case, we know
261 // that we have looped back to a type that we have previously visited.
262 // Generate the appropriate upreference to handle this.
265 return "\\" + utostr(CurSize-Slot); // Here's the upreference
267 // Recursive case: derived types...
269 TypeStack.push_back(Ty); // Add us to the stack..
271 switch (Ty->getTypeID()) {
272 case Type::IntegerTyID: {
273 const IntegerType *ITy = cast<IntegerType>(Ty);
274 Result = "i" + utostr(ITy->getBitWidth());
277 case Type::FunctionTyID: {
278 const FunctionType *FTy = cast<FunctionType>(Ty);
281 Result += getTypeDescription(FTy->getReturnType(), TypeStack) + " (";
283 const ParamAttrsList *Attrs = FTy->getParamAttrs();
284 for (FunctionType::param_iterator I = FTy->param_begin(),
285 E = FTy->param_end(); I != E; ++I) {
286 if (I != FTy->param_begin())
288 if (Attrs && Attrs->getParamAttrs(Idx) != ParamAttr::None)
289 Result += Attrs->getParamAttrsTextByIndex(Idx);
291 Result += getTypeDescription(*I, TypeStack);
293 if (FTy->isVarArg()) {
294 if (FTy->getNumParams()) Result += ", ";
298 if (Attrs && Attrs->getParamAttrs(0) != ParamAttr::None) {
299 Result += " " + Attrs->getParamAttrsTextByIndex(0);
303 case Type::PackedStructTyID:
304 case Type::StructTyID: {
305 const StructType *STy = cast<StructType>(Ty);
310 for (StructType::element_iterator I = STy->element_begin(),
311 E = STy->element_end(); I != E; ++I) {
312 if (I != STy->element_begin())
314 Result += getTypeDescription(*I, TypeStack);
321 case Type::PointerTyID: {
322 const PointerType *PTy = cast<PointerType>(Ty);
323 Result = getTypeDescription(PTy->getElementType(), TypeStack) + " *";
326 case Type::ArrayTyID: {
327 const ArrayType *ATy = cast<ArrayType>(Ty);
328 unsigned NumElements = ATy->getNumElements();
330 Result += utostr(NumElements) + " x ";
331 Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
334 case Type::VectorTyID: {
335 const VectorType *PTy = cast<VectorType>(Ty);
336 unsigned NumElements = PTy->getNumElements();
338 Result += utostr(NumElements) + " x ";
339 Result += getTypeDescription(PTy->getElementType(), TypeStack) + ">";
344 assert(0 && "Unhandled type in getTypeDescription!");
347 TypeStack.pop_back(); // Remove self from stack...
354 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
356 std::map<const Type*, std::string>::iterator I = Map.find(Ty);
357 if (I != Map.end()) return I->second;
359 std::vector<const Type *> TypeStack;
360 std::string Result = getTypeDescription(Ty, TypeStack);
361 return Map[Ty] = Result;
365 const std::string &Type::getDescription() const {
367 return getOrCreateDesc(*AbstractTypeDescriptions, this);
369 return getOrCreateDesc(*ConcreteTypeDescriptions, this);
373 bool StructType::indexValid(const Value *V) const {
374 // Structure indexes require 32-bit integer constants.
375 if (V->getType() == Type::Int32Ty)
376 if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
377 return CU->getZExtValue() < NumContainedTys;
381 // getTypeAtIndex - Given an index value into the type, return the type of the
382 // element. For a structure type, this must be a constant value...
384 const Type *StructType::getTypeAtIndex(const Value *V) const {
385 assert(indexValid(V) && "Invalid structure index!");
386 unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
387 return ContainedTys[Idx];
390 //===----------------------------------------------------------------------===//
391 // Primitive 'Type' data
392 //===----------------------------------------------------------------------===//
394 const Type *Type::VoidTy = new Type("void", Type::VoidTyID);
395 const Type *Type::FloatTy = new Type("float", Type::FloatTyID);
396 const Type *Type::DoubleTy = new Type("double", Type::DoubleTyID);
397 const Type *Type::LabelTy = new Type("label", Type::LabelTyID);
400 struct BuiltinIntegerType : public IntegerType {
401 BuiltinIntegerType(unsigned W) : IntegerType(W) {}
404 const IntegerType *Type::Int1Ty = new BuiltinIntegerType(1);
405 const IntegerType *Type::Int8Ty = new BuiltinIntegerType(8);
406 const IntegerType *Type::Int16Ty = new BuiltinIntegerType(16);
407 const IntegerType *Type::Int32Ty = new BuiltinIntegerType(32);
408 const IntegerType *Type::Int64Ty = new BuiltinIntegerType(64);
411 //===----------------------------------------------------------------------===//
412 // Derived Type Constructors
413 //===----------------------------------------------------------------------===//
415 FunctionType::FunctionType(const Type *Result,
416 const std::vector<const Type*> &Params,
417 bool IsVarArgs, ParamAttrsList *Attrs)
418 : DerivedType(FunctionTyID), isVarArgs(IsVarArgs), ParamAttrs(Attrs) {
419 ContainedTys = reinterpret_cast<PATypeHandle*>(this+1);
420 NumContainedTys = Params.size() + 1; // + 1 for result type
421 assert((Result->isFirstClassType() || Result == Type::VoidTy ||
422 isa<OpaqueType>(Result)) &&
423 "LLVM functions cannot return aggregates");
424 bool isAbstract = Result->isAbstract();
425 new (&ContainedTys[0]) PATypeHandle(Result, this);
427 for (unsigned i = 0; i != Params.size(); ++i) {
428 assert((Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])) &&
429 "Function arguments must be value types!");
430 new (&ContainedTys[i+1]) PATypeHandle(Params[i],this);
431 isAbstract |= Params[i]->isAbstract();
434 // Calculate whether or not this type is abstract
435 setAbstract(isAbstract);
438 StructType::StructType(const std::vector<const Type*> &Types, bool isPacked)
439 : CompositeType(StructTyID) {
440 ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
441 NumContainedTys = Types.size();
442 setSubclassData(isPacked);
443 bool isAbstract = false;
444 for (unsigned i = 0; i < Types.size(); ++i) {
445 assert(Types[i] != Type::VoidTy && "Void type for structure field!!");
446 new (&ContainedTys[i]) PATypeHandle(Types[i], this);
447 isAbstract |= Types[i]->isAbstract();
450 // Calculate whether or not this type is abstract
451 setAbstract(isAbstract);
454 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
455 : SequentialType(ArrayTyID, ElType) {
458 // Calculate whether or not this type is abstract
459 setAbstract(ElType->isAbstract());
462 VectorType::VectorType(const Type *ElType, unsigned NumEl)
463 : SequentialType(VectorTyID, ElType) {
465 setAbstract(ElType->isAbstract());
466 assert(NumEl > 0 && "NumEl of a VectorType must be greater than 0");
467 assert((ElType->isInteger() || ElType->isFloatingPoint() ||
468 isa<OpaqueType>(ElType)) &&
469 "Elements of a VectorType must be a primitive type");
474 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
475 // Calculate whether or not this type is abstract
476 setAbstract(E->isAbstract());
479 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
481 #ifdef DEBUG_MERGE_TYPES
482 DOUT << "Derived new type: " << *this << "\n";
486 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
487 // another (more concrete) type, we must eliminate all references to other
488 // types, to avoid some circular reference problems.
489 void DerivedType::dropAllTypeUses() {
490 if (NumContainedTys != 0) {
491 // The type must stay abstract. To do this, we insert a pointer to a type
492 // that will never get resolved, thus will always be abstract.
493 static Type *AlwaysOpaqueTy = OpaqueType::get();
494 static PATypeHolder Holder(AlwaysOpaqueTy);
495 ContainedTys[0] = AlwaysOpaqueTy;
497 // Change the rest of the types to be Int32Ty's. It doesn't matter what we
498 // pick so long as it doesn't point back to this type. We choose something
499 // concrete to avoid overhead for adding to AbstracTypeUser lists and stuff.
500 for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
501 ContainedTys[i] = Type::Int32Ty;
507 /// TypePromotionGraph and graph traits - this is designed to allow us to do
508 /// efficient SCC processing of type graphs. This is the exact same as
509 /// GraphTraits<Type*>, except that we pretend that concrete types have no
510 /// children to avoid processing them.
511 struct TypePromotionGraph {
513 TypePromotionGraph(Type *T) : Ty(T) {}
517 template <> struct GraphTraits<TypePromotionGraph> {
518 typedef Type NodeType;
519 typedef Type::subtype_iterator ChildIteratorType;
521 static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
522 static inline ChildIteratorType child_begin(NodeType *N) {
524 return N->subtype_begin();
525 else // No need to process children of concrete types.
526 return N->subtype_end();
528 static inline ChildIteratorType child_end(NodeType *N) {
529 return N->subtype_end();
535 // PromoteAbstractToConcrete - This is a recursive function that walks a type
536 // graph calculating whether or not a type is abstract.
538 void Type::PromoteAbstractToConcrete() {
539 if (!isAbstract()) return;
541 scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
542 scc_iterator<TypePromotionGraph> SE = scc_end (TypePromotionGraph(this));
544 for (; SI != SE; ++SI) {
545 std::vector<Type*> &SCC = *SI;
547 // Concrete types are leaves in the tree. Since an SCC will either be all
548 // abstract or all concrete, we only need to check one type.
549 if (SCC[0]->isAbstract()) {
550 if (isa<OpaqueType>(SCC[0]))
551 return; // Not going to be concrete, sorry.
553 // If all of the children of all of the types in this SCC are concrete,
554 // then this SCC is now concrete as well. If not, neither this SCC, nor
555 // any parent SCCs will be concrete, so we might as well just exit.
556 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
557 for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
558 E = SCC[i]->subtype_end(); CI != E; ++CI)
559 if ((*CI)->isAbstract())
560 // If the child type is in our SCC, it doesn't make the entire SCC
561 // abstract unless there is a non-SCC abstract type.
562 if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
563 return; // Not going to be concrete, sorry.
565 // Okay, we just discovered this whole SCC is now concrete, mark it as
567 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
568 assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
570 SCC[i]->setAbstract(false);
573 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
574 assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
575 // The type just became concrete, notify all users!
576 cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
583 //===----------------------------------------------------------------------===//
584 // Type Structural Equality Testing
585 //===----------------------------------------------------------------------===//
587 // TypesEqual - Two types are considered structurally equal if they have the
588 // same "shape": Every level and element of the types have identical primitive
589 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
590 // be pointer equals to be equivalent though. This uses an optimistic algorithm
591 // that assumes that two graphs are the same until proven otherwise.
593 static bool TypesEqual(const Type *Ty, const Type *Ty2,
594 std::map<const Type *, const Type *> &EqTypes) {
595 if (Ty == Ty2) return true;
596 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
597 if (isa<OpaqueType>(Ty))
598 return false; // Two unequal opaque types are never equal
600 std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
601 if (It != EqTypes.end() && It->first == Ty)
602 return It->second == Ty2; // Looping back on a type, check for equality
604 // Otherwise, add the mapping to the table to make sure we don't get
605 // recursion on the types...
606 EqTypes.insert(It, std::make_pair(Ty, Ty2));
608 // Two really annoying special cases that breaks an otherwise nice simple
609 // algorithm is the fact that arraytypes have sizes that differentiates types,
610 // and that function types can be varargs or not. Consider this now.
612 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
613 const IntegerType *ITy2 = cast<IntegerType>(Ty2);
614 return ITy->getBitWidth() == ITy2->getBitWidth();
615 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
616 return TypesEqual(PTy->getElementType(),
617 cast<PointerType>(Ty2)->getElementType(), EqTypes);
618 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
619 const StructType *STy2 = cast<StructType>(Ty2);
620 if (STy->getNumElements() != STy2->getNumElements()) return false;
621 if (STy->isPacked() != STy2->isPacked()) return false;
622 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
623 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
626 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
627 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
628 return ATy->getNumElements() == ATy2->getNumElements() &&
629 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
630 } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
631 const VectorType *PTy2 = cast<VectorType>(Ty2);
632 return PTy->getNumElements() == PTy2->getNumElements() &&
633 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
634 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
635 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
636 if (FTy->isVarArg() != FTy2->isVarArg() ||
637 FTy->getNumParams() != FTy2->getNumParams() ||
638 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
640 const ParamAttrsList *Attrs1 = FTy->getParamAttrs();
641 const ParamAttrsList *Attrs2 = FTy2->getParamAttrs();
642 if ((!Attrs1 && Attrs2 && !Attrs2->empty()) ||
643 (!Attrs2 && Attrs1 && !Attrs1->empty()) ||
644 (Attrs1 && Attrs2 && (Attrs1->size() != Attrs2->size() ||
645 (Attrs1->size() > 0 &&
646 Attrs1->getParamAttrs(0) != Attrs2->getParamAttrs(0)))))
654 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
655 if (PAL1.getParamAttrs(i+1) != PAL2.getParamAttrs(i+1))
657 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
662 assert(0 && "Unknown derived type!");
667 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
668 std::map<const Type *, const Type *> EqTypes;
669 return TypesEqual(Ty, Ty2, EqTypes);
672 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
673 // TargetTy in the type graph. We know that Ty is an abstract type, so if we
674 // ever reach a non-abstract type, we know that we don't need to search the
676 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
677 std::set<const Type*> &VisitedTypes) {
678 if (TargetTy == CurTy) return true;
679 if (!CurTy->isAbstract()) return false;
681 if (!VisitedTypes.insert(CurTy).second)
682 return false; // Already been here.
684 for (Type::subtype_iterator I = CurTy->subtype_begin(),
685 E = CurTy->subtype_end(); I != E; ++I)
686 if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
691 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
692 std::set<const Type*> &VisitedTypes) {
693 if (TargetTy == CurTy) return true;
695 if (!VisitedTypes.insert(CurTy).second)
696 return false; // Already been here.
698 for (Type::subtype_iterator I = CurTy->subtype_begin(),
699 E = CurTy->subtype_end(); I != E; ++I)
700 if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
705 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
707 static bool TypeHasCycleThroughItself(const Type *Ty) {
708 std::set<const Type*> VisitedTypes;
710 if (Ty->isAbstract()) { // Optimized case for abstract types.
711 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
713 if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
716 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
718 if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
724 /// getSubElementHash - Generate a hash value for all of the SubType's of this
725 /// type. The hash value is guaranteed to be zero if any of the subtypes are
726 /// an opaque type. Otherwise we try to mix them in as well as possible, but do
727 /// not look at the subtype's subtype's.
728 static unsigned getSubElementHash(const Type *Ty) {
729 unsigned HashVal = 0;
730 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
733 const Type *SubTy = I->get();
734 HashVal += SubTy->getTypeID();
735 switch (SubTy->getTypeID()) {
737 case Type::OpaqueTyID: return 0; // Opaque -> hash = 0 no matter what.
738 case Type::IntegerTyID:
739 HashVal ^= (cast<IntegerType>(SubTy)->getBitWidth() << 3);
741 case Type::FunctionTyID:
742 HashVal ^= cast<FunctionType>(SubTy)->getNumParams()*2 +
743 cast<FunctionType>(SubTy)->isVarArg();
745 case Type::ArrayTyID:
746 HashVal ^= cast<ArrayType>(SubTy)->getNumElements();
748 case Type::VectorTyID:
749 HashVal ^= cast<VectorType>(SubTy)->getNumElements();
751 case Type::StructTyID:
752 HashVal ^= cast<StructType>(SubTy)->getNumElements();
756 return HashVal ? HashVal : 1; // Do not return zero unless opaque subty.
759 //===----------------------------------------------------------------------===//
760 // Derived Type Factory Functions
761 //===----------------------------------------------------------------------===//
766 /// TypesByHash - Keep track of types by their structure hash value. Note
767 /// that we only keep track of types that have cycles through themselves in
770 std::multimap<unsigned, PATypeHolder> TypesByHash;
773 void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
774 std::multimap<unsigned, PATypeHolder>::iterator I =
775 TypesByHash.lower_bound(Hash);
776 for (; I != TypesByHash.end() && I->first == Hash; ++I) {
777 if (I->second == Ty) {
778 TypesByHash.erase(I);
783 // This must be do to an opaque type that was resolved. Switch down to hash
785 assert(Hash && "Didn't find type entry!");
786 RemoveFromTypesByHash(0, Ty);
789 /// TypeBecameConcrete - When Ty gets a notification that TheType just became
790 /// concrete, drop uses and make Ty non-abstract if we should.
791 void TypeBecameConcrete(DerivedType *Ty, const DerivedType *TheType) {
792 // If the element just became concrete, remove 'ty' from the abstract
793 // type user list for the type. Do this for as many times as Ty uses
795 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
797 if (I->get() == TheType)
798 TheType->removeAbstractTypeUser(Ty);
800 // If the type is currently thought to be abstract, rescan all of our
801 // subtypes to see if the type has just become concrete! Note that this
802 // may send out notifications to AbstractTypeUsers that types become
804 if (Ty->isAbstract())
805 Ty->PromoteAbstractToConcrete();
811 // TypeMap - Make sure that only one instance of a particular type may be
812 // created on any given run of the compiler... note that this involves updating
813 // our map if an abstract type gets refined somehow.
816 template<class ValType, class TypeClass>
817 class TypeMap : public TypeMapBase {
818 std::map<ValType, PATypeHolder> Map;
820 typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
821 ~TypeMap() { print("ON EXIT"); }
823 inline TypeClass *get(const ValType &V) {
824 iterator I = Map.find(V);
825 return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
828 inline void add(const ValType &V, TypeClass *Ty) {
829 Map.insert(std::make_pair(V, Ty));
831 // If this type has a cycle, remember it.
832 TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
836 /// RefineAbstractType - This method is called after we have merged a type
837 /// with another one. We must now either merge the type away with
838 /// some other type or reinstall it in the map with it's new configuration.
839 void RefineAbstractType(TypeClass *Ty, const DerivedType *OldType,
840 const Type *NewType) {
841 #ifdef DEBUG_MERGE_TYPES
842 DOUT << "RefineAbstractType(" << (void*)OldType << "[" << *OldType
843 << "], " << (void*)NewType << " [" << *NewType << "])\n";
846 // Otherwise, we are changing one subelement type into another. Clearly the
847 // OldType must have been abstract, making us abstract.
848 assert(Ty->isAbstract() && "Refining a non-abstract type!");
849 assert(OldType != NewType);
851 // Make a temporary type holder for the type so that it doesn't disappear on
852 // us when we erase the entry from the map.
853 PATypeHolder TyHolder = Ty;
855 // The old record is now out-of-date, because one of the children has been
856 // updated. Remove the obsolete entry from the map.
857 unsigned NumErased = Map.erase(ValType::get(Ty));
858 assert(NumErased && "Element not found!");
860 // Remember the structural hash for the type before we start hacking on it,
861 // in case we need it later.
862 unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
864 // Find the type element we are refining... and change it now!
865 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i)
866 if (Ty->ContainedTys[i] == OldType)
867 Ty->ContainedTys[i] = NewType;
868 unsigned NewTypeHash = ValType::hashTypeStructure(Ty);
870 // If there are no cycles going through this node, we can do a simple,
871 // efficient lookup in the map, instead of an inefficient nasty linear
873 if (!TypeHasCycleThroughItself(Ty)) {
874 typename std::map<ValType, PATypeHolder>::iterator I;
877 tie(I, Inserted) = Map.insert(std::make_pair(ValType::get(Ty), Ty));
879 // Refined to a different type altogether?
880 RemoveFromTypesByHash(OldTypeHash, Ty);
882 // We already have this type in the table. Get rid of the newly refined
884 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
885 Ty->refineAbstractTypeTo(NewTy);
889 // Now we check to see if there is an existing entry in the table which is
890 // structurally identical to the newly refined type. If so, this type
891 // gets refined to the pre-existing type.
893 std::multimap<unsigned, PATypeHolder>::iterator I, E, Entry;
894 tie(I, E) = TypesByHash.equal_range(NewTypeHash);
896 for (; I != E; ++I) {
897 if (I->second == Ty) {
898 // Remember the position of the old type if we see it in our scan.
901 if (TypesEqual(Ty, I->second)) {
902 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
904 // Remove the old entry form TypesByHash. If the hash values differ
905 // now, remove it from the old place. Otherwise, continue scanning
906 // withing this hashcode to reduce work.
907 if (NewTypeHash != OldTypeHash) {
908 RemoveFromTypesByHash(OldTypeHash, Ty);
911 // Find the location of Ty in the TypesByHash structure if we
912 // haven't seen it already.
913 while (I->second != Ty) {
915 assert(I != E && "Structure doesn't contain type??");
919 TypesByHash.erase(Entry);
921 Ty->refineAbstractTypeTo(NewTy);
927 // If there is no existing type of the same structure, we reinsert an
928 // updated record into the map.
929 Map.insert(std::make_pair(ValType::get(Ty), Ty));
932 // If the hash codes differ, update TypesByHash
933 if (NewTypeHash != OldTypeHash) {
934 RemoveFromTypesByHash(OldTypeHash, Ty);
935 TypesByHash.insert(std::make_pair(NewTypeHash, Ty));
938 // If the type is currently thought to be abstract, rescan all of our
939 // subtypes to see if the type has just become concrete! Note that this
940 // may send out notifications to AbstractTypeUsers that types become
942 if (Ty->isAbstract())
943 Ty->PromoteAbstractToConcrete();
946 void print(const char *Arg) const {
947 #ifdef DEBUG_MERGE_TYPES
948 DOUT << "TypeMap<>::" << Arg << " table contents:\n";
950 for (typename std::map<ValType, PATypeHolder>::const_iterator I
951 = Map.begin(), E = Map.end(); I != E; ++I)
952 DOUT << " " << (++i) << ". " << (void*)I->second.get() << " "
953 << *I->second.get() << "\n";
957 void dump() const { print("dump output"); }
962 //===----------------------------------------------------------------------===//
963 // Function Type Factory and Value Class...
966 //===----------------------------------------------------------------------===//
967 // Integer Type Factory...
970 class IntegerValType {
973 IntegerValType(uint16_t numbits) : bits(numbits) {}
975 static IntegerValType get(const IntegerType *Ty) {
976 return IntegerValType(Ty->getBitWidth());
979 static unsigned hashTypeStructure(const IntegerType *Ty) {
980 return (unsigned)Ty->getBitWidth();
983 inline bool operator<(const IntegerValType &IVT) const {
984 return bits < IVT.bits;
989 static ManagedStatic<TypeMap<IntegerValType, IntegerType> > IntegerTypes;
991 const IntegerType *IntegerType::get(unsigned NumBits) {
992 assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
993 assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
995 // Check for the built-in integer types
997 case 1: return cast<IntegerType>(Type::Int1Ty);
998 case 8: return cast<IntegerType>(Type::Int8Ty);
999 case 16: return cast<IntegerType>(Type::Int16Ty);
1000 case 32: return cast<IntegerType>(Type::Int32Ty);
1001 case 64: return cast<IntegerType>(Type::Int64Ty);
1006 IntegerValType IVT(NumBits);
1007 IntegerType *ITy = IntegerTypes->get(IVT);
1008 if (ITy) return ITy; // Found a match, return it!
1010 // Value not found. Derive a new type!
1011 ITy = new IntegerType(NumBits);
1012 IntegerTypes->add(IVT, ITy);
1014 #ifdef DEBUG_MERGE_TYPES
1015 DOUT << "Derived new type: " << *ITy << "\n";
1020 bool IntegerType::isPowerOf2ByteWidth() const {
1021 unsigned BitWidth = getBitWidth();
1022 return (BitWidth > 7) && isPowerOf2_32(BitWidth);
1025 APInt IntegerType::getMask() const {
1026 return APInt::getAllOnesValue(getBitWidth());
1029 // FunctionValType - Define a class to hold the key that goes into the TypeMap
1032 class FunctionValType {
1034 std::vector<const Type*> ArgTypes;
1035 const ParamAttrsList *ParamAttrs;
1038 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
1039 bool IVA, const ParamAttrsList *attrs)
1040 : RetTy(ret), ParamAttrs(attrs), isVarArg(IVA) {
1041 for (unsigned i = 0; i < args.size(); ++i)
1042 ArgTypes.push_back(args[i]);
1045 static FunctionValType get(const FunctionType *FT);
1047 static unsigned hashTypeStructure(const FunctionType *FT) {
1048 unsigned Result = FT->getNumParams()*64 + FT->isVarArg();
1049 if (FT->getParamAttrs())
1050 Result += FT->getParamAttrs()->size()*2;
1054 inline bool operator<(const FunctionValType &MTV) const {
1055 if (RetTy < MTV.RetTy) return true;
1056 if (RetTy > MTV.RetTy) return false;
1057 if (isVarArg < MTV.isVarArg) return true;
1058 if (isVarArg > MTV.isVarArg) return false;
1059 if (ArgTypes < MTV.ArgTypes) return true;
1060 if (ArgTypes > MTV.ArgTypes) return false;
1063 return *ParamAttrs < *MTV.ParamAttrs;
1064 else if (ParamAttrs->empty())
1068 else if (MTV.ParamAttrs)
1069 if (MTV.ParamAttrs->empty())
1078 // Define the actual map itself now...
1079 static ManagedStatic<TypeMap<FunctionValType, FunctionType> > FunctionTypes;
1081 FunctionValType FunctionValType::get(const FunctionType *FT) {
1082 // Build up a FunctionValType
1083 std::vector<const Type *> ParamTypes;
1084 ParamTypes.reserve(FT->getNumParams());
1085 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1086 ParamTypes.push_back(FT->getParamType(i));
1087 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg(),
1088 FT->getParamAttrs());
1092 // FunctionType::get - The factory function for the FunctionType class...
1093 FunctionType *FunctionType::get(const Type *ReturnType,
1094 const std::vector<const Type*> &Params,
1096 ParamAttrsList *Attrs) {
1098 FunctionValType VT(ReturnType, Params, isVarArg, Attrs);
1099 FunctionType *MT = FunctionTypes->get(VT);
1101 delete Attrs; // not needed any more
1106 MT = (FunctionType*) new char[sizeof(FunctionType) +
1107 sizeof(PATypeHandle)*(Params.size()+1)];
1108 new (MT) FunctionType(ReturnType, Params, isVarArg, Attrs);
1109 FunctionTypes->add(VT, MT);
1111 #ifdef DEBUG_MERGE_TYPES
1112 DOUT << "Derived new type: " << MT << "\n";
1117 FunctionType::~FunctionType() {
1121 bool FunctionType::isStructReturn() const {
1123 return ParamAttrs->paramHasAttr(1, ParamAttr::StructRet);
1127 //===----------------------------------------------------------------------===//
1128 // Array Type Factory...
1131 class ArrayValType {
1135 ArrayValType(const Type *val, uint64_t sz) : ValTy(val), Size(sz) {}
1137 static ArrayValType get(const ArrayType *AT) {
1138 return ArrayValType(AT->getElementType(), AT->getNumElements());
1141 static unsigned hashTypeStructure(const ArrayType *AT) {
1142 return (unsigned)AT->getNumElements();
1145 inline bool operator<(const ArrayValType &MTV) const {
1146 if (Size < MTV.Size) return true;
1147 return Size == MTV.Size && ValTy < MTV.ValTy;
1151 static ManagedStatic<TypeMap<ArrayValType, ArrayType> > ArrayTypes;
1154 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
1155 assert(ElementType && "Can't get array of null types!");
1157 ArrayValType AVT(ElementType, NumElements);
1158 ArrayType *AT = ArrayTypes->get(AVT);
1159 if (AT) return AT; // Found a match, return it!
1161 // Value not found. Derive a new type!
1162 ArrayTypes->add(AVT, AT = new ArrayType(ElementType, NumElements));
1164 #ifdef DEBUG_MERGE_TYPES
1165 DOUT << "Derived new type: " << *AT << "\n";
1171 //===----------------------------------------------------------------------===//
1172 // Vector Type Factory...
1175 class VectorValType {
1179 VectorValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
1181 static VectorValType get(const VectorType *PT) {
1182 return VectorValType(PT->getElementType(), PT->getNumElements());
1185 static unsigned hashTypeStructure(const VectorType *PT) {
1186 return PT->getNumElements();
1189 inline bool operator<(const VectorValType &MTV) const {
1190 if (Size < MTV.Size) return true;
1191 return Size == MTV.Size && ValTy < MTV.ValTy;
1195 static ManagedStatic<TypeMap<VectorValType, VectorType> > VectorTypes;
1198 VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) {
1199 assert(ElementType && "Can't get packed of null types!");
1200 assert(isPowerOf2_32(NumElements) && "Vector length should be a power of 2!");
1202 VectorValType PVT(ElementType, NumElements);
1203 VectorType *PT = VectorTypes->get(PVT);
1204 if (PT) return PT; // Found a match, return it!
1206 // Value not found. Derive a new type!
1207 VectorTypes->add(PVT, PT = new VectorType(ElementType, NumElements));
1209 #ifdef DEBUG_MERGE_TYPES
1210 DOUT << "Derived new type: " << *PT << "\n";
1215 //===----------------------------------------------------------------------===//
1216 // Struct Type Factory...
1220 // StructValType - Define a class to hold the key that goes into the TypeMap
1222 class StructValType {
1223 std::vector<const Type*> ElTypes;
1226 StructValType(const std::vector<const Type*> &args, bool isPacked)
1227 : ElTypes(args), packed(isPacked) {}
1229 static StructValType get(const StructType *ST) {
1230 std::vector<const Type *> ElTypes;
1231 ElTypes.reserve(ST->getNumElements());
1232 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
1233 ElTypes.push_back(ST->getElementType(i));
1235 return StructValType(ElTypes, ST->isPacked());
1238 static unsigned hashTypeStructure(const StructType *ST) {
1239 return ST->getNumElements();
1242 inline bool operator<(const StructValType &STV) const {
1243 if (ElTypes < STV.ElTypes) return true;
1244 else if (ElTypes > STV.ElTypes) return false;
1245 else return (int)packed < (int)STV.packed;
1250 static ManagedStatic<TypeMap<StructValType, StructType> > StructTypes;
1252 StructType *StructType::get(const std::vector<const Type*> &ETypes,
1254 StructValType STV(ETypes, isPacked);
1255 StructType *ST = StructTypes->get(STV);
1258 // Value not found. Derive a new type!
1259 ST = (StructType*) new char[sizeof(StructType) +
1260 sizeof(PATypeHandle) * ETypes.size()];
1261 new (ST) StructType(ETypes, isPacked);
1262 StructTypes->add(STV, ST);
1264 #ifdef DEBUG_MERGE_TYPES
1265 DOUT << "Derived new type: " << *ST << "\n";
1272 //===----------------------------------------------------------------------===//
1273 // Pointer Type Factory...
1276 // PointerValType - Define a class to hold the key that goes into the TypeMap
1279 class PointerValType {
1282 PointerValType(const Type *val) : ValTy(val) {}
1284 static PointerValType get(const PointerType *PT) {
1285 return PointerValType(PT->getElementType());
1288 static unsigned hashTypeStructure(const PointerType *PT) {
1289 return getSubElementHash(PT);
1292 bool operator<(const PointerValType &MTV) const {
1293 return ValTy < MTV.ValTy;
1298 static ManagedStatic<TypeMap<PointerValType, PointerType> > PointerTypes;
1300 PointerType *PointerType::get(const Type *ValueType) {
1301 assert(ValueType && "Can't get a pointer to <null> type!");
1302 assert(ValueType != Type::VoidTy &&
1303 "Pointer to void is not valid, use sbyte* instead!");
1304 assert(ValueType != Type::LabelTy && "Pointer to label is not valid!");
1305 PointerValType PVT(ValueType);
1307 PointerType *PT = PointerTypes->get(PVT);
1310 // Value not found. Derive a new type!
1311 PointerTypes->add(PVT, PT = new PointerType(ValueType));
1313 #ifdef DEBUG_MERGE_TYPES
1314 DOUT << "Derived new type: " << *PT << "\n";
1319 //===----------------------------------------------------------------------===//
1320 // Derived Type Refinement Functions
1321 //===----------------------------------------------------------------------===//
1323 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1324 // no longer has a handle to the type. This function is called primarily by
1325 // the PATypeHandle class. When there are no users of the abstract type, it
1326 // is annihilated, because there is no way to get a reference to it ever again.
1328 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
1329 // Search from back to front because we will notify users from back to
1330 // front. Also, it is likely that there will be a stack like behavior to
1331 // users that register and unregister users.
1334 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1335 assert(i != 0 && "AbstractTypeUser not in user list!");
1337 --i; // Convert to be in range 0 <= i < size()
1338 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1340 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1342 #ifdef DEBUG_MERGE_TYPES
1343 DOUT << " remAbstractTypeUser[" << (void*)this << ", "
1344 << *this << "][" << i << "] User = " << U << "\n";
1347 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1348 #ifdef DEBUG_MERGE_TYPES
1349 DOUT << "DELETEing unused abstract type: <" << *this
1350 << ">[" << (void*)this << "]" << "\n";
1356 // refineAbstractTypeTo - This function is used when it is discovered that
1357 // the 'this' abstract type is actually equivalent to the NewType specified.
1358 // This causes all users of 'this' to switch to reference the more concrete type
1359 // NewType and for 'this' to be deleted.
1361 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1362 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1363 assert(this != NewType && "Can't refine to myself!");
1364 assert(ForwardType == 0 && "This type has already been refined!");
1366 // The descriptions may be out of date. Conservatively clear them all!
1367 AbstractTypeDescriptions->clear();
1369 #ifdef DEBUG_MERGE_TYPES
1370 DOUT << "REFINING abstract type [" << (void*)this << " "
1371 << *this << "] to [" << (void*)NewType << " "
1372 << *NewType << "]!\n";
1375 // Make sure to put the type to be refined to into a holder so that if IT gets
1376 // refined, that we will not continue using a dead reference...
1378 PATypeHolder NewTy(NewType);
1380 // Any PATypeHolders referring to this type will now automatically forward to
1381 // the type we are resolved to.
1382 ForwardType = NewType;
1383 if (NewType->isAbstract())
1384 cast<DerivedType>(NewType)->addRef();
1386 // Add a self use of the current type so that we don't delete ourself until
1387 // after the function exits.
1389 PATypeHolder CurrentTy(this);
1391 // To make the situation simpler, we ask the subclass to remove this type from
1392 // the type map, and to replace any type uses with uses of non-abstract types.
1393 // This dramatically limits the amount of recursive type trouble we can find
1397 // Iterate over all of the uses of this type, invoking callback. Each user
1398 // should remove itself from our use list automatically. We have to check to
1399 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1400 // will not cause users to drop off of the use list. If we resolve to ourself
1403 while (!AbstractTypeUsers.empty() && NewTy != this) {
1404 AbstractTypeUser *User = AbstractTypeUsers.back();
1406 unsigned OldSize = AbstractTypeUsers.size();
1407 #ifdef DEBUG_MERGE_TYPES
1408 DOUT << " REFINING user " << OldSize-1 << "[" << (void*)User
1409 << "] of abstract type [" << (void*)this << " "
1410 << *this << "] to [" << (void*)NewTy.get() << " "
1411 << *NewTy << "]!\n";
1413 User->refineAbstractType(this, NewTy);
1415 assert(AbstractTypeUsers.size() != OldSize &&
1416 "AbsTyUser did not remove self from user list!");
1419 // If we were successful removing all users from the type, 'this' will be
1420 // deleted when the last PATypeHolder is destroyed or updated from this type.
1421 // This may occur on exit of this function, as the CurrentTy object is
1425 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1426 // the current type has transitioned from being abstract to being concrete.
1428 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1429 #ifdef DEBUG_MERGE_TYPES
1430 DOUT << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1433 unsigned OldSize = AbstractTypeUsers.size();
1434 while (!AbstractTypeUsers.empty()) {
1435 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1436 ATU->typeBecameConcrete(this);
1438 assert(AbstractTypeUsers.size() < OldSize-- &&
1439 "AbstractTypeUser did not remove itself from the use list!");
1443 // refineAbstractType - Called when a contained type is found to be more
1444 // concrete - this could potentially change us from an abstract type to a
1447 void FunctionType::refineAbstractType(const DerivedType *OldType,
1448 const Type *NewType) {
1449 FunctionTypes->RefineAbstractType(this, OldType, NewType);
1452 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1453 FunctionTypes->TypeBecameConcrete(this, AbsTy);
1457 // refineAbstractType - Called when a contained type is found to be more
1458 // concrete - this could potentially change us from an abstract type to a
1461 void ArrayType::refineAbstractType(const DerivedType *OldType,
1462 const Type *NewType) {
1463 ArrayTypes->RefineAbstractType(this, OldType, NewType);
1466 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1467 ArrayTypes->TypeBecameConcrete(this, AbsTy);
1470 // refineAbstractType - Called when a contained type is found to be more
1471 // concrete - this could potentially change us from an abstract type to a
1474 void VectorType::refineAbstractType(const DerivedType *OldType,
1475 const Type *NewType) {
1476 VectorTypes->RefineAbstractType(this, OldType, NewType);
1479 void VectorType::typeBecameConcrete(const DerivedType *AbsTy) {
1480 VectorTypes->TypeBecameConcrete(this, AbsTy);
1483 // refineAbstractType - Called when a contained type is found to be more
1484 // concrete - this could potentially change us from an abstract type to a
1487 void StructType::refineAbstractType(const DerivedType *OldType,
1488 const Type *NewType) {
1489 StructTypes->RefineAbstractType(this, OldType, NewType);
1492 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1493 StructTypes->TypeBecameConcrete(this, AbsTy);
1496 // refineAbstractType - Called when a contained type is found to be more
1497 // concrete - this could potentially change us from an abstract type to a
1500 void PointerType::refineAbstractType(const DerivedType *OldType,
1501 const Type *NewType) {
1502 PointerTypes->RefineAbstractType(this, OldType, NewType);
1505 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1506 PointerTypes->TypeBecameConcrete(this, AbsTy);
1509 bool SequentialType::indexValid(const Value *V) const {
1510 if (const IntegerType *IT = dyn_cast<IntegerType>(V->getType()))
1511 return IT->getBitWidth() == 32 || IT->getBitWidth() == 64;
1516 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1518 OS << "<null> value!\n";
1524 std::ostream &operator<<(std::ostream &OS, const Type &T) {