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 "LLVMContextImpl.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Metadata.h"
20 #include "llvm/ADT/DepthFirstIterator.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/SCCIterator.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/System/Mutex.h"
31 #include "llvm/System/RWMutex.h"
32 #include "llvm/System/Threading.h"
37 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
38 // created and later destroyed, all in an effort to make sure that there is only
39 // a single canonical version of a type.
41 // #define DEBUG_MERGE_TYPES 1
43 AbstractTypeUser::~AbstractTypeUser() {}
46 //===----------------------------------------------------------------------===//
47 // Type Class Implementation
48 //===----------------------------------------------------------------------===//
50 // Lock used for guarding access to the type maps.
51 static ManagedStatic<sys::SmartMutex<true> > TypeMapLock;
53 // Recursive lock used for guarding access to AbstractTypeUsers.
54 // NOTE: The true template parameter means this will no-op when we're not in
55 // multithreaded mode.
56 static ManagedStatic<sys::SmartMutex<true> > AbstractTypeUsersLock;
58 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
59 // for types as they are needed. Because resolution of types must invalidate
60 // all of the abstract type descriptions, we keep them in a seperate map to make
62 static ManagedStatic<TypePrinting> ConcreteTypeDescriptions;
63 static ManagedStatic<TypePrinting> AbstractTypeDescriptions;
65 /// Because of the way Type subclasses are allocated, this function is necessary
66 /// to use the correct kind of "delete" operator to deallocate the Type object.
67 /// Some type objects (FunctionTy, StructTy) allocate additional space after
68 /// the space for their derived type to hold the contained types array of
69 /// PATypeHandles. Using this allocation scheme means all the PATypeHandles are
70 /// allocated with the type object, decreasing allocations and eliminating the
71 /// need for a std::vector to be used in the Type class itself.
72 /// @brief Type destruction function
73 void Type::destroy() const {
75 // Structures and Functions allocate their contained types past the end of
76 // the type object itself. These need to be destroyed differently than the
78 if (isa<FunctionType>(this) || isa<StructType>(this)) {
79 // First, make sure we destruct any PATypeHandles allocated by these
80 // subclasses. They must be manually destructed.
81 for (unsigned i = 0; i < NumContainedTys; ++i)
82 ContainedTys[i].PATypeHandle::~PATypeHandle();
84 // Now call the destructor for the subclass directly because we're going
85 // to delete this as an array of char.
86 if (isa<FunctionType>(this))
87 static_cast<const FunctionType*>(this)->FunctionType::~FunctionType();
89 static_cast<const StructType*>(this)->StructType::~StructType();
91 // Finally, remove the memory as an array deallocation of the chars it was
93 operator delete(const_cast<Type *>(this));
98 // For all the other type subclasses, there is either no contained types or
99 // just one (all Sequentials). For Sequentials, the PATypeHandle is not
100 // allocated past the type object, its included directly in the SequentialType
101 // class. This means we can safely just do "normal" delete of this object and
102 // all the destructors that need to run will be run.
106 const Type *Type::getPrimitiveType(TypeID IDNumber) {
108 case VoidTyID : return VoidTy;
109 case FloatTyID : return FloatTy;
110 case DoubleTyID : return DoubleTy;
111 case X86_FP80TyID : return X86_FP80Ty;
112 case FP128TyID : return FP128Ty;
113 case PPC_FP128TyID : return PPC_FP128Ty;
114 case LabelTyID : return LabelTy;
115 case MetadataTyID : return MetadataTy;
121 const Type *Type::getVAArgsPromotedType() const {
122 if (ID == IntegerTyID && getSubclassData() < 32)
123 return Type::Int32Ty;
124 else if (ID == FloatTyID)
125 return Type::DoubleTy;
130 /// getScalarType - If this is a vector type, return the element type,
131 /// otherwise return this.
132 const Type *Type::getScalarType() const {
133 if (const VectorType *VTy = dyn_cast<VectorType>(this))
134 return VTy->getElementType();
138 /// isIntOrIntVector - Return true if this is an integer type or a vector of
141 bool Type::isIntOrIntVector() const {
144 if (ID != Type::VectorTyID) return false;
146 return cast<VectorType>(this)->getElementType()->isInteger();
149 /// isFPOrFPVector - Return true if this is a FP type or a vector of FP types.
151 bool Type::isFPOrFPVector() const {
152 if (ID == Type::FloatTyID || ID == Type::DoubleTyID ||
153 ID == Type::FP128TyID || ID == Type::X86_FP80TyID ||
154 ID == Type::PPC_FP128TyID)
156 if (ID != Type::VectorTyID) return false;
158 return cast<VectorType>(this)->getElementType()->isFloatingPoint();
161 // canLosslesslyBitCastTo - Return true if this type can be converted to
162 // 'Ty' without any reinterpretation of bits. For example, i8* to i32*.
164 bool Type::canLosslesslyBitCastTo(const Type *Ty) const {
165 // Identity cast means no change so return true
169 // They are not convertible unless they are at least first class types
170 if (!this->isFirstClassType() || !Ty->isFirstClassType())
173 // Vector -> Vector conversions are always lossless if the two vector types
174 // have the same size, otherwise not.
175 if (const VectorType *thisPTy = dyn_cast<VectorType>(this))
176 if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
177 return thisPTy->getBitWidth() == thatPTy->getBitWidth();
179 // At this point we have only various mismatches of the first class types
180 // remaining and ptr->ptr. Just select the lossless conversions. Everything
181 // else is not lossless.
182 if (isa<PointerType>(this))
183 return isa<PointerType>(Ty);
184 return false; // Other types have no identity values
187 unsigned Type::getPrimitiveSizeInBits() const {
188 switch (getTypeID()) {
189 case Type::FloatTyID: return 32;
190 case Type::DoubleTyID: return 64;
191 case Type::X86_FP80TyID: return 80;
192 case Type::FP128TyID: return 128;
193 case Type::PPC_FP128TyID: return 128;
194 case Type::IntegerTyID: return cast<IntegerType>(this)->getBitWidth();
195 case Type::VectorTyID: return cast<VectorType>(this)->getBitWidth();
200 /// getScalarSizeInBits - If this is a vector type, return the
201 /// getPrimitiveSizeInBits value for the element type. Otherwise return the
202 /// getPrimitiveSizeInBits value for this type.
203 unsigned Type::getScalarSizeInBits() const {
204 return getScalarType()->getPrimitiveSizeInBits();
207 /// getFPMantissaWidth - Return the width of the mantissa of this type. This
208 /// is only valid on floating point types. If the FP type does not
209 /// have a stable mantissa (e.g. ppc long double), this method returns -1.
210 int Type::getFPMantissaWidth() const {
211 if (const VectorType *VTy = dyn_cast<VectorType>(this))
212 return VTy->getElementType()->getFPMantissaWidth();
213 assert(isFloatingPoint() && "Not a floating point type!");
214 if (ID == FloatTyID) return 24;
215 if (ID == DoubleTyID) return 53;
216 if (ID == X86_FP80TyID) return 64;
217 if (ID == FP128TyID) return 113;
218 assert(ID == PPC_FP128TyID && "unknown fp type");
222 /// isSizedDerivedType - Derived types like structures and arrays are sized
223 /// iff all of the members of the type are sized as well. Since asking for
224 /// their size is relatively uncommon, move this operation out of line.
225 bool Type::isSizedDerivedType() const {
226 if (isa<IntegerType>(this))
229 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
230 return ATy->getElementType()->isSized();
232 if (const VectorType *PTy = dyn_cast<VectorType>(this))
233 return PTy->getElementType()->isSized();
235 if (!isa<StructType>(this))
238 // Okay, our struct is sized if all of the elements are...
239 for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
240 if (!(*I)->isSized())
246 /// getForwardedTypeInternal - This method is used to implement the union-find
247 /// algorithm for when a type is being forwarded to another type.
248 const Type *Type::getForwardedTypeInternal() const {
249 assert(ForwardType && "This type is not being forwarded to another type!");
251 // Check to see if the forwarded type has been forwarded on. If so, collapse
252 // the forwarding links.
253 const Type *RealForwardedType = ForwardType->getForwardedType();
254 if (!RealForwardedType)
255 return ForwardType; // No it's not forwarded again
257 // Yes, it is forwarded again. First thing, add the reference to the new
259 if (RealForwardedType->isAbstract())
260 cast<DerivedType>(RealForwardedType)->addRef();
262 // Now drop the old reference. This could cause ForwardType to get deleted.
263 cast<DerivedType>(ForwardType)->dropRef();
265 // Return the updated type.
266 ForwardType = RealForwardedType;
270 void Type::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
271 llvm_unreachable("Attempting to refine a derived type!");
273 void Type::typeBecameConcrete(const DerivedType *AbsTy) {
274 llvm_unreachable("DerivedType is already a concrete type!");
278 std::string Type::getDescription() const {
280 isAbstract() ? *AbstractTypeDescriptions : *ConcreteTypeDescriptions;
283 raw_string_ostream DescOS(DescStr);
284 Map.print(this, DescOS);
289 bool StructType::indexValid(const Value *V) const {
290 // Structure indexes require 32-bit integer constants.
291 if (V->getType() == Type::Int32Ty)
292 if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
293 return indexValid(CU->getZExtValue());
297 bool StructType::indexValid(unsigned V) const {
298 return V < NumContainedTys;
301 // getTypeAtIndex - Given an index value into the type, return the type of the
302 // element. For a structure type, this must be a constant value...
304 const Type *StructType::getTypeAtIndex(const Value *V) const {
305 unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
306 return getTypeAtIndex(Idx);
309 const Type *StructType::getTypeAtIndex(unsigned Idx) const {
310 assert(indexValid(Idx) && "Invalid structure index!");
311 return ContainedTys[Idx];
314 //===----------------------------------------------------------------------===//
315 // Primitive 'Type' data
316 //===----------------------------------------------------------------------===//
318 const Type *Type::VoidTy = new Type(Type::VoidTyID);
319 const Type *Type::FloatTy = new Type(Type::FloatTyID);
320 const Type *Type::DoubleTy = new Type(Type::DoubleTyID);
321 const Type *Type::X86_FP80Ty = new Type(Type::X86_FP80TyID);
322 const Type *Type::FP128Ty = new Type(Type::FP128TyID);
323 const Type *Type::PPC_FP128Ty = new Type(Type::PPC_FP128TyID);
324 const Type *Type::LabelTy = new Type(Type::LabelTyID);
325 const Type *Type::MetadataTy = new Type(Type::MetadataTyID);
328 struct BuiltinIntegerType : public IntegerType {
329 explicit BuiltinIntegerType(unsigned W) : IntegerType(W) {}
332 const IntegerType *Type::Int1Ty = new BuiltinIntegerType(1);
333 const IntegerType *Type::Int8Ty = new BuiltinIntegerType(8);
334 const IntegerType *Type::Int16Ty = new BuiltinIntegerType(16);
335 const IntegerType *Type::Int32Ty = new BuiltinIntegerType(32);
336 const IntegerType *Type::Int64Ty = new BuiltinIntegerType(64);
338 //===----------------------------------------------------------------------===//
339 // Derived Type Constructors
340 //===----------------------------------------------------------------------===//
342 /// isValidReturnType - Return true if the specified type is valid as a return
344 bool FunctionType::isValidReturnType(const Type *RetTy) {
345 if (RetTy->isFirstClassType()) {
346 if (const PointerType *PTy = dyn_cast<PointerType>(RetTy))
347 return PTy->getElementType() != Type::MetadataTy;
350 if (RetTy == Type::VoidTy || RetTy == Type::MetadataTy ||
351 isa<OpaqueType>(RetTy))
354 // If this is a multiple return case, verify that each return is a first class
355 // value and that there is at least one value.
356 const StructType *SRetTy = dyn_cast<StructType>(RetTy);
357 if (SRetTy == 0 || SRetTy->getNumElements() == 0)
360 for (unsigned i = 0, e = SRetTy->getNumElements(); i != e; ++i)
361 if (!SRetTy->getElementType(i)->isFirstClassType())
366 /// isValidArgumentType - Return true if the specified type is valid as an
368 bool FunctionType::isValidArgumentType(const Type *ArgTy) {
369 if ((!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy)) ||
370 (isa<PointerType>(ArgTy) &&
371 cast<PointerType>(ArgTy)->getElementType() == Type::MetadataTy))
377 FunctionType::FunctionType(const Type *Result,
378 const std::vector<const Type*> &Params,
380 : DerivedType(FunctionTyID), isVarArgs(IsVarArgs) {
381 ContainedTys = reinterpret_cast<PATypeHandle*>(this+1);
382 NumContainedTys = Params.size() + 1; // + 1 for result type
383 assert(isValidReturnType(Result) && "invalid return type for function");
386 bool isAbstract = Result->isAbstract();
387 new (&ContainedTys[0]) PATypeHandle(Result, this);
389 for (unsigned i = 0; i != Params.size(); ++i) {
390 assert(isValidArgumentType(Params[i]) &&
391 "Not a valid type for function argument!");
392 new (&ContainedTys[i+1]) PATypeHandle(Params[i], this);
393 isAbstract |= Params[i]->isAbstract();
396 // Calculate whether or not this type is abstract
397 setAbstract(isAbstract);
400 StructType::StructType(const std::vector<const Type*> &Types, bool isPacked)
401 : CompositeType(StructTyID) {
402 ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
403 NumContainedTys = Types.size();
404 setSubclassData(isPacked);
405 bool isAbstract = false;
406 for (unsigned i = 0; i < Types.size(); ++i) {
407 assert(Types[i] && "<null> type for structure field!");
408 assert(isValidElementType(Types[i]) &&
409 "Invalid type for structure element!");
410 new (&ContainedTys[i]) PATypeHandle(Types[i], this);
411 isAbstract |= Types[i]->isAbstract();
414 // Calculate whether or not this type is abstract
415 setAbstract(isAbstract);
418 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
419 : SequentialType(ArrayTyID, ElType) {
422 // Calculate whether or not this type is abstract
423 setAbstract(ElType->isAbstract());
426 VectorType::VectorType(const Type *ElType, unsigned NumEl)
427 : SequentialType(VectorTyID, ElType) {
429 setAbstract(ElType->isAbstract());
430 assert(NumEl > 0 && "NumEl of a VectorType must be greater than 0");
431 assert(isValidElementType(ElType) &&
432 "Elements of a VectorType must be a primitive type");
437 PointerType::PointerType(const Type *E, unsigned AddrSpace)
438 : SequentialType(PointerTyID, E) {
439 AddressSpace = AddrSpace;
440 // Calculate whether or not this type is abstract
441 setAbstract(E->isAbstract());
444 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
446 #ifdef DEBUG_MERGE_TYPES
447 DOUT << "Derived new type: " << *this << "\n";
451 void PATypeHolder::destroy() {
455 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
456 // another (more concrete) type, we must eliminate all references to other
457 // types, to avoid some circular reference problems.
458 void DerivedType::dropAllTypeUses() {
459 if (NumContainedTys != 0) {
460 // The type must stay abstract. To do this, we insert a pointer to a type
461 // that will never get resolved, thus will always be abstract.
462 static Type *AlwaysOpaqueTy = 0;
463 static PATypeHolder* Holder = 0;
464 Type *tmp = AlwaysOpaqueTy;
465 if (llvm_is_multithreaded()) {
468 llvm_acquire_global_lock();
469 tmp = AlwaysOpaqueTy;
471 tmp = OpaqueType::get();
472 PATypeHolder* tmp2 = new PATypeHolder(AlwaysOpaqueTy);
474 AlwaysOpaqueTy = tmp;
478 llvm_release_global_lock();
481 AlwaysOpaqueTy = OpaqueType::get();
482 Holder = new PATypeHolder(AlwaysOpaqueTy);
485 ContainedTys[0] = AlwaysOpaqueTy;
487 // Change the rest of the types to be Int32Ty's. It doesn't matter what we
488 // pick so long as it doesn't point back to this type. We choose something
489 // concrete to avoid overhead for adding to AbstracTypeUser lists and stuff.
490 for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
491 ContainedTys[i] = Type::Int32Ty;
498 /// TypePromotionGraph and graph traits - this is designed to allow us to do
499 /// efficient SCC processing of type graphs. This is the exact same as
500 /// GraphTraits<Type*>, except that we pretend that concrete types have no
501 /// children to avoid processing them.
502 struct TypePromotionGraph {
504 TypePromotionGraph(Type *T) : Ty(T) {}
510 template <> struct GraphTraits<TypePromotionGraph> {
511 typedef Type NodeType;
512 typedef Type::subtype_iterator ChildIteratorType;
514 static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
515 static inline ChildIteratorType child_begin(NodeType *N) {
517 return N->subtype_begin();
518 else // No need to process children of concrete types.
519 return N->subtype_end();
521 static inline ChildIteratorType child_end(NodeType *N) {
522 return N->subtype_end();
528 // PromoteAbstractToConcrete - This is a recursive function that walks a type
529 // graph calculating whether or not a type is abstract.
531 void Type::PromoteAbstractToConcrete() {
532 if (!isAbstract()) return;
534 scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
535 scc_iterator<TypePromotionGraph> SE = scc_end (TypePromotionGraph(this));
537 for (; SI != SE; ++SI) {
538 std::vector<Type*> &SCC = *SI;
540 // Concrete types are leaves in the tree. Since an SCC will either be all
541 // abstract or all concrete, we only need to check one type.
542 if (SCC[0]->isAbstract()) {
543 if (isa<OpaqueType>(SCC[0]))
544 return; // Not going to be concrete, sorry.
546 // If all of the children of all of the types in this SCC are concrete,
547 // then this SCC is now concrete as well. If not, neither this SCC, nor
548 // any parent SCCs will be concrete, so we might as well just exit.
549 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
550 for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
551 E = SCC[i]->subtype_end(); CI != E; ++CI)
552 if ((*CI)->isAbstract())
553 // If the child type is in our SCC, it doesn't make the entire SCC
554 // abstract unless there is a non-SCC abstract type.
555 if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
556 return; // Not going to be concrete, sorry.
558 // Okay, we just discovered this whole SCC is now concrete, mark it as
560 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
561 assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
563 SCC[i]->setAbstract(false);
566 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
567 assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
568 // The type just became concrete, notify all users!
569 cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
576 //===----------------------------------------------------------------------===//
577 // Type Structural Equality Testing
578 //===----------------------------------------------------------------------===//
580 // TypesEqual - Two types are considered structurally equal if they have the
581 // same "shape": Every level and element of the types have identical primitive
582 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
583 // be pointer equals to be equivalent though. This uses an optimistic algorithm
584 // that assumes that two graphs are the same until proven otherwise.
586 static bool TypesEqual(const Type *Ty, const Type *Ty2,
587 std::map<const Type *, const Type *> &EqTypes) {
588 if (Ty == Ty2) return true;
589 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
590 if (isa<OpaqueType>(Ty))
591 return false; // Two unequal opaque types are never equal
593 std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
594 if (It != EqTypes.end())
595 return It->second == Ty2; // Looping back on a type, check for equality
597 // Otherwise, add the mapping to the table to make sure we don't get
598 // recursion on the types...
599 EqTypes.insert(It, std::make_pair(Ty, Ty2));
601 // Two really annoying special cases that breaks an otherwise nice simple
602 // algorithm is the fact that arraytypes have sizes that differentiates types,
603 // and that function types can be varargs or not. Consider this now.
605 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
606 const IntegerType *ITy2 = cast<IntegerType>(Ty2);
607 return ITy->getBitWidth() == ITy2->getBitWidth();
608 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
609 const PointerType *PTy2 = cast<PointerType>(Ty2);
610 return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
611 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
612 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
613 const StructType *STy2 = cast<StructType>(Ty2);
614 if (STy->getNumElements() != STy2->getNumElements()) return false;
615 if (STy->isPacked() != STy2->isPacked()) return false;
616 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
617 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
620 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
621 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
622 return ATy->getNumElements() == ATy2->getNumElements() &&
623 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
624 } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
625 const VectorType *PTy2 = cast<VectorType>(Ty2);
626 return PTy->getNumElements() == PTy2->getNumElements() &&
627 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
628 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
629 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
630 if (FTy->isVarArg() != FTy2->isVarArg() ||
631 FTy->getNumParams() != FTy2->getNumParams() ||
632 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
634 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
635 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
640 llvm_unreachable("Unknown derived type!");
645 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
646 std::map<const Type *, const Type *> EqTypes;
647 return TypesEqual(Ty, Ty2, EqTypes);
650 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
651 // TargetTy in the type graph. We know that Ty is an abstract type, so if we
652 // ever reach a non-abstract type, we know that we don't need to search the
654 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
655 SmallPtrSet<const Type*, 128> &VisitedTypes) {
656 if (TargetTy == CurTy) return true;
657 if (!CurTy->isAbstract()) return false;
659 if (!VisitedTypes.insert(CurTy))
660 return false; // Already been here.
662 for (Type::subtype_iterator I = CurTy->subtype_begin(),
663 E = CurTy->subtype_end(); I != E; ++I)
664 if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
669 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
670 SmallPtrSet<const Type*, 128> &VisitedTypes) {
671 if (TargetTy == CurTy) return true;
673 if (!VisitedTypes.insert(CurTy))
674 return false; // Already been here.
676 for (Type::subtype_iterator I = CurTy->subtype_begin(),
677 E = CurTy->subtype_end(); I != E; ++I)
678 if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
683 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
685 static bool TypeHasCycleThroughItself(const Type *Ty) {
686 SmallPtrSet<const Type*, 128> VisitedTypes;
688 if (Ty->isAbstract()) { // Optimized case for abstract types.
689 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
691 if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
694 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
696 if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
702 //===----------------------------------------------------------------------===//
703 // Function Type Factory and Value Class...
706 static ManagedStatic<TypeMap<IntegerValType, IntegerType> > IntegerTypes;
708 const IntegerType *IntegerType::get(unsigned NumBits) {
709 assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
710 assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
712 // Check for the built-in integer types
714 case 1: return cast<IntegerType>(Type::Int1Ty);
715 case 8: return cast<IntegerType>(Type::Int8Ty);
716 case 16: return cast<IntegerType>(Type::Int16Ty);
717 case 32: return cast<IntegerType>(Type::Int32Ty);
718 case 64: return cast<IntegerType>(Type::Int64Ty);
723 IntegerValType IVT(NumBits);
724 IntegerType *ITy = 0;
726 // First, see if the type is already in the table, for which
727 // a reader lock suffices.
728 sys::SmartScopedLock<true> L(*TypeMapLock);
729 ITy = IntegerTypes->get(IVT);
732 // Value not found. Derive a new type!
733 ITy = new IntegerType(NumBits);
734 IntegerTypes->add(IVT, ITy);
736 #ifdef DEBUG_MERGE_TYPES
737 DOUT << "Derived new type: " << *ITy << "\n";
742 bool IntegerType::isPowerOf2ByteWidth() const {
743 unsigned BitWidth = getBitWidth();
744 return (BitWidth > 7) && isPowerOf2_32(BitWidth);
747 APInt IntegerType::getMask() const {
748 return APInt::getAllOnesValue(getBitWidth());
751 // Define the actual map itself now...
752 static ManagedStatic<TypeMap<FunctionValType, FunctionType> > FunctionTypes;
754 FunctionValType FunctionValType::get(const FunctionType *FT) {
755 // Build up a FunctionValType
756 std::vector<const Type *> ParamTypes;
757 ParamTypes.reserve(FT->getNumParams());
758 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
759 ParamTypes.push_back(FT->getParamType(i));
760 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
764 // FunctionType::get - The factory function for the FunctionType class...
765 FunctionType *FunctionType::get(const Type *ReturnType,
766 const std::vector<const Type*> &Params,
768 FunctionValType VT(ReturnType, Params, isVarArg);
769 FunctionType *FT = 0;
771 sys::SmartScopedLock<true> L(*TypeMapLock);
772 FT = FunctionTypes->get(VT);
775 FT = (FunctionType*) operator new(sizeof(FunctionType) +
776 sizeof(PATypeHandle)*(Params.size()+1));
777 new (FT) FunctionType(ReturnType, Params, isVarArg);
778 FunctionTypes->add(VT, FT);
781 #ifdef DEBUG_MERGE_TYPES
782 DOUT << "Derived new type: " << FT << "\n";
787 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
788 assert(ElementType && "Can't get array of <null> types!");
789 assert(isValidElementType(ElementType) && "Invalid type for array element!");
791 ArrayValType AVT(ElementType, NumElements);
794 LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
796 sys::SmartScopedLock<true> L(*TypeMapLock);
797 AT = pImpl->ArrayTypes.get(AVT);
800 // Value not found. Derive a new type!
801 pImpl->ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
803 #ifdef DEBUG_MERGE_TYPES
804 DOUT << "Derived new type: " << *AT << "\n";
809 bool ArrayType::isValidElementType(const Type *ElemTy) {
810 if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy ||
811 ElemTy == Type::MetadataTy)
814 if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
815 if (PTy->getElementType() == Type::MetadataTy)
821 static ManagedStatic<TypeMap<VectorValType, VectorType> > VectorTypes;
823 VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) {
824 assert(ElementType && "Can't get vector of <null> types!");
826 VectorValType PVT(ElementType, NumElements);
829 sys::SmartScopedLock<true> L(*TypeMapLock);
830 PT = VectorTypes->get(PVT);
833 VectorTypes->add(PVT, PT = new VectorType(ElementType, NumElements));
835 #ifdef DEBUG_MERGE_TYPES
836 DOUT << "Derived new type: " << *PT << "\n";
841 bool VectorType::isValidElementType(const Type *ElemTy) {
842 if (ElemTy->isInteger() || ElemTy->isFloatingPoint() ||
843 isa<OpaqueType>(ElemTy))
849 //===----------------------------------------------------------------------===//
850 // Struct Type Factory...
853 static ManagedStatic<TypeMap<StructValType, StructType> > StructTypes;
855 StructType *StructType::get(const std::vector<const Type*> &ETypes,
857 StructValType STV(ETypes, isPacked);
860 sys::SmartScopedLock<true> L(*TypeMapLock);
861 ST = StructTypes->get(STV);
864 // Value not found. Derive a new type!
865 ST = (StructType*) operator new(sizeof(StructType) +
866 sizeof(PATypeHandle) * ETypes.size());
867 new (ST) StructType(ETypes, isPacked);
868 StructTypes->add(STV, ST);
870 #ifdef DEBUG_MERGE_TYPES
871 DOUT << "Derived new type: " << *ST << "\n";
876 StructType *StructType::get(const Type *type, ...) {
878 std::vector<const llvm::Type*> StructFields;
881 StructFields.push_back(type);
882 type = va_arg(ap, llvm::Type*);
884 return llvm::StructType::get(StructFields);
887 bool StructType::isValidElementType(const Type *ElemTy) {
888 if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy ||
889 ElemTy == Type::MetadataTy)
892 if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
893 if (PTy->getElementType() == Type::MetadataTy)
900 //===----------------------------------------------------------------------===//
901 // Pointer Type Factory...
904 static ManagedStatic<TypeMap<PointerValType, PointerType> > PointerTypes;
906 PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) {
907 assert(ValueType && "Can't get a pointer to <null> type!");
908 assert(ValueType != Type::VoidTy &&
909 "Pointer to void is not valid, use i8* instead!");
910 assert(isValidElementType(ValueType) && "Invalid type for pointer element!");
911 PointerValType PVT(ValueType, AddressSpace);
915 sys::SmartScopedLock<true> L(*TypeMapLock);
916 PT = PointerTypes->get(PVT);
919 // Value not found. Derive a new type!
920 PointerTypes->add(PVT, PT = new PointerType(ValueType, AddressSpace));
922 #ifdef DEBUG_MERGE_TYPES
923 DOUT << "Derived new type: " << *PT << "\n";
928 PointerType *Type::getPointerTo(unsigned addrs) const {
929 return PointerType::get(this, addrs);
932 bool PointerType::isValidElementType(const Type *ElemTy) {
933 if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy)
936 if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
937 if (PTy->getElementType() == Type::MetadataTy)
944 //===----------------------------------------------------------------------===//
945 // Derived Type Refinement Functions
946 //===----------------------------------------------------------------------===//
948 // addAbstractTypeUser - Notify an abstract type that there is a new user of
949 // it. This function is called primarily by the PATypeHandle class.
950 void Type::addAbstractTypeUser(AbstractTypeUser *U) const {
951 assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
952 AbstractTypeUsersLock->acquire();
953 AbstractTypeUsers.push_back(U);
954 AbstractTypeUsersLock->release();
958 // removeAbstractTypeUser - Notify an abstract type that a user of the class
959 // no longer has a handle to the type. This function is called primarily by
960 // the PATypeHandle class. When there are no users of the abstract type, it
961 // is annihilated, because there is no way to get a reference to it ever again.
963 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
964 AbstractTypeUsersLock->acquire();
966 // Search from back to front because we will notify users from back to
967 // front. Also, it is likely that there will be a stack like behavior to
968 // users that register and unregister users.
971 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
972 assert(i != 0 && "AbstractTypeUser not in user list!");
974 --i; // Convert to be in range 0 <= i < size()
975 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
977 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
979 #ifdef DEBUG_MERGE_TYPES
980 DOUT << " remAbstractTypeUser[" << (void*)this << ", "
981 << *this << "][" << i << "] User = " << U << "\n";
984 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
985 #ifdef DEBUG_MERGE_TYPES
986 DOUT << "DELETEing unused abstract type: <" << *this
987 << ">[" << (void*)this << "]" << "\n";
993 AbstractTypeUsersLock->release();
996 // unlockedRefineAbstractTypeTo - This function is used when it is discovered
997 // that the 'this' abstract type is actually equivalent to the NewType
998 // specified. This causes all users of 'this' to switch to reference the more
999 // concrete type NewType and for 'this' to be deleted. Only used for internal
1002 void DerivedType::unlockedRefineAbstractTypeTo(const Type *NewType) {
1003 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1004 assert(this != NewType && "Can't refine to myself!");
1005 assert(ForwardType == 0 && "This type has already been refined!");
1007 // The descriptions may be out of date. Conservatively clear them all!
1008 if (AbstractTypeDescriptions.isConstructed())
1009 AbstractTypeDescriptions->clear();
1011 #ifdef DEBUG_MERGE_TYPES
1012 DOUT << "REFINING abstract type [" << (void*)this << " "
1013 << *this << "] to [" << (void*)NewType << " "
1014 << *NewType << "]!\n";
1017 // Make sure to put the type to be refined to into a holder so that if IT gets
1018 // refined, that we will not continue using a dead reference...
1020 PATypeHolder NewTy(NewType);
1021 // Any PATypeHolders referring to this type will now automatically forward o
1022 // the type we are resolved to.
1023 ForwardType = NewType;
1024 if (NewType->isAbstract())
1025 cast<DerivedType>(NewType)->addRef();
1027 // Add a self use of the current type so that we don't delete ourself until
1028 // after the function exits.
1030 PATypeHolder CurrentTy(this);
1032 // To make the situation simpler, we ask the subclass to remove this type from
1033 // the type map, and to replace any type uses with uses of non-abstract types.
1034 // This dramatically limits the amount of recursive type trouble we can find
1038 // Iterate over all of the uses of this type, invoking callback. Each user
1039 // should remove itself from our use list automatically. We have to check to
1040 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1041 // will not cause users to drop off of the use list. If we resolve to ourself
1044 AbstractTypeUsersLock->acquire();
1045 while (!AbstractTypeUsers.empty() && NewTy != this) {
1046 AbstractTypeUser *User = AbstractTypeUsers.back();
1048 unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1049 #ifdef DEBUG_MERGE_TYPES
1050 DOUT << " REFINING user " << OldSize-1 << "[" << (void*)User
1051 << "] of abstract type [" << (void*)this << " "
1052 << *this << "] to [" << (void*)NewTy.get() << " "
1053 << *NewTy << "]!\n";
1055 User->refineAbstractType(this, NewTy);
1057 assert(AbstractTypeUsers.size() != OldSize &&
1058 "AbsTyUser did not remove self from user list!");
1060 AbstractTypeUsersLock->release();
1062 // If we were successful removing all users from the type, 'this' will be
1063 // deleted when the last PATypeHolder is destroyed or updated from this type.
1064 // This may occur on exit of this function, as the CurrentTy object is
1068 // refineAbstractTypeTo - This function is used by external callers to notify
1069 // us that this abstract type is equivalent to another type.
1071 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1072 // All recursive calls will go through unlockedRefineAbstractTypeTo,
1073 // to avoid deadlock problems.
1074 sys::SmartScopedLock<true> L(*TypeMapLock);
1075 unlockedRefineAbstractTypeTo(NewType);
1078 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1079 // the current type has transitioned from being abstract to being concrete.
1081 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1082 #ifdef DEBUG_MERGE_TYPES
1083 DOUT << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1086 AbstractTypeUsersLock->acquire();
1087 unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1088 while (!AbstractTypeUsers.empty()) {
1089 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1090 ATU->typeBecameConcrete(this);
1092 assert(AbstractTypeUsers.size() < OldSize-- &&
1093 "AbstractTypeUser did not remove itself from the use list!");
1095 AbstractTypeUsersLock->release();
1098 // refineAbstractType - Called when a contained type is found to be more
1099 // concrete - this could potentially change us from an abstract type to a
1102 void FunctionType::refineAbstractType(const DerivedType *OldType,
1103 const Type *NewType) {
1104 FunctionTypes->RefineAbstractType(this, OldType, NewType);
1107 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1108 FunctionTypes->TypeBecameConcrete(this, AbsTy);
1112 // refineAbstractType - Called when a contained type is found to be more
1113 // concrete - this could potentially change us from an abstract type to a
1116 void ArrayType::refineAbstractType(const DerivedType *OldType,
1117 const Type *NewType) {
1118 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1119 pImpl->ArrayTypes.RefineAbstractType(this, OldType, NewType);
1122 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1123 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1124 pImpl->ArrayTypes.TypeBecameConcrete(this, AbsTy);
1127 // refineAbstractType - Called when a contained type is found to be more
1128 // concrete - this could potentially change us from an abstract type to a
1131 void VectorType::refineAbstractType(const DerivedType *OldType,
1132 const Type *NewType) {
1133 VectorTypes->RefineAbstractType(this, OldType, NewType);
1136 void VectorType::typeBecameConcrete(const DerivedType *AbsTy) {
1137 VectorTypes->TypeBecameConcrete(this, AbsTy);
1140 // refineAbstractType - Called when a contained type is found to be more
1141 // concrete - this could potentially change us from an abstract type to a
1144 void StructType::refineAbstractType(const DerivedType *OldType,
1145 const Type *NewType) {
1146 StructTypes->RefineAbstractType(this, OldType, NewType);
1149 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1150 StructTypes->TypeBecameConcrete(this, AbsTy);
1153 // refineAbstractType - Called when a contained type is found to be more
1154 // concrete - this could potentially change us from an abstract type to a
1157 void PointerType::refineAbstractType(const DerivedType *OldType,
1158 const Type *NewType) {
1159 PointerTypes->RefineAbstractType(this, OldType, NewType);
1162 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1163 PointerTypes->TypeBecameConcrete(this, AbsTy);
1166 bool SequentialType::indexValid(const Value *V) const {
1167 if (isa<IntegerType>(V->getType()))
1173 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1175 OS << "<null> value!\n";
1181 std::ostream &operator<<(std::ostream &OS, const Type &T) {
1186 raw_ostream &operator<<(raw_ostream &OS, const Type &T) {