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 /// Because of the way Type subclasses are allocated, this function is necessary
51 /// to use the correct kind of "delete" operator to deallocate the Type object.
52 /// Some type objects (FunctionTy, StructTy) allocate additional space after
53 /// the space for their derived type to hold the contained types array of
54 /// PATypeHandles. Using this allocation scheme means all the PATypeHandles are
55 /// allocated with the type object, decreasing allocations and eliminating the
56 /// need for a std::vector to be used in the Type class itself.
57 /// @brief Type destruction function
58 void Type::destroy() const {
60 // Structures and Functions allocate their contained types past the end of
61 // the type object itself. These need to be destroyed differently than the
63 if (isa<FunctionType>(this) || isa<StructType>(this)) {
64 // First, make sure we destruct any PATypeHandles allocated by these
65 // subclasses. They must be manually destructed.
66 for (unsigned i = 0; i < NumContainedTys; ++i)
67 ContainedTys[i].PATypeHandle::~PATypeHandle();
69 // Now call the destructor for the subclass directly because we're going
70 // to delete this as an array of char.
71 if (isa<FunctionType>(this))
72 static_cast<const FunctionType*>(this)->FunctionType::~FunctionType();
74 static_cast<const StructType*>(this)->StructType::~StructType();
76 // Finally, remove the memory as an array deallocation of the chars it was
78 operator delete(const_cast<Type *>(this));
83 // For all the other type subclasses, there is either no contained types or
84 // just one (all Sequentials). For Sequentials, the PATypeHandle is not
85 // allocated past the type object, its included directly in the SequentialType
86 // class. This means we can safely just do "normal" delete of this object and
87 // all the destructors that need to run will be run.
91 const Type *Type::getPrimitiveType(LLVMContext &C, TypeID IDNumber) {
93 case VoidTyID : return getVoidTy(C);
94 case FloatTyID : return getFloatTy(C);
95 case DoubleTyID : return getDoubleTy(C);
96 case X86_FP80TyID : return getX86_FP80Ty(C);
97 case FP128TyID : return getFP128Ty(C);
98 case PPC_FP128TyID : return getPPC_FP128Ty(C);
99 case LabelTyID : return getLabelTy(C);
100 case MetadataTyID : return getMetadataTy(C);
106 const Type *Type::getVAArgsPromotedType(LLVMContext &C) const {
107 if (ID == IntegerTyID && getSubclassData() < 32)
108 return Type::getInt32Ty(C);
109 else if (ID == FloatTyID)
110 return Type::getDoubleTy(C);
115 /// getScalarType - If this is a vector type, return the element type,
116 /// otherwise return this.
117 const Type *Type::getScalarType() const {
118 if (const VectorType *VTy = dyn_cast<VectorType>(this))
119 return VTy->getElementType();
123 /// isIntOrIntVector - Return true if this is an integer type or a vector of
126 bool Type::isIntOrIntVector() const {
129 if (ID != Type::VectorTyID) return false;
131 return cast<VectorType>(this)->getElementType()->isInteger();
134 /// isFPOrFPVector - Return true if this is a FP type or a vector of FP types.
136 bool Type::isFPOrFPVector() const {
137 if (ID == Type::FloatTyID || ID == Type::DoubleTyID ||
138 ID == Type::FP128TyID || ID == Type::X86_FP80TyID ||
139 ID == Type::PPC_FP128TyID)
141 if (ID != Type::VectorTyID) return false;
143 return cast<VectorType>(this)->getElementType()->isFloatingPoint();
146 // canLosslesslyBitCastTo - Return true if this type can be converted to
147 // 'Ty' without any reinterpretation of bits. For example, i8* to i32*.
149 bool Type::canLosslesslyBitCastTo(const Type *Ty) const {
150 // Identity cast means no change so return true
154 // They are not convertible unless they are at least first class types
155 if (!this->isFirstClassType() || !Ty->isFirstClassType())
158 // Vector -> Vector conversions are always lossless if the two vector types
159 // have the same size, otherwise not.
160 if (const VectorType *thisPTy = dyn_cast<VectorType>(this))
161 if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
162 return thisPTy->getBitWidth() == thatPTy->getBitWidth();
164 // At this point we have only various mismatches of the first class types
165 // remaining and ptr->ptr. Just select the lossless conversions. Everything
166 // else is not lossless.
167 if (isa<PointerType>(this))
168 return isa<PointerType>(Ty);
169 return false; // Other types have no identity values
172 unsigned Type::getPrimitiveSizeInBits() const {
173 switch (getTypeID()) {
174 case Type::FloatTyID: return 32;
175 case Type::DoubleTyID: return 64;
176 case Type::X86_FP80TyID: return 80;
177 case Type::FP128TyID: return 128;
178 case Type::PPC_FP128TyID: return 128;
179 case Type::IntegerTyID: return cast<IntegerType>(this)->getBitWidth();
180 case Type::VectorTyID: return cast<VectorType>(this)->getBitWidth();
185 /// getScalarSizeInBits - If this is a vector type, return the
186 /// getPrimitiveSizeInBits value for the element type. Otherwise return the
187 /// getPrimitiveSizeInBits value for this type.
188 unsigned Type::getScalarSizeInBits() const {
189 return getScalarType()->getPrimitiveSizeInBits();
192 /// getFPMantissaWidth - Return the width of the mantissa of this type. This
193 /// is only valid on floating point types. If the FP type does not
194 /// have a stable mantissa (e.g. ppc long double), this method returns -1.
195 int Type::getFPMantissaWidth() const {
196 if (const VectorType *VTy = dyn_cast<VectorType>(this))
197 return VTy->getElementType()->getFPMantissaWidth();
198 assert(isFloatingPoint() && "Not a floating point type!");
199 if (ID == FloatTyID) return 24;
200 if (ID == DoubleTyID) return 53;
201 if (ID == X86_FP80TyID) return 64;
202 if (ID == FP128TyID) return 113;
203 assert(ID == PPC_FP128TyID && "unknown fp type");
207 /// isSizedDerivedType - Derived types like structures and arrays are sized
208 /// iff all of the members of the type are sized as well. Since asking for
209 /// their size is relatively uncommon, move this operation out of line.
210 bool Type::isSizedDerivedType() const {
211 if (isa<IntegerType>(this))
214 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
215 return ATy->getElementType()->isSized();
217 if (const VectorType *PTy = dyn_cast<VectorType>(this))
218 return PTy->getElementType()->isSized();
220 if (!isa<StructType>(this))
223 // Okay, our struct is sized if all of the elements are...
224 for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
225 if (!(*I)->isSized())
231 /// getForwardedTypeInternal - This method is used to implement the union-find
232 /// algorithm for when a type is being forwarded to another type.
233 const Type *Type::getForwardedTypeInternal() const {
234 assert(ForwardType && "This type is not being forwarded to another type!");
236 // Check to see if the forwarded type has been forwarded on. If so, collapse
237 // the forwarding links.
238 const Type *RealForwardedType = ForwardType->getForwardedType();
239 if (!RealForwardedType)
240 return ForwardType; // No it's not forwarded again
242 // Yes, it is forwarded again. First thing, add the reference to the new
244 if (RealForwardedType->isAbstract())
245 cast<DerivedType>(RealForwardedType)->addRef();
247 // Now drop the old reference. This could cause ForwardType to get deleted.
248 cast<DerivedType>(ForwardType)->dropRef();
250 // Return the updated type.
251 ForwardType = RealForwardedType;
255 void Type::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
256 llvm_unreachable("Attempting to refine a derived type!");
258 void Type::typeBecameConcrete(const DerivedType *AbsTy) {
259 llvm_unreachable("DerivedType is already a concrete type!");
263 std::string Type::getDescription() const {
264 LLVMContextImpl *pImpl = getContext().pImpl;
267 pImpl->AbstractTypeDescriptions :
268 pImpl->ConcreteTypeDescriptions;
271 raw_string_ostream DescOS(DescStr);
272 Map.print(this, DescOS);
277 bool StructType::indexValid(const Value *V) const {
278 // Structure indexes require 32-bit integer constants.
279 if (V->getType() == Type::getInt32Ty(V->getContext()))
280 if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
281 return indexValid(CU->getZExtValue());
285 bool StructType::indexValid(unsigned V) const {
286 return V < NumContainedTys;
289 // getTypeAtIndex - Given an index value into the type, return the type of the
290 // element. For a structure type, this must be a constant value...
292 const Type *StructType::getTypeAtIndex(const Value *V) const {
293 unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
294 return getTypeAtIndex(Idx);
297 const Type *StructType::getTypeAtIndex(unsigned Idx) const {
298 assert(indexValid(Idx) && "Invalid structure index!");
299 return ContainedTys[Idx];
302 //===----------------------------------------------------------------------===//
303 // Primitive 'Type' data
304 //===----------------------------------------------------------------------===//
306 const Type *Type::getVoidTy(LLVMContext &C) {
307 return C.pImpl->VoidTy;
310 const Type *Type::getLabelTy(LLVMContext &C) {
311 return C.pImpl->LabelTy;
314 const Type *Type::getFloatTy(LLVMContext &C) {
315 return C.pImpl->FloatTy;
318 const Type *Type::getDoubleTy(LLVMContext &C) {
319 return C.pImpl->DoubleTy;
322 const Type *Type::getMetadataTy(LLVMContext &C) {
323 return C.pImpl->MetadataTy;
326 const Type *Type::getX86_FP80Ty(LLVMContext &C) {
327 return C.pImpl->X86_FP80Ty;
330 const Type *Type::getFP128Ty(LLVMContext &C) {
331 return C.pImpl->FP128Ty;
334 const Type *Type::getPPC_FP128Ty(LLVMContext &C) {
335 return C.pImpl->PPC_FP128Ty;
338 const IntegerType *Type::getInt1Ty(LLVMContext &C) {
339 return C.pImpl->Int1Ty;
342 const IntegerType *Type::getInt8Ty(LLVMContext &C) {
343 return C.pImpl->Int8Ty;
346 const IntegerType *Type::getInt16Ty(LLVMContext &C) {
347 return C.pImpl->Int16Ty;
350 const IntegerType *Type::getInt32Ty(LLVMContext &C) {
351 return C.pImpl->Int32Ty;
354 const IntegerType *Type::getInt64Ty(LLVMContext &C) {
355 return C.pImpl->Int64Ty;
358 //===----------------------------------------------------------------------===//
359 // Derived Type Constructors
360 //===----------------------------------------------------------------------===//
362 /// isValidReturnType - Return true if the specified type is valid as a return
364 bool FunctionType::isValidReturnType(const Type *RetTy) {
365 if (RetTy->isFirstClassType()) {
366 if (const PointerType *PTy = dyn_cast<PointerType>(RetTy))
367 return PTy->getElementType() != Type::getMetadataTy(RetTy->getContext());
370 if (RetTy == Type::getVoidTy(RetTy->getContext()) ||
371 RetTy == Type::getMetadataTy(RetTy->getContext()) ||
372 isa<OpaqueType>(RetTy))
375 // If this is a multiple return case, verify that each return is a first class
376 // value and that there is at least one value.
377 const StructType *SRetTy = dyn_cast<StructType>(RetTy);
378 if (SRetTy == 0 || SRetTy->getNumElements() == 0)
381 for (unsigned i = 0, e = SRetTy->getNumElements(); i != e; ++i)
382 if (!SRetTy->getElementType(i)->isFirstClassType())
387 /// isValidArgumentType - Return true if the specified type is valid as an
389 bool FunctionType::isValidArgumentType(const Type *ArgTy) {
390 if ((!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy)) ||
391 (isa<PointerType>(ArgTy) &&
392 cast<PointerType>(ArgTy)->getElementType() ==
393 Type::getMetadataTy(ArgTy->getContext())))
399 FunctionType::FunctionType(const Type *Result,
400 const std::vector<const Type*> &Params,
402 : DerivedType(Result->getContext(), FunctionTyID), isVarArgs(IsVarArgs) {
403 ContainedTys = reinterpret_cast<PATypeHandle*>(this+1);
404 NumContainedTys = Params.size() + 1; // + 1 for result type
405 assert(isValidReturnType(Result) && "invalid return type for function");
408 bool isAbstract = Result->isAbstract();
409 new (&ContainedTys[0]) PATypeHandle(Result, this);
411 for (unsigned i = 0; i != Params.size(); ++i) {
412 assert(isValidArgumentType(Params[i]) &&
413 "Not a valid type for function argument!");
414 new (&ContainedTys[i+1]) PATypeHandle(Params[i], this);
415 isAbstract |= Params[i]->isAbstract();
418 // Calculate whether or not this type is abstract
419 setAbstract(isAbstract);
422 StructType::StructType(LLVMContext &C,
423 const std::vector<const Type*> &Types, bool isPacked)
424 : CompositeType(C, StructTyID) {
425 ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
426 NumContainedTys = Types.size();
427 setSubclassData(isPacked);
428 bool isAbstract = false;
429 for (unsigned i = 0; i < Types.size(); ++i) {
430 assert(Types[i] && "<null> type for structure field!");
431 assert(isValidElementType(Types[i]) &&
432 "Invalid type for structure element!");
433 new (&ContainedTys[i]) PATypeHandle(Types[i], this);
434 isAbstract |= Types[i]->isAbstract();
437 // Calculate whether or not this type is abstract
438 setAbstract(isAbstract);
441 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
442 : SequentialType(ArrayTyID, ElType) {
445 // Calculate whether or not this type is abstract
446 setAbstract(ElType->isAbstract());
449 VectorType::VectorType(const Type *ElType, unsigned NumEl)
450 : SequentialType(VectorTyID, ElType) {
452 setAbstract(ElType->isAbstract());
453 assert(NumEl > 0 && "NumEl of a VectorType must be greater than 0");
454 assert(isValidElementType(ElType) &&
455 "Elements of a VectorType must be a primitive type");
460 PointerType::PointerType(const Type *E, unsigned AddrSpace)
461 : SequentialType(PointerTyID, E) {
462 AddressSpace = AddrSpace;
463 // Calculate whether or not this type is abstract
464 setAbstract(E->isAbstract());
467 OpaqueType::OpaqueType(LLVMContext &C) : DerivedType(C, OpaqueTyID) {
469 #ifdef DEBUG_MERGE_TYPES
470 DEBUG(errs() << "Derived new type: " << *this << "\n");
474 void PATypeHolder::destroy() {
478 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
479 // another (more concrete) type, we must eliminate all references to other
480 // types, to avoid some circular reference problems.
481 void DerivedType::dropAllTypeUses() {
482 if (NumContainedTys != 0) {
483 // The type must stay abstract. To do this, we insert a pointer to a type
484 // that will never get resolved, thus will always be abstract.
485 static Type *AlwaysOpaqueTy = 0;
486 static PATypeHolder* Holder = 0;
487 Type *tmp = AlwaysOpaqueTy;
488 if (llvm_is_multithreaded()) {
491 llvm_acquire_global_lock();
492 tmp = AlwaysOpaqueTy;
494 tmp = OpaqueType::get(getContext());
495 PATypeHolder* tmp2 = new PATypeHolder(AlwaysOpaqueTy);
497 AlwaysOpaqueTy = tmp;
501 llvm_release_global_lock();
504 AlwaysOpaqueTy = OpaqueType::get(getContext());
505 Holder = new PATypeHolder(AlwaysOpaqueTy);
508 ContainedTys[0] = AlwaysOpaqueTy;
510 // Change the rest of the types to be Int32Ty's. It doesn't matter what we
511 // pick so long as it doesn't point back to this type. We choose something
512 // concrete to avoid overhead for adding to AbstracTypeUser lists and stuff.
513 for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
514 ContainedTys[i] = Type::getInt32Ty(getContext());
521 /// TypePromotionGraph and graph traits - this is designed to allow us to do
522 /// efficient SCC processing of type graphs. This is the exact same as
523 /// GraphTraits<Type*>, except that we pretend that concrete types have no
524 /// children to avoid processing them.
525 struct TypePromotionGraph {
527 TypePromotionGraph(Type *T) : Ty(T) {}
533 template <> struct GraphTraits<TypePromotionGraph> {
534 typedef Type NodeType;
535 typedef Type::subtype_iterator ChildIteratorType;
537 static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
538 static inline ChildIteratorType child_begin(NodeType *N) {
540 return N->subtype_begin();
541 else // No need to process children of concrete types.
542 return N->subtype_end();
544 static inline ChildIteratorType child_end(NodeType *N) {
545 return N->subtype_end();
551 // PromoteAbstractToConcrete - This is a recursive function that walks a type
552 // graph calculating whether or not a type is abstract.
554 void Type::PromoteAbstractToConcrete() {
555 if (!isAbstract()) return;
557 scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
558 scc_iterator<TypePromotionGraph> SE = scc_end (TypePromotionGraph(this));
560 for (; SI != SE; ++SI) {
561 std::vector<Type*> &SCC = *SI;
563 // Concrete types are leaves in the tree. Since an SCC will either be all
564 // abstract or all concrete, we only need to check one type.
565 if (SCC[0]->isAbstract()) {
566 if (isa<OpaqueType>(SCC[0]))
567 return; // Not going to be concrete, sorry.
569 // If all of the children of all of the types in this SCC are concrete,
570 // then this SCC is now concrete as well. If not, neither this SCC, nor
571 // any parent SCCs will be concrete, so we might as well just exit.
572 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
573 for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
574 E = SCC[i]->subtype_end(); CI != E; ++CI)
575 if ((*CI)->isAbstract())
576 // If the child type is in our SCC, it doesn't make the entire SCC
577 // abstract unless there is a non-SCC abstract type.
578 if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
579 return; // Not going to be concrete, sorry.
581 // Okay, we just discovered this whole SCC is now concrete, mark it as
583 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
584 assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
586 SCC[i]->setAbstract(false);
589 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
590 assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
591 // The type just became concrete, notify all users!
592 cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
599 //===----------------------------------------------------------------------===//
600 // Type Structural Equality Testing
601 //===----------------------------------------------------------------------===//
603 // TypesEqual - Two types are considered structurally equal if they have the
604 // same "shape": Every level and element of the types have identical primitive
605 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
606 // be pointer equals to be equivalent though. This uses an optimistic algorithm
607 // that assumes that two graphs are the same until proven otherwise.
609 static bool TypesEqual(const Type *Ty, const Type *Ty2,
610 std::map<const Type *, const Type *> &EqTypes) {
611 if (Ty == Ty2) return true;
612 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
613 if (isa<OpaqueType>(Ty))
614 return false; // Two unequal opaque types are never equal
616 std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
617 if (It != EqTypes.end())
618 return It->second == Ty2; // Looping back on a type, check for equality
620 // Otherwise, add the mapping to the table to make sure we don't get
621 // recursion on the types...
622 EqTypes.insert(It, std::make_pair(Ty, Ty2));
624 // Two really annoying special cases that breaks an otherwise nice simple
625 // algorithm is the fact that arraytypes have sizes that differentiates types,
626 // and that function types can be varargs or not. Consider this now.
628 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
629 const IntegerType *ITy2 = cast<IntegerType>(Ty2);
630 return ITy->getBitWidth() == ITy2->getBitWidth();
631 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
632 const PointerType *PTy2 = cast<PointerType>(Ty2);
633 return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
634 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
635 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
636 const StructType *STy2 = cast<StructType>(Ty2);
637 if (STy->getNumElements() != STy2->getNumElements()) return false;
638 if (STy->isPacked() != STy2->isPacked()) return false;
639 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
640 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
643 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
644 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
645 return ATy->getNumElements() == ATy2->getNumElements() &&
646 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
647 } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
648 const VectorType *PTy2 = cast<VectorType>(Ty2);
649 return PTy->getNumElements() == PTy2->getNumElements() &&
650 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
651 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
652 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
653 if (FTy->isVarArg() != FTy2->isVarArg() ||
654 FTy->getNumParams() != FTy2->getNumParams() ||
655 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
657 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
658 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
663 llvm_unreachable("Unknown derived type!");
668 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
669 std::map<const Type *, const Type *> EqTypes;
670 return TypesEqual(Ty, Ty2, EqTypes);
673 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
674 // TargetTy in the type graph. We know that Ty is an abstract type, so if we
675 // ever reach a non-abstract type, we know that we don't need to search the
677 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
678 SmallPtrSet<const Type*, 128> &VisitedTypes) {
679 if (TargetTy == CurTy) return true;
680 if (!CurTy->isAbstract()) return false;
682 if (!VisitedTypes.insert(CurTy))
683 return false; // Already been here.
685 for (Type::subtype_iterator I = CurTy->subtype_begin(),
686 E = CurTy->subtype_end(); I != E; ++I)
687 if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
692 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
693 SmallPtrSet<const Type*, 128> &VisitedTypes) {
694 if (TargetTy == CurTy) return true;
696 if (!VisitedTypes.insert(CurTy))
697 return false; // Already been here.
699 for (Type::subtype_iterator I = CurTy->subtype_begin(),
700 E = CurTy->subtype_end(); I != E; ++I)
701 if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
706 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
708 static bool TypeHasCycleThroughItself(const Type *Ty) {
709 SmallPtrSet<const Type*, 128> VisitedTypes;
711 if (Ty->isAbstract()) { // Optimized case for abstract types.
712 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
714 if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
717 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
719 if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
725 //===----------------------------------------------------------------------===//
726 // Function Type Factory and Value Class...
728 const IntegerType *IntegerType::get(LLVMContext &C, unsigned NumBits) {
729 assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
730 assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
732 // Check for the built-in integer types
734 case 1: return cast<IntegerType>(Type::getInt1Ty(C));
735 case 8: return cast<IntegerType>(Type::getInt8Ty(C));
736 case 16: return cast<IntegerType>(Type::getInt16Ty(C));
737 case 32: return cast<IntegerType>(Type::getInt32Ty(C));
738 case 64: return cast<IntegerType>(Type::getInt64Ty(C));
743 LLVMContextImpl *pImpl = C.pImpl;
745 IntegerValType IVT(NumBits);
746 IntegerType *ITy = 0;
748 // First, see if the type is already in the table, for which
749 // a reader lock suffices.
750 sys::SmartScopedLock<true> L(pImpl->TypeMapLock);
751 ITy = pImpl->IntegerTypes.get(IVT);
754 // Value not found. Derive a new type!
755 ITy = new IntegerType(C, NumBits);
756 pImpl->IntegerTypes.add(IVT, ITy);
758 #ifdef DEBUG_MERGE_TYPES
759 DEBUG(errs() << "Derived new type: " << *ITy << "\n");
764 bool IntegerType::isPowerOf2ByteWidth() const {
765 unsigned BitWidth = getBitWidth();
766 return (BitWidth > 7) && isPowerOf2_32(BitWidth);
769 APInt IntegerType::getMask() const {
770 return APInt::getAllOnesValue(getBitWidth());
773 FunctionValType FunctionValType::get(const FunctionType *FT) {
774 // Build up a FunctionValType
775 std::vector<const Type *> ParamTypes;
776 ParamTypes.reserve(FT->getNumParams());
777 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
778 ParamTypes.push_back(FT->getParamType(i));
779 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
783 // FunctionType::get - The factory function for the FunctionType class...
784 FunctionType *FunctionType::get(const Type *ReturnType,
785 const std::vector<const Type*> &Params,
787 FunctionValType VT(ReturnType, Params, isVarArg);
788 FunctionType *FT = 0;
790 LLVMContextImpl *pImpl = ReturnType->getContext().pImpl;
792 sys::SmartScopedLock<true> L(pImpl->TypeMapLock);
793 FT = pImpl->FunctionTypes.get(VT);
796 FT = (FunctionType*) operator new(sizeof(FunctionType) +
797 sizeof(PATypeHandle)*(Params.size()+1));
798 new (FT) FunctionType(ReturnType, Params, isVarArg);
799 pImpl->FunctionTypes.add(VT, FT);
802 #ifdef DEBUG_MERGE_TYPES
803 DEBUG(errs() << "Derived new type: " << FT << "\n");
808 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
809 assert(ElementType && "Can't get array of <null> types!");
810 assert(isValidElementType(ElementType) && "Invalid type for array element!");
812 ArrayValType AVT(ElementType, NumElements);
815 LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
817 sys::SmartScopedLock<true> L(pImpl->TypeMapLock);
818 AT = pImpl->ArrayTypes.get(AVT);
821 // Value not found. Derive a new type!
822 pImpl->ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
824 #ifdef DEBUG_MERGE_TYPES
825 DEBUG(errs() << "Derived new type: " << *AT << "\n");
830 bool ArrayType::isValidElementType(const Type *ElemTy) {
831 if (ElemTy == Type::getVoidTy(ElemTy->getContext()) ||
832 ElemTy == Type::getLabelTy(ElemTy->getContext()) ||
833 ElemTy == Type::getMetadataTy(ElemTy->getContext()))
836 if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
837 if (PTy->getElementType() == Type::getMetadataTy(ElemTy->getContext()))
843 VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) {
844 assert(ElementType && "Can't get vector of <null> types!");
846 VectorValType PVT(ElementType, NumElements);
849 LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
851 sys::SmartScopedLock<true> L(pImpl->TypeMapLock);
852 PT = pImpl->VectorTypes.get(PVT);
855 pImpl->VectorTypes.add(PVT, PT = new VectorType(ElementType, NumElements));
857 #ifdef DEBUG_MERGE_TYPES
858 DEBUG(errs() << "Derived new type: " << *PT << "\n");
863 bool VectorType::isValidElementType(const Type *ElemTy) {
864 if (ElemTy->isInteger() || ElemTy->isFloatingPoint() ||
865 isa<OpaqueType>(ElemTy))
871 //===----------------------------------------------------------------------===//
872 // Struct Type Factory...
875 StructType *StructType::get(LLVMContext &Context,
876 const std::vector<const Type*> &ETypes,
878 StructValType STV(ETypes, isPacked);
881 LLVMContextImpl *pImpl = Context.pImpl;
883 sys::SmartScopedLock<true> L(pImpl->TypeMapLock);
884 ST = pImpl->StructTypes.get(STV);
887 // Value not found. Derive a new type!
888 ST = (StructType*) operator new(sizeof(StructType) +
889 sizeof(PATypeHandle) * ETypes.size());
890 new (ST) StructType(Context, ETypes, isPacked);
891 pImpl->StructTypes.add(STV, ST);
893 #ifdef DEBUG_MERGE_TYPES
894 DEBUG(errs() << "Derived new type: " << *ST << "\n");
899 StructType *StructType::get(LLVMContext &Context, const Type *type, ...) {
901 std::vector<const llvm::Type*> StructFields;
904 StructFields.push_back(type);
905 type = va_arg(ap, llvm::Type*);
907 return llvm::StructType::get(Context, StructFields);
910 bool StructType::isValidElementType(const Type *ElemTy) {
911 if (ElemTy == Type::getVoidTy(ElemTy->getContext()) ||
912 ElemTy == Type::getLabelTy(ElemTy->getContext()) ||
913 ElemTy == Type::getMetadataTy(ElemTy->getContext()))
916 if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
917 if (PTy->getElementType() == Type::getMetadataTy(ElemTy->getContext()))
924 //===----------------------------------------------------------------------===//
925 // Pointer Type Factory...
928 PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) {
929 assert(ValueType && "Can't get a pointer to <null> type!");
930 assert(ValueType != Type::getVoidTy(ValueType->getContext()) &&
931 "Pointer to void is not valid, use i8* instead!");
932 assert(isValidElementType(ValueType) && "Invalid type for pointer element!");
933 PointerValType PVT(ValueType, AddressSpace);
937 LLVMContextImpl *pImpl = ValueType->getContext().pImpl;
939 sys::SmartScopedLock<true> L(pImpl->TypeMapLock);
940 PT = pImpl->PointerTypes.get(PVT);
943 // Value not found. Derive a new type!
944 pImpl->PointerTypes.add(PVT, PT = new PointerType(ValueType, AddressSpace));
946 #ifdef DEBUG_MERGE_TYPES
947 DEBUG(errs() << "Derived new type: " << *PT << "\n");
952 PointerType *Type::getPointerTo(unsigned addrs) const {
953 return PointerType::get(this, addrs);
956 bool PointerType::isValidElementType(const Type *ElemTy) {
957 if (ElemTy == Type::getVoidTy(ElemTy->getContext()) ||
958 ElemTy == Type::getLabelTy(ElemTy->getContext()))
961 if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
962 if (PTy->getElementType() == Type::getMetadataTy(ElemTy->getContext()))
969 //===----------------------------------------------------------------------===//
970 // Derived Type Refinement Functions
971 //===----------------------------------------------------------------------===//
973 // addAbstractTypeUser - Notify an abstract type that there is a new user of
974 // it. This function is called primarily by the PATypeHandle class.
975 void Type::addAbstractTypeUser(AbstractTypeUser *U) const {
976 assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
977 LLVMContextImpl *pImpl = getContext().pImpl;
978 pImpl->AbstractTypeUsersLock.acquire();
979 AbstractTypeUsers.push_back(U);
980 pImpl->AbstractTypeUsersLock.release();
984 // removeAbstractTypeUser - Notify an abstract type that a user of the class
985 // no longer has a handle to the type. This function is called primarily by
986 // the PATypeHandle class. When there are no users of the abstract type, it
987 // is annihilated, because there is no way to get a reference to it ever again.
989 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
990 LLVMContextImpl *pImpl = getContext().pImpl;
991 pImpl->AbstractTypeUsersLock.acquire();
993 // Search from back to front because we will notify users from back to
994 // front. Also, it is likely that there will be a stack like behavior to
995 // users that register and unregister users.
998 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
999 assert(i != 0 && "AbstractTypeUser not in user list!");
1001 --i; // Convert to be in range 0 <= i < size()
1002 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1004 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1006 #ifdef DEBUG_MERGE_TYPES
1007 DEBUG(errs() << " remAbstractTypeUser[" << (void*)this << ", "
1008 << *this << "][" << i << "] User = " << U << "\n");
1011 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1012 #ifdef DEBUG_MERGE_TYPES
1013 DEBUG(errs() << "DELETEing unused abstract type: <" << *this
1014 << ">[" << (void*)this << "]" << "\n");
1020 pImpl->AbstractTypeUsersLock.release();
1023 // unlockedRefineAbstractTypeTo - This function is used when it is discovered
1024 // that the 'this' abstract type is actually equivalent to the NewType
1025 // specified. This causes all users of 'this' to switch to reference the more
1026 // concrete type NewType and for 'this' to be deleted. Only used for internal
1029 void DerivedType::unlockedRefineAbstractTypeTo(const Type *NewType) {
1030 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1031 assert(this != NewType && "Can't refine to myself!");
1032 assert(ForwardType == 0 && "This type has already been refined!");
1034 LLVMContextImpl *pImpl = getContext().pImpl;
1036 // The descriptions may be out of date. Conservatively clear them all!
1037 pImpl->AbstractTypeDescriptions.clear();
1039 #ifdef DEBUG_MERGE_TYPES
1040 DEBUG(errs() << "REFINING abstract type [" << (void*)this << " "
1041 << *this << "] to [" << (void*)NewType << " "
1042 << *NewType << "]!\n");
1045 // Make sure to put the type to be refined to into a holder so that if IT gets
1046 // refined, that we will not continue using a dead reference...
1048 PATypeHolder NewTy(NewType);
1049 // Any PATypeHolders referring to this type will now automatically forward o
1050 // the type we are resolved to.
1051 ForwardType = NewType;
1052 if (NewType->isAbstract())
1053 cast<DerivedType>(NewType)->addRef();
1055 // Add a self use of the current type so that we don't delete ourself until
1056 // after the function exits.
1058 PATypeHolder CurrentTy(this);
1060 // To make the situation simpler, we ask the subclass to remove this type from
1061 // the type map, and to replace any type uses with uses of non-abstract types.
1062 // This dramatically limits the amount of recursive type trouble we can find
1066 // Iterate over all of the uses of this type, invoking callback. Each user
1067 // should remove itself from our use list automatically. We have to check to
1068 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1069 // will not cause users to drop off of the use list. If we resolve to ourself
1072 pImpl->AbstractTypeUsersLock.acquire();
1073 while (!AbstractTypeUsers.empty() && NewTy != this) {
1074 AbstractTypeUser *User = AbstractTypeUsers.back();
1076 unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1077 #ifdef DEBUG_MERGE_TYPES
1078 DEBUG(errs() << " REFINING user " << OldSize-1 << "[" << (void*)User
1079 << "] of abstract type [" << (void*)this << " "
1080 << *this << "] to [" << (void*)NewTy.get() << " "
1081 << *NewTy << "]!\n");
1083 User->refineAbstractType(this, NewTy);
1085 assert(AbstractTypeUsers.size() != OldSize &&
1086 "AbsTyUser did not remove self from user list!");
1088 pImpl->AbstractTypeUsersLock.release();
1090 // If we were successful removing all users from the type, 'this' will be
1091 // deleted when the last PATypeHolder is destroyed or updated from this type.
1092 // This may occur on exit of this function, as the CurrentTy object is
1096 // refineAbstractTypeTo - This function is used by external callers to notify
1097 // us that this abstract type is equivalent to another type.
1099 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1100 // All recursive calls will go through unlockedRefineAbstractTypeTo,
1101 // to avoid deadlock problems.
1102 sys::SmartScopedLock<true> L(NewType->getContext().pImpl->TypeMapLock);
1103 unlockedRefineAbstractTypeTo(NewType);
1106 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1107 // the current type has transitioned from being abstract to being concrete.
1109 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1110 #ifdef DEBUG_MERGE_TYPES
1111 DEBUG(errs() << "typeIsREFINED type: " << (void*)this << " " << *this <<"\n");
1114 LLVMContextImpl *pImpl = getContext().pImpl;
1116 pImpl->AbstractTypeUsersLock.acquire();
1117 unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1118 while (!AbstractTypeUsers.empty()) {
1119 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1120 ATU->typeBecameConcrete(this);
1122 assert(AbstractTypeUsers.size() < OldSize-- &&
1123 "AbstractTypeUser did not remove itself from the use list!");
1125 pImpl->AbstractTypeUsersLock.release();
1128 // refineAbstractType - Called when a contained type is found to be more
1129 // concrete - this could potentially change us from an abstract type to a
1132 void FunctionType::refineAbstractType(const DerivedType *OldType,
1133 const Type *NewType) {
1134 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1135 pImpl->FunctionTypes.RefineAbstractType(this, OldType, NewType);
1138 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1139 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1140 pImpl->FunctionTypes.TypeBecameConcrete(this, AbsTy);
1144 // refineAbstractType - Called when a contained type is found to be more
1145 // concrete - this could potentially change us from an abstract type to a
1148 void ArrayType::refineAbstractType(const DerivedType *OldType,
1149 const Type *NewType) {
1150 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1151 pImpl->ArrayTypes.RefineAbstractType(this, OldType, NewType);
1154 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1155 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1156 pImpl->ArrayTypes.TypeBecameConcrete(this, AbsTy);
1159 // refineAbstractType - Called when a contained type is found to be more
1160 // concrete - this could potentially change us from an abstract type to a
1163 void VectorType::refineAbstractType(const DerivedType *OldType,
1164 const Type *NewType) {
1165 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1166 pImpl->VectorTypes.RefineAbstractType(this, OldType, NewType);
1169 void VectorType::typeBecameConcrete(const DerivedType *AbsTy) {
1170 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1171 pImpl->VectorTypes.TypeBecameConcrete(this, AbsTy);
1174 // refineAbstractType - Called when a contained type is found to be more
1175 // concrete - this could potentially change us from an abstract type to a
1178 void StructType::refineAbstractType(const DerivedType *OldType,
1179 const Type *NewType) {
1180 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1181 pImpl->StructTypes.RefineAbstractType(this, OldType, NewType);
1184 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1185 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1186 pImpl->StructTypes.TypeBecameConcrete(this, AbsTy);
1189 // refineAbstractType - Called when a contained type is found to be more
1190 // concrete - this could potentially change us from an abstract type to a
1193 void PointerType::refineAbstractType(const DerivedType *OldType,
1194 const Type *NewType) {
1195 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1196 pImpl->PointerTypes.RefineAbstractType(this, OldType, NewType);
1199 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1200 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1201 pImpl->PointerTypes.TypeBecameConcrete(this, AbsTy);
1204 bool SequentialType::indexValid(const Value *V) const {
1205 if (isa<IntegerType>(V->getType()))
1211 raw_ostream &operator<<(raw_ostream &OS, const Type &T) {