1 //===-- Type.cpp - Implement the Type class -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Type class for the VMCore library.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/DerivedTypes.h"
15 #include "llvm/Constants.h"
16 #include "llvm/Assembly/Writer.h"
17 #include "llvm/ADT/DepthFirstIterator.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/SCCIterator.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/System/Mutex.h"
28 #include "llvm/System/RWMutex.h"
29 #include "llvm/System/Threading.h"
34 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
35 // created and later destroyed, all in an effort to make sure that there is only
36 // a single canonical version of a type.
38 // #define DEBUG_MERGE_TYPES 1
40 AbstractTypeUser::~AbstractTypeUser() {}
43 //===----------------------------------------------------------------------===//
44 // Type Class Implementation
45 //===----------------------------------------------------------------------===//
47 // Lock used for guarding access to the type maps.
48 static ManagedStatic<sys::SmartMutex<true> > TypeMapLock;
50 // Recursive lock used for guarding access to AbstractTypeUsers.
51 // NOTE: The true template parameter means this will no-op when we're not in
52 // multithreaded mode.
53 static ManagedStatic<sys::SmartMutex<true> > AbstractTypeUsersLock;
55 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
56 // for types as they are needed. Because resolution of types must invalidate
57 // all of the abstract type descriptions, we keep them in a seperate map to make
59 static ManagedStatic<TypePrinting> ConcreteTypeDescriptions;
60 static ManagedStatic<TypePrinting> AbstractTypeDescriptions;
62 /// Because of the way Type subclasses are allocated, this function is necessary
63 /// to use the correct kind of "delete" operator to deallocate the Type object.
64 /// Some type objects (FunctionTy, StructTy) allocate additional space after
65 /// the space for their derived type to hold the contained types array of
66 /// PATypeHandles. Using this allocation scheme means all the PATypeHandles are
67 /// allocated with the type object, decreasing allocations and eliminating the
68 /// need for a std::vector to be used in the Type class itself.
69 /// @brief Type destruction function
70 void Type::destroy() const {
72 // Structures and Functions allocate their contained types past the end of
73 // the type object itself. These need to be destroyed differently than the
75 if (isa<FunctionType>(this) || isa<StructType>(this)) {
76 // First, make sure we destruct any PATypeHandles allocated by these
77 // subclasses. They must be manually destructed.
78 for (unsigned i = 0; i < NumContainedTys; ++i)
79 ContainedTys[i].PATypeHandle::~PATypeHandle();
81 // Now call the destructor for the subclass directly because we're going
82 // to delete this as an array of char.
83 if (isa<FunctionType>(this))
84 static_cast<const FunctionType*>(this)->FunctionType::~FunctionType();
86 static_cast<const StructType*>(this)->StructType::~StructType();
88 // Finally, remove the memory as an array deallocation of the chars it was
90 operator delete(const_cast<Type *>(this));
95 // For all the other type subclasses, there is either no contained types or
96 // just one (all Sequentials). For Sequentials, the PATypeHandle is not
97 // allocated past the type object, its included directly in the SequentialType
98 // class. This means we can safely just do "normal" delete of this object and
99 // all the destructors that need to run will be run.
103 const Type *Type::getPrimitiveType(TypeID IDNumber) {
105 case VoidTyID : return VoidTy;
106 case FloatTyID : return FloatTy;
107 case DoubleTyID : return DoubleTy;
108 case X86_FP80TyID : return X86_FP80Ty;
109 case FP128TyID : return FP128Ty;
110 case PPC_FP128TyID : return PPC_FP128Ty;
111 case LabelTyID : return LabelTy;
112 case MetadataTyID : return MetadataTy;
118 const Type *Type::getVAArgsPromotedType() const {
119 if (ID == IntegerTyID && getSubclassData() < 32)
120 return Type::Int32Ty;
121 else if (ID == FloatTyID)
122 return Type::DoubleTy;
127 /// getScalarType - If this is a vector type, return the element type,
128 /// otherwise return this.
129 const Type *Type::getScalarType() const {
130 if (const VectorType *VTy = dyn_cast<VectorType>(this))
131 return VTy->getElementType();
135 /// isIntOrIntVector - Return true if this is an integer type or a vector of
138 bool Type::isIntOrIntVector() const {
141 if (ID != Type::VectorTyID) return false;
143 return cast<VectorType>(this)->getElementType()->isInteger();
146 /// isFPOrFPVector - Return true if this is a FP type or a vector of FP types.
148 bool Type::isFPOrFPVector() const {
149 if (ID == Type::FloatTyID || ID == Type::DoubleTyID ||
150 ID == Type::FP128TyID || ID == Type::X86_FP80TyID ||
151 ID == Type::PPC_FP128TyID)
153 if (ID != Type::VectorTyID) return false;
155 return cast<VectorType>(this)->getElementType()->isFloatingPoint();
158 // canLosslesslyBitCastTo - Return true if this type can be converted to
159 // 'Ty' without any reinterpretation of bits. For example, i8* to i32*.
161 bool Type::canLosslesslyBitCastTo(const Type *Ty) const {
162 // Identity cast means no change so return true
166 // They are not convertible unless they are at least first class types
167 if (!this->isFirstClassType() || !Ty->isFirstClassType())
170 // Vector -> Vector conversions are always lossless if the two vector types
171 // have the same size, otherwise not.
172 if (const VectorType *thisPTy = dyn_cast<VectorType>(this))
173 if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
174 return thisPTy->getBitWidth() == thatPTy->getBitWidth();
176 // At this point we have only various mismatches of the first class types
177 // remaining and ptr->ptr. Just select the lossless conversions. Everything
178 // else is not lossless.
179 if (isa<PointerType>(this))
180 return isa<PointerType>(Ty);
181 return false; // Other types have no identity values
184 unsigned Type::getPrimitiveSizeInBits() const {
185 switch (getTypeID()) {
186 case Type::FloatTyID: return 32;
187 case Type::DoubleTyID: return 64;
188 case Type::X86_FP80TyID: return 80;
189 case Type::FP128TyID: return 128;
190 case Type::PPC_FP128TyID: return 128;
191 case Type::IntegerTyID: return cast<IntegerType>(this)->getBitWidth();
192 case Type::VectorTyID: return cast<VectorType>(this)->getBitWidth();
197 /// getScalarSizeInBits - If this is a vector type, return the
198 /// getPrimitiveSizeInBits value for the element type. Otherwise return the
199 /// getPrimitiveSizeInBits value for this type.
200 unsigned Type::getScalarSizeInBits() const {
201 return getScalarType()->getPrimitiveSizeInBits();
204 /// getFPMantissaWidth - Return the width of the mantissa of this type. This
205 /// is only valid on floating point types. If the FP type does not
206 /// have a stable mantissa (e.g. ppc long double), this method returns -1.
207 int Type::getFPMantissaWidth() const {
208 if (const VectorType *VTy = dyn_cast<VectorType>(this))
209 return VTy->getElementType()->getFPMantissaWidth();
210 assert(isFloatingPoint() && "Not a floating point type!");
211 if (ID == FloatTyID) return 24;
212 if (ID == DoubleTyID) return 53;
213 if (ID == X86_FP80TyID) return 64;
214 if (ID == FP128TyID) return 113;
215 assert(ID == PPC_FP128TyID && "unknown fp type");
219 /// isSizedDerivedType - Derived types like structures and arrays are sized
220 /// iff all of the members of the type are sized as well. Since asking for
221 /// their size is relatively uncommon, move this operation out of line.
222 bool Type::isSizedDerivedType() const {
223 if (isa<IntegerType>(this))
226 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
227 return ATy->getElementType()->isSized();
229 if (const VectorType *PTy = dyn_cast<VectorType>(this))
230 return PTy->getElementType()->isSized();
232 if (!isa<StructType>(this))
235 // Okay, our struct is sized if all of the elements are...
236 for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
237 if (!(*I)->isSized())
243 /// getForwardedTypeInternal - This method is used to implement the union-find
244 /// algorithm for when a type is being forwarded to another type.
245 const Type *Type::getForwardedTypeInternal() const {
246 assert(ForwardType && "This type is not being forwarded to another type!");
248 // Check to see if the forwarded type has been forwarded on. If so, collapse
249 // the forwarding links.
250 const Type *RealForwardedType = ForwardType->getForwardedType();
251 if (!RealForwardedType)
252 return ForwardType; // No it's not forwarded again
254 // Yes, it is forwarded again. First thing, add the reference to the new
256 if (RealForwardedType->isAbstract())
257 cast<DerivedType>(RealForwardedType)->addRef();
259 // Now drop the old reference. This could cause ForwardType to get deleted.
260 cast<DerivedType>(ForwardType)->dropRef();
262 // Return the updated type.
263 ForwardType = RealForwardedType;
267 void Type::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
268 llvm_unreachable("Attempting to refine a derived type!");
270 void Type::typeBecameConcrete(const DerivedType *AbsTy) {
271 llvm_unreachable("DerivedType is already a concrete type!");
275 std::string Type::getDescription() const {
277 isAbstract() ? *AbstractTypeDescriptions : *ConcreteTypeDescriptions;
280 raw_string_ostream DescOS(DescStr);
281 Map.print(this, DescOS);
286 bool StructType::indexValid(const Value *V) const {
287 // Structure indexes require 32-bit integer constants.
288 if (V->getType() == Type::Int32Ty)
289 if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
290 return indexValid(CU->getZExtValue());
294 bool StructType::indexValid(unsigned V) const {
295 return V < NumContainedTys;
298 // getTypeAtIndex - Given an index value into the type, return the type of the
299 // element. For a structure type, this must be a constant value...
301 const Type *StructType::getTypeAtIndex(const Value *V) const {
302 unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
303 return getTypeAtIndex(Idx);
306 const Type *StructType::getTypeAtIndex(unsigned Idx) const {
307 assert(indexValid(Idx) && "Invalid structure index!");
308 return ContainedTys[Idx];
311 //===----------------------------------------------------------------------===//
312 // Primitive 'Type' data
313 //===----------------------------------------------------------------------===//
315 const Type *Type::VoidTy = new Type(Type::VoidTyID);
316 const Type *Type::FloatTy = new Type(Type::FloatTyID);
317 const Type *Type::DoubleTy = new Type(Type::DoubleTyID);
318 const Type *Type::X86_FP80Ty = new Type(Type::X86_FP80TyID);
319 const Type *Type::FP128Ty = new Type(Type::FP128TyID);
320 const Type *Type::PPC_FP128Ty = new Type(Type::PPC_FP128TyID);
321 const Type *Type::LabelTy = new Type(Type::LabelTyID);
322 const Type *Type::MetadataTy = new Type(Type::MetadataTyID);
325 struct BuiltinIntegerType : public IntegerType {
326 explicit BuiltinIntegerType(unsigned W) : IntegerType(W) {}
329 const IntegerType *Type::Int1Ty = new BuiltinIntegerType(1);
330 const IntegerType *Type::Int8Ty = new BuiltinIntegerType(8);
331 const IntegerType *Type::Int16Ty = new BuiltinIntegerType(16);
332 const IntegerType *Type::Int32Ty = new BuiltinIntegerType(32);
333 const IntegerType *Type::Int64Ty = new BuiltinIntegerType(64);
335 //===----------------------------------------------------------------------===//
336 // Derived Type Constructors
337 //===----------------------------------------------------------------------===//
339 /// isValidReturnType - Return true if the specified type is valid as a return
341 bool FunctionType::isValidReturnType(const Type *RetTy) {
342 if (RetTy->isFirstClassType()) {
343 if (const PointerType *PTy = dyn_cast<PointerType>(RetTy))
344 return PTy->getElementType() != Type::MetadataTy;
347 if (RetTy == Type::VoidTy || RetTy == Type::MetadataTy ||
348 isa<OpaqueType>(RetTy))
351 // If this is a multiple return case, verify that each return is a first class
352 // value and that there is at least one value.
353 const StructType *SRetTy = dyn_cast<StructType>(RetTy);
354 if (SRetTy == 0 || SRetTy->getNumElements() == 0)
357 for (unsigned i = 0, e = SRetTy->getNumElements(); i != e; ++i)
358 if (!SRetTy->getElementType(i)->isFirstClassType())
363 /// isValidArgumentType - Return true if the specified type is valid as an
365 bool FunctionType::isValidArgumentType(const Type *ArgTy) {
366 if ((!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy)) ||
367 (isa<PointerType>(ArgTy) &&
368 cast<PointerType>(ArgTy)->getElementType() == Type::MetadataTy))
374 FunctionType::FunctionType(const Type *Result,
375 const std::vector<const Type*> &Params,
377 : DerivedType(FunctionTyID), isVarArgs(IsVarArgs) {
378 ContainedTys = reinterpret_cast<PATypeHandle*>(this+1);
379 NumContainedTys = Params.size() + 1; // + 1 for result type
380 assert(isValidReturnType(Result) && "invalid return type for function");
383 bool isAbstract = Result->isAbstract();
384 new (&ContainedTys[0]) PATypeHandle(Result, this);
386 for (unsigned i = 0; i != Params.size(); ++i) {
387 assert(isValidArgumentType(Params[i]) &&
388 "Not a valid type for function argument!");
389 new (&ContainedTys[i+1]) PATypeHandle(Params[i], this);
390 isAbstract |= Params[i]->isAbstract();
393 // Calculate whether or not this type is abstract
394 setAbstract(isAbstract);
397 StructType::StructType(const std::vector<const Type*> &Types, bool isPacked)
398 : CompositeType(StructTyID) {
399 ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
400 NumContainedTys = Types.size();
401 setSubclassData(isPacked);
402 bool isAbstract = false;
403 for (unsigned i = 0; i < Types.size(); ++i) {
404 assert(Types[i] && "<null> type for structure field!");
405 assert(isValidElementType(Types[i]) &&
406 "Invalid type for structure element!");
407 new (&ContainedTys[i]) PATypeHandle(Types[i], this);
408 isAbstract |= Types[i]->isAbstract();
411 // Calculate whether or not this type is abstract
412 setAbstract(isAbstract);
415 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
416 : SequentialType(ArrayTyID, ElType) {
419 // Calculate whether or not this type is abstract
420 setAbstract(ElType->isAbstract());
423 VectorType::VectorType(const Type *ElType, unsigned NumEl)
424 : SequentialType(VectorTyID, ElType) {
426 setAbstract(ElType->isAbstract());
427 assert(NumEl > 0 && "NumEl of a VectorType must be greater than 0");
428 assert(isValidElementType(ElType) &&
429 "Elements of a VectorType must be a primitive type");
434 PointerType::PointerType(const Type *E, unsigned AddrSpace)
435 : SequentialType(PointerTyID, E) {
436 AddressSpace = AddrSpace;
437 // Calculate whether or not this type is abstract
438 setAbstract(E->isAbstract());
441 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
443 #ifdef DEBUG_MERGE_TYPES
444 DOUT << "Derived new type: " << *this << "\n";
448 void PATypeHolder::destroy() {
452 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
453 // another (more concrete) type, we must eliminate all references to other
454 // types, to avoid some circular reference problems.
455 void DerivedType::dropAllTypeUses() {
456 if (NumContainedTys != 0) {
457 // The type must stay abstract. To do this, we insert a pointer to a type
458 // that will never get resolved, thus will always be abstract.
459 static Type *AlwaysOpaqueTy = 0;
460 static PATypeHolder* Holder = 0;
461 Type *tmp = AlwaysOpaqueTy;
462 if (llvm_is_multithreaded()) {
465 llvm_acquire_global_lock();
466 tmp = AlwaysOpaqueTy;
468 tmp = OpaqueType::get();
469 PATypeHolder* tmp2 = new PATypeHolder(AlwaysOpaqueTy);
471 AlwaysOpaqueTy = tmp;
475 llvm_release_global_lock();
478 AlwaysOpaqueTy = OpaqueType::get();
479 Holder = new PATypeHolder(AlwaysOpaqueTy);
482 ContainedTys[0] = AlwaysOpaqueTy;
484 // Change the rest of the types to be Int32Ty's. It doesn't matter what we
485 // pick so long as it doesn't point back to this type. We choose something
486 // concrete to avoid overhead for adding to AbstracTypeUser lists and stuff.
487 for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
488 ContainedTys[i] = Type::Int32Ty;
495 /// TypePromotionGraph and graph traits - this is designed to allow us to do
496 /// efficient SCC processing of type graphs. This is the exact same as
497 /// GraphTraits<Type*>, except that we pretend that concrete types have no
498 /// children to avoid processing them.
499 struct TypePromotionGraph {
501 TypePromotionGraph(Type *T) : Ty(T) {}
507 template <> struct GraphTraits<TypePromotionGraph> {
508 typedef Type NodeType;
509 typedef Type::subtype_iterator ChildIteratorType;
511 static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
512 static inline ChildIteratorType child_begin(NodeType *N) {
514 return N->subtype_begin();
515 else // No need to process children of concrete types.
516 return N->subtype_end();
518 static inline ChildIteratorType child_end(NodeType *N) {
519 return N->subtype_end();
525 // PromoteAbstractToConcrete - This is a recursive function that walks a type
526 // graph calculating whether or not a type is abstract.
528 void Type::PromoteAbstractToConcrete() {
529 if (!isAbstract()) return;
531 scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
532 scc_iterator<TypePromotionGraph> SE = scc_end (TypePromotionGraph(this));
534 for (; SI != SE; ++SI) {
535 std::vector<Type*> &SCC = *SI;
537 // Concrete types are leaves in the tree. Since an SCC will either be all
538 // abstract or all concrete, we only need to check one type.
539 if (SCC[0]->isAbstract()) {
540 if (isa<OpaqueType>(SCC[0]))
541 return; // Not going to be concrete, sorry.
543 // If all of the children of all of the types in this SCC are concrete,
544 // then this SCC is now concrete as well. If not, neither this SCC, nor
545 // any parent SCCs will be concrete, so we might as well just exit.
546 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
547 for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
548 E = SCC[i]->subtype_end(); CI != E; ++CI)
549 if ((*CI)->isAbstract())
550 // If the child type is in our SCC, it doesn't make the entire SCC
551 // abstract unless there is a non-SCC abstract type.
552 if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
553 return; // Not going to be concrete, sorry.
555 // Okay, we just discovered this whole SCC is now concrete, mark it as
557 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
558 assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
560 SCC[i]->setAbstract(false);
563 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
564 assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
565 // The type just became concrete, notify all users!
566 cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
573 //===----------------------------------------------------------------------===//
574 // Type Structural Equality Testing
575 //===----------------------------------------------------------------------===//
577 // TypesEqual - Two types are considered structurally equal if they have the
578 // same "shape": Every level and element of the types have identical primitive
579 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
580 // be pointer equals to be equivalent though. This uses an optimistic algorithm
581 // that assumes that two graphs are the same until proven otherwise.
583 static bool TypesEqual(const Type *Ty, const Type *Ty2,
584 std::map<const Type *, const Type *> &EqTypes) {
585 if (Ty == Ty2) return true;
586 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
587 if (isa<OpaqueType>(Ty))
588 return false; // Two unequal opaque types are never equal
590 std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
591 if (It != EqTypes.end())
592 return It->second == Ty2; // Looping back on a type, check for equality
594 // Otherwise, add the mapping to the table to make sure we don't get
595 // recursion on the types...
596 EqTypes.insert(It, std::make_pair(Ty, Ty2));
598 // Two really annoying special cases that breaks an otherwise nice simple
599 // algorithm is the fact that arraytypes have sizes that differentiates types,
600 // and that function types can be varargs or not. Consider this now.
602 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
603 const IntegerType *ITy2 = cast<IntegerType>(Ty2);
604 return ITy->getBitWidth() == ITy2->getBitWidth();
605 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
606 const PointerType *PTy2 = cast<PointerType>(Ty2);
607 return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
608 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
609 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
610 const StructType *STy2 = cast<StructType>(Ty2);
611 if (STy->getNumElements() != STy2->getNumElements()) return false;
612 if (STy->isPacked() != STy2->isPacked()) return false;
613 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
614 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
617 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
618 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
619 return ATy->getNumElements() == ATy2->getNumElements() &&
620 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
621 } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
622 const VectorType *PTy2 = cast<VectorType>(Ty2);
623 return PTy->getNumElements() == PTy2->getNumElements() &&
624 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
625 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
626 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
627 if (FTy->isVarArg() != FTy2->isVarArg() ||
628 FTy->getNumParams() != FTy2->getNumParams() ||
629 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
631 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
632 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
637 llvm_unreachable("Unknown derived type!");
642 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
643 std::map<const Type *, const Type *> EqTypes;
644 return TypesEqual(Ty, Ty2, EqTypes);
647 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
648 // TargetTy in the type graph. We know that Ty is an abstract type, so if we
649 // ever reach a non-abstract type, we know that we don't need to search the
651 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
652 SmallPtrSet<const Type*, 128> &VisitedTypes) {
653 if (TargetTy == CurTy) return true;
654 if (!CurTy->isAbstract()) return false;
656 if (!VisitedTypes.insert(CurTy))
657 return false; // Already been here.
659 for (Type::subtype_iterator I = CurTy->subtype_begin(),
660 E = CurTy->subtype_end(); I != E; ++I)
661 if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
666 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
667 SmallPtrSet<const Type*, 128> &VisitedTypes) {
668 if (TargetTy == CurTy) return true;
670 if (!VisitedTypes.insert(CurTy))
671 return false; // Already been here.
673 for (Type::subtype_iterator I = CurTy->subtype_begin(),
674 E = CurTy->subtype_end(); I != E; ++I)
675 if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
680 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
682 static bool TypeHasCycleThroughItself(const Type *Ty) {
683 SmallPtrSet<const Type*, 128> VisitedTypes;
685 if (Ty->isAbstract()) { // Optimized case for abstract types.
686 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
688 if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
691 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
693 if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
699 /// getSubElementHash - Generate a hash value for all of the SubType's of this
700 /// type. The hash value is guaranteed to be zero if any of the subtypes are
701 /// an opaque type. Otherwise we try to mix them in as well as possible, but do
702 /// not look at the subtype's subtype's.
703 static unsigned getSubElementHash(const Type *Ty) {
704 unsigned HashVal = 0;
705 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
708 const Type *SubTy = I->get();
709 HashVal += SubTy->getTypeID();
710 switch (SubTy->getTypeID()) {
712 case Type::OpaqueTyID: return 0; // Opaque -> hash = 0 no matter what.
713 case Type::IntegerTyID:
714 HashVal ^= (cast<IntegerType>(SubTy)->getBitWidth() << 3);
716 case Type::FunctionTyID:
717 HashVal ^= cast<FunctionType>(SubTy)->getNumParams()*2 +
718 cast<FunctionType>(SubTy)->isVarArg();
720 case Type::ArrayTyID:
721 HashVal ^= cast<ArrayType>(SubTy)->getNumElements();
723 case Type::VectorTyID:
724 HashVal ^= cast<VectorType>(SubTy)->getNumElements();
726 case Type::StructTyID:
727 HashVal ^= cast<StructType>(SubTy)->getNumElements();
729 case Type::PointerTyID:
730 HashVal ^= cast<PointerType>(SubTy)->getAddressSpace();
734 return HashVal ? HashVal : 1; // Do not return zero unless opaque subty.
737 //===----------------------------------------------------------------------===//
738 // Derived Type Factory Functions
739 //===----------------------------------------------------------------------===//
744 /// TypesByHash - Keep track of types by their structure hash value. Note
745 /// that we only keep track of types that have cycles through themselves in
748 std::multimap<unsigned, PATypeHolder> TypesByHash;
752 // PATypeHolder won't destroy non-abstract types.
753 // We can't destroy them by simply iterating, because
754 // they may contain references to each-other.
756 for (std::multimap<unsigned, PATypeHolder>::iterator I
757 = TypesByHash.begin(), E = TypesByHash.end(); I != E; ++I) {
758 Type *Ty = const_cast<Type*>(I->second.Ty);
760 // We can't invoke destroy or delete, because the type may
761 // contain references to already freed types.
762 // So we have to destruct the object the ugly way.
764 Ty->AbstractTypeUsers.clear();
765 static_cast<const Type*>(Ty)->Type::~Type();
772 void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
773 std::multimap<unsigned, PATypeHolder>::iterator I =
774 TypesByHash.lower_bound(Hash);
775 for (; I != TypesByHash.end() && I->first == Hash; ++I) {
776 if (I->second == Ty) {
777 TypesByHash.erase(I);
782 // This must be do to an opaque type that was resolved. Switch down to hash
784 assert(Hash && "Didn't find type entry!");
785 RemoveFromTypesByHash(0, Ty);
788 /// TypeBecameConcrete - When Ty gets a notification that TheType just became
789 /// concrete, drop uses and make Ty non-abstract if we should.
790 void TypeBecameConcrete(DerivedType *Ty, const DerivedType *TheType) {
791 // If the element just became concrete, remove 'ty' from the abstract
792 // type user list for the type. Do this for as many times as Ty uses
794 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
796 if (I->get() == TheType)
797 TheType->removeAbstractTypeUser(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! Note that this
801 // may send out notifications to AbstractTypeUsers that types become
803 if (Ty->isAbstract())
804 Ty->PromoteAbstractToConcrete();
810 // TypeMap - Make sure that only one instance of a particular type may be
811 // created on any given run of the compiler... note that this involves updating
812 // our map if an abstract type gets refined somehow.
815 template<class ValType, class TypeClass>
816 class TypeMap : public TypeMapBase {
817 std::map<ValType, PATypeHolder> Map;
819 typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
820 ~TypeMap() { print("ON EXIT"); }
822 inline TypeClass *get(const ValType &V) {
823 iterator I = Map.find(V);
824 return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
827 inline void add(const ValType &V, TypeClass *Ty) {
828 Map.insert(std::make_pair(V, Ty));
830 // If this type has a cycle, remember it.
831 TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
835 /// RefineAbstractType - This method is called after we have merged a type
836 /// with another one. We must now either merge the type away with
837 /// some other type or reinstall it in the map with it's new configuration.
838 void RefineAbstractType(TypeClass *Ty, const DerivedType *OldType,
839 const Type *NewType) {
840 #ifdef DEBUG_MERGE_TYPES
841 DOUT << "RefineAbstractType(" << (void*)OldType << "[" << *OldType
842 << "], " << (void*)NewType << " [" << *NewType << "])\n";
845 // Otherwise, we are changing one subelement type into another. Clearly the
846 // OldType must have been abstract, making us abstract.
847 assert(Ty->isAbstract() && "Refining a non-abstract type!");
848 assert(OldType != NewType);
850 // Make a temporary type holder for the type so that it doesn't disappear on
851 // us when we erase the entry from the map.
852 PATypeHolder TyHolder = Ty;
854 // The old record is now out-of-date, because one of the children has been
855 // updated. Remove the obsolete entry from the map.
856 unsigned NumErased = Map.erase(ValType::get(Ty));
857 assert(NumErased && "Element not found!"); NumErased = NumErased;
859 // Remember the structural hash for the type before we start hacking on it,
860 // in case we need it later.
861 unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
863 // Find the type element we are refining... and change it now!
864 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i)
865 if (Ty->ContainedTys[i] == OldType)
866 Ty->ContainedTys[i] = NewType;
867 unsigned NewTypeHash = ValType::hashTypeStructure(Ty);
869 // If there are no cycles going through this node, we can do a simple,
870 // efficient lookup in the map, instead of an inefficient nasty linear
872 if (!TypeHasCycleThroughItself(Ty)) {
873 typename std::map<ValType, PATypeHolder>::iterator I;
876 tie(I, Inserted) = Map.insert(std::make_pair(ValType::get(Ty), Ty));
878 // Refined to a different type altogether?
879 RemoveFromTypesByHash(OldTypeHash, Ty);
881 // We already have this type in the table. Get rid of the newly refined
883 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
884 Ty->unlockedRefineAbstractTypeTo(NewTy);
888 // Now we check to see if there is an existing entry in the table which is
889 // structurally identical to the newly refined type. If so, this type
890 // gets refined to the pre-existing type.
892 std::multimap<unsigned, PATypeHolder>::iterator I, E, Entry;
893 tie(I, E) = TypesByHash.equal_range(NewTypeHash);
895 for (; I != E; ++I) {
896 if (I->second == Ty) {
897 // Remember the position of the old type if we see it in our scan.
900 if (TypesEqual(Ty, I->second)) {
901 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
903 // Remove the old entry form TypesByHash. If the hash values differ
904 // now, remove it from the old place. Otherwise, continue scanning
905 // withing this hashcode to reduce work.
906 if (NewTypeHash != OldTypeHash) {
907 RemoveFromTypesByHash(OldTypeHash, Ty);
910 // Find the location of Ty in the TypesByHash structure if we
911 // haven't seen it already.
912 while (I->second != Ty) {
914 assert(I != E && "Structure doesn't contain type??");
918 TypesByHash.erase(Entry);
920 Ty->unlockedRefineAbstractTypeTo(NewTy);
926 // If there is no existing type of the same structure, we reinsert an
927 // updated record into the map.
928 Map.insert(std::make_pair(ValType::get(Ty), Ty));
931 // If the hash codes differ, update TypesByHash
932 if (NewTypeHash != OldTypeHash) {
933 RemoveFromTypesByHash(OldTypeHash, Ty);
934 TypesByHash.insert(std::make_pair(NewTypeHash, Ty));
937 // If the type is currently thought to be abstract, rescan all of our
938 // subtypes to see if the type has just become concrete! Note that this
939 // may send out notifications to AbstractTypeUsers that types become
941 if (Ty->isAbstract())
942 Ty->PromoteAbstractToConcrete();
945 void print(const char *Arg) const {
946 #ifdef DEBUG_MERGE_TYPES
947 DOUT << "TypeMap<>::" << Arg << " table contents:\n";
949 for (typename std::map<ValType, PATypeHolder>::const_iterator I
950 = Map.begin(), E = Map.end(); I != E; ++I)
951 DOUT << " " << (++i) << ". " << (void*)I->second.get() << " "
952 << *I->second.get() << "\n";
956 void dump() const { print("dump output"); }
961 //===----------------------------------------------------------------------===//
962 // Function Type Factory and Value Class...
965 //===----------------------------------------------------------------------===//
966 // Integer Type Factory...
969 class IntegerValType {
972 IntegerValType(uint16_t numbits) : bits(numbits) {}
974 static IntegerValType get(const IntegerType *Ty) {
975 return IntegerValType(Ty->getBitWidth());
978 static unsigned hashTypeStructure(const IntegerType *Ty) {
979 return (unsigned)Ty->getBitWidth();
982 inline bool operator<(const IntegerValType &IVT) const {
983 return bits < IVT.bits;
988 static ManagedStatic<TypeMap<IntegerValType, IntegerType> > IntegerTypes;
990 const IntegerType *IntegerType::get(unsigned NumBits) {
991 assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
992 assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
994 // Check for the built-in integer types
996 case 1: return cast<IntegerType>(Type::Int1Ty);
997 case 8: return cast<IntegerType>(Type::Int8Ty);
998 case 16: return cast<IntegerType>(Type::Int16Ty);
999 case 32: return cast<IntegerType>(Type::Int32Ty);
1000 case 64: return cast<IntegerType>(Type::Int64Ty);
1005 IntegerValType IVT(NumBits);
1006 IntegerType *ITy = 0;
1008 // First, see if the type is already in the table, for which
1009 // a reader lock suffices.
1010 sys::SmartScopedLock<true> L(*TypeMapLock);
1011 ITy = IntegerTypes->get(IVT);
1014 // Value not found. Derive a new type!
1015 ITy = new IntegerType(NumBits);
1016 IntegerTypes->add(IVT, ITy);
1018 #ifdef DEBUG_MERGE_TYPES
1019 DOUT << "Derived new type: " << *ITy << "\n";
1024 bool IntegerType::isPowerOf2ByteWidth() const {
1025 unsigned BitWidth = getBitWidth();
1026 return (BitWidth > 7) && isPowerOf2_32(BitWidth);
1029 APInt IntegerType::getMask() const {
1030 return APInt::getAllOnesValue(getBitWidth());
1033 // FunctionValType - Define a class to hold the key that goes into the TypeMap
1036 class FunctionValType {
1038 std::vector<const Type*> ArgTypes;
1041 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
1042 bool isVA) : RetTy(ret), ArgTypes(args), isVarArg(isVA) {}
1044 static FunctionValType get(const FunctionType *FT);
1046 static unsigned hashTypeStructure(const FunctionType *FT) {
1047 unsigned Result = FT->getNumParams()*2 + FT->isVarArg();
1051 inline bool operator<(const FunctionValType &MTV) const {
1052 if (RetTy < MTV.RetTy) return true;
1053 if (RetTy > MTV.RetTy) return false;
1054 if (isVarArg < MTV.isVarArg) return true;
1055 if (isVarArg > MTV.isVarArg) return false;
1056 if (ArgTypes < MTV.ArgTypes) return true;
1057 if (ArgTypes > MTV.ArgTypes) return false;
1063 // Define the actual map itself now...
1064 static ManagedStatic<TypeMap<FunctionValType, FunctionType> > FunctionTypes;
1066 FunctionValType FunctionValType::get(const FunctionType *FT) {
1067 // Build up a FunctionValType
1068 std::vector<const Type *> ParamTypes;
1069 ParamTypes.reserve(FT->getNumParams());
1070 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1071 ParamTypes.push_back(FT->getParamType(i));
1072 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
1076 // FunctionType::get - The factory function for the FunctionType class...
1077 FunctionType *FunctionType::get(const Type *ReturnType,
1078 const std::vector<const Type*> &Params,
1080 FunctionValType VT(ReturnType, Params, isVarArg);
1081 FunctionType *FT = 0;
1083 sys::SmartScopedLock<true> L(*TypeMapLock);
1084 FT = FunctionTypes->get(VT);
1087 FT = (FunctionType*) operator new(sizeof(FunctionType) +
1088 sizeof(PATypeHandle)*(Params.size()+1));
1089 new (FT) FunctionType(ReturnType, Params, isVarArg);
1090 FunctionTypes->add(VT, FT);
1093 #ifdef DEBUG_MERGE_TYPES
1094 DOUT << "Derived new type: " << FT << "\n";
1099 //===----------------------------------------------------------------------===//
1100 // Array Type Factory...
1103 class ArrayValType {
1107 ArrayValType(const Type *val, uint64_t sz) : ValTy(val), Size(sz) {}
1109 static ArrayValType get(const ArrayType *AT) {
1110 return ArrayValType(AT->getElementType(), AT->getNumElements());
1113 static unsigned hashTypeStructure(const ArrayType *AT) {
1114 return (unsigned)AT->getNumElements();
1117 inline bool operator<(const ArrayValType &MTV) const {
1118 if (Size < MTV.Size) return true;
1119 return Size == MTV.Size && ValTy < MTV.ValTy;
1124 static ManagedStatic<TypeMap<ArrayValType, ArrayType> > ArrayTypes;
1126 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
1127 assert(ElementType && "Can't get array of <null> types!");
1128 assert(isValidElementType(ElementType) && "Invalid type for array element!");
1130 ArrayValType AVT(ElementType, NumElements);
1133 sys::SmartScopedLock<true> L(*TypeMapLock);
1134 AT = ArrayTypes->get(AVT);
1137 // Value not found. Derive a new type!
1138 ArrayTypes->add(AVT, AT = new ArrayType(ElementType, NumElements));
1140 #ifdef DEBUG_MERGE_TYPES
1141 DOUT << "Derived new type: " << *AT << "\n";
1146 bool ArrayType::isValidElementType(const Type *ElemTy) {
1147 if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy ||
1148 ElemTy == Type::MetadataTy)
1151 if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
1152 if (PTy->getElementType() == Type::MetadataTy)
1159 //===----------------------------------------------------------------------===//
1160 // Vector Type Factory...
1163 class VectorValType {
1167 VectorValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
1169 static VectorValType get(const VectorType *PT) {
1170 return VectorValType(PT->getElementType(), PT->getNumElements());
1173 static unsigned hashTypeStructure(const VectorType *PT) {
1174 return PT->getNumElements();
1177 inline bool operator<(const VectorValType &MTV) const {
1178 if (Size < MTV.Size) return true;
1179 return Size == MTV.Size && ValTy < MTV.ValTy;
1184 static ManagedStatic<TypeMap<VectorValType, VectorType> > VectorTypes;
1186 VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) {
1187 assert(ElementType && "Can't get vector of <null> types!");
1189 VectorValType PVT(ElementType, NumElements);
1192 sys::SmartScopedLock<true> L(*TypeMapLock);
1193 PT = VectorTypes->get(PVT);
1196 VectorTypes->add(PVT, PT = new VectorType(ElementType, NumElements));
1198 #ifdef DEBUG_MERGE_TYPES
1199 DOUT << "Derived new type: " << *PT << "\n";
1204 bool VectorType::isValidElementType(const Type *ElemTy) {
1205 if (ElemTy->isInteger() || ElemTy->isFloatingPoint() ||
1206 isa<OpaqueType>(ElemTy))
1212 //===----------------------------------------------------------------------===//
1213 // Struct Type Factory...
1217 // StructValType - Define a class to hold the key that goes into the TypeMap
1219 class StructValType {
1220 std::vector<const Type*> ElTypes;
1223 StructValType(const std::vector<const Type*> &args, bool isPacked)
1224 : ElTypes(args), packed(isPacked) {}
1226 static StructValType get(const StructType *ST) {
1227 std::vector<const Type *> ElTypes;
1228 ElTypes.reserve(ST->getNumElements());
1229 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
1230 ElTypes.push_back(ST->getElementType(i));
1232 return StructValType(ElTypes, ST->isPacked());
1235 static unsigned hashTypeStructure(const StructType *ST) {
1236 return ST->getNumElements();
1239 inline bool operator<(const StructValType &STV) const {
1240 if (ElTypes < STV.ElTypes) return true;
1241 else if (ElTypes > STV.ElTypes) return false;
1242 else return (int)packed < (int)STV.packed;
1247 static ManagedStatic<TypeMap<StructValType, StructType> > StructTypes;
1249 StructType *StructType::get(const std::vector<const Type*> &ETypes,
1251 StructValType STV(ETypes, isPacked);
1254 sys::SmartScopedLock<true> L(*TypeMapLock);
1255 ST = StructTypes->get(STV);
1258 // Value not found. Derive a new type!
1259 ST = (StructType*) operator new(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";
1270 StructType *StructType::get(const Type *type, ...) {
1272 std::vector<const llvm::Type*> StructFields;
1275 StructFields.push_back(type);
1276 type = va_arg(ap, llvm::Type*);
1278 return llvm::StructType::get(StructFields);
1281 bool StructType::isValidElementType(const Type *ElemTy) {
1282 if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy ||
1283 ElemTy == Type::MetadataTy)
1286 if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
1287 if (PTy->getElementType() == Type::MetadataTy)
1294 //===----------------------------------------------------------------------===//
1295 // Pointer Type Factory...
1298 // PointerValType - Define a class to hold the key that goes into the TypeMap
1301 class PointerValType {
1303 unsigned AddressSpace;
1305 PointerValType(const Type *val, unsigned as) : ValTy(val), AddressSpace(as) {}
1307 static PointerValType get(const PointerType *PT) {
1308 return PointerValType(PT->getElementType(), PT->getAddressSpace());
1311 static unsigned hashTypeStructure(const PointerType *PT) {
1312 return getSubElementHash(PT);
1315 bool operator<(const PointerValType &MTV) const {
1316 if (AddressSpace < MTV.AddressSpace) return true;
1317 return AddressSpace == MTV.AddressSpace && ValTy < MTV.ValTy;
1322 static ManagedStatic<TypeMap<PointerValType, PointerType> > PointerTypes;
1324 PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) {
1325 assert(ValueType && "Can't get a pointer to <null> type!");
1326 assert(ValueType != Type::VoidTy &&
1327 "Pointer to void is not valid, use i8* instead!");
1328 assert(isValidElementType(ValueType) && "Invalid type for pointer element!");
1329 PointerValType PVT(ValueType, AddressSpace);
1331 PointerType *PT = 0;
1333 sys::SmartScopedLock<true> L(*TypeMapLock);
1334 PT = PointerTypes->get(PVT);
1337 // Value not found. Derive a new type!
1338 PointerTypes->add(PVT, PT = new PointerType(ValueType, AddressSpace));
1340 #ifdef DEBUG_MERGE_TYPES
1341 DOUT << "Derived new type: " << *PT << "\n";
1346 PointerType *Type::getPointerTo(unsigned addrs) const {
1347 return PointerType::get(this, addrs);
1350 bool PointerType::isValidElementType(const Type *ElemTy) {
1351 if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy)
1354 if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
1355 if (PTy->getElementType() == Type::MetadataTy)
1362 //===----------------------------------------------------------------------===//
1363 // Derived Type Refinement Functions
1364 //===----------------------------------------------------------------------===//
1366 // addAbstractTypeUser - Notify an abstract type that there is a new user of
1367 // it. This function is called primarily by the PATypeHandle class.
1368 void Type::addAbstractTypeUser(AbstractTypeUser *U) const {
1369 assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
1370 AbstractTypeUsersLock->acquire();
1371 AbstractTypeUsers.push_back(U);
1372 AbstractTypeUsersLock->release();
1376 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1377 // no longer has a handle to the type. This function is called primarily by
1378 // the PATypeHandle class. When there are no users of the abstract type, it
1379 // is annihilated, because there is no way to get a reference to it ever again.
1381 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
1382 AbstractTypeUsersLock->acquire();
1384 // Search from back to front because we will notify users from back to
1385 // front. Also, it is likely that there will be a stack like behavior to
1386 // users that register and unregister users.
1389 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1390 assert(i != 0 && "AbstractTypeUser not in user list!");
1392 --i; // Convert to be in range 0 <= i < size()
1393 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1395 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1397 #ifdef DEBUG_MERGE_TYPES
1398 DOUT << " remAbstractTypeUser[" << (void*)this << ", "
1399 << *this << "][" << i << "] User = " << U << "\n";
1402 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1403 #ifdef DEBUG_MERGE_TYPES
1404 DOUT << "DELETEing unused abstract type: <" << *this
1405 << ">[" << (void*)this << "]" << "\n";
1411 AbstractTypeUsersLock->release();
1414 // unlockedRefineAbstractTypeTo - This function is used when it is discovered
1415 // that the 'this' abstract type is actually equivalent to the NewType
1416 // specified. This causes all users of 'this' to switch to reference the more
1417 // concrete type NewType and for 'this' to be deleted. Only used for internal
1420 void DerivedType::unlockedRefineAbstractTypeTo(const Type *NewType) {
1421 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1422 assert(this != NewType && "Can't refine to myself!");
1423 assert(ForwardType == 0 && "This type has already been refined!");
1425 // The descriptions may be out of date. Conservatively clear them all!
1426 if (AbstractTypeDescriptions.isConstructed())
1427 AbstractTypeDescriptions->clear();
1429 #ifdef DEBUG_MERGE_TYPES
1430 DOUT << "REFINING abstract type [" << (void*)this << " "
1431 << *this << "] to [" << (void*)NewType << " "
1432 << *NewType << "]!\n";
1435 // Make sure to put the type to be refined to into a holder so that if IT gets
1436 // refined, that we will not continue using a dead reference...
1438 PATypeHolder NewTy(NewType);
1439 // Any PATypeHolders referring to this type will now automatically forward o
1440 // the type we are resolved to.
1441 ForwardType = NewType;
1442 if (NewType->isAbstract())
1443 cast<DerivedType>(NewType)->addRef();
1445 // Add a self use of the current type so that we don't delete ourself until
1446 // after the function exits.
1448 PATypeHolder CurrentTy(this);
1450 // To make the situation simpler, we ask the subclass to remove this type from
1451 // the type map, and to replace any type uses with uses of non-abstract types.
1452 // This dramatically limits the amount of recursive type trouble we can find
1456 // Iterate over all of the uses of this type, invoking callback. Each user
1457 // should remove itself from our use list automatically. We have to check to
1458 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1459 // will not cause users to drop off of the use list. If we resolve to ourself
1462 AbstractTypeUsersLock->acquire();
1463 while (!AbstractTypeUsers.empty() && NewTy != this) {
1464 AbstractTypeUser *User = AbstractTypeUsers.back();
1466 unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1467 #ifdef DEBUG_MERGE_TYPES
1468 DOUT << " REFINING user " << OldSize-1 << "[" << (void*)User
1469 << "] of abstract type [" << (void*)this << " "
1470 << *this << "] to [" << (void*)NewTy.get() << " "
1471 << *NewTy << "]!\n";
1473 User->refineAbstractType(this, NewTy);
1475 assert(AbstractTypeUsers.size() != OldSize &&
1476 "AbsTyUser did not remove self from user list!");
1478 AbstractTypeUsersLock->release();
1480 // If we were successful removing all users from the type, 'this' will be
1481 // deleted when the last PATypeHolder is destroyed or updated from this type.
1482 // This may occur on exit of this function, as the CurrentTy object is
1486 // refineAbstractTypeTo - This function is used by external callers to notify
1487 // us that this abstract type is equivalent to another type.
1489 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1490 // All recursive calls will go through unlockedRefineAbstractTypeTo,
1491 // to avoid deadlock problems.
1492 sys::SmartScopedLock<true> L(*TypeMapLock);
1493 unlockedRefineAbstractTypeTo(NewType);
1496 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1497 // the current type has transitioned from being abstract to being concrete.
1499 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1500 #ifdef DEBUG_MERGE_TYPES
1501 DOUT << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1504 AbstractTypeUsersLock->acquire();
1505 unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1506 while (!AbstractTypeUsers.empty()) {
1507 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1508 ATU->typeBecameConcrete(this);
1510 assert(AbstractTypeUsers.size() < OldSize-- &&
1511 "AbstractTypeUser did not remove itself from the use list!");
1513 AbstractTypeUsersLock->release();
1516 // refineAbstractType - Called when a contained type is found to be more
1517 // concrete - this could potentially change us from an abstract type to a
1520 void FunctionType::refineAbstractType(const DerivedType *OldType,
1521 const Type *NewType) {
1522 FunctionTypes->RefineAbstractType(this, OldType, NewType);
1525 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1526 FunctionTypes->TypeBecameConcrete(this, AbsTy);
1530 // refineAbstractType - Called when a contained type is found to be more
1531 // concrete - this could potentially change us from an abstract type to a
1534 void ArrayType::refineAbstractType(const DerivedType *OldType,
1535 const Type *NewType) {
1536 ArrayTypes->RefineAbstractType(this, OldType, NewType);
1539 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1540 ArrayTypes->TypeBecameConcrete(this, AbsTy);
1543 // refineAbstractType - Called when a contained type is found to be more
1544 // concrete - this could potentially change us from an abstract type to a
1547 void VectorType::refineAbstractType(const DerivedType *OldType,
1548 const Type *NewType) {
1549 VectorTypes->RefineAbstractType(this, OldType, NewType);
1552 void VectorType::typeBecameConcrete(const DerivedType *AbsTy) {
1553 VectorTypes->TypeBecameConcrete(this, AbsTy);
1556 // refineAbstractType - Called when a contained type is found to be more
1557 // concrete - this could potentially change us from an abstract type to a
1560 void StructType::refineAbstractType(const DerivedType *OldType,
1561 const Type *NewType) {
1562 StructTypes->RefineAbstractType(this, OldType, NewType);
1565 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1566 StructTypes->TypeBecameConcrete(this, AbsTy);
1569 // refineAbstractType - Called when a contained type is found to be more
1570 // concrete - this could potentially change us from an abstract type to a
1573 void PointerType::refineAbstractType(const DerivedType *OldType,
1574 const Type *NewType) {
1575 PointerTypes->RefineAbstractType(this, OldType, NewType);
1578 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1579 PointerTypes->TypeBecameConcrete(this, AbsTy);
1582 bool SequentialType::indexValid(const Value *V) const {
1583 if (isa<IntegerType>(V->getType()))
1589 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1591 OS << "<null> value!\n";
1597 std::ostream &operator<<(std::ostream &OS, const Type &T) {
1602 raw_ostream &operator<<(raw_ostream &OS, const Type &T) {