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(LLVMContext &C, TypeID IDNumber) {
108 case VoidTyID : return getVoidTy(C);
109 case FloatTyID : return getFloatTy(C);
110 case DoubleTyID : return getDoubleTy(C);
111 case X86_FP80TyID : return getX86_FP80Ty(C);
112 case FP128TyID : return getFP128Ty(C);
113 case PPC_FP128TyID : return getPPC_FP128Ty(C);
114 case LabelTyID : return getLabelTy(C);
115 case MetadataTyID : return getMetadataTy(C);
121 const Type *Type::getVAArgsPromotedType(LLVMContext &C) const {
122 if (ID == IntegerTyID && getSubclassData() < 32)
123 return Type::getInt32Ty(C);
124 else if (ID == FloatTyID)
125 return Type::getDoubleTy(C);
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::getInt32Ty(V->getContext()))
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 //===----------------------------------------------------------------------===//
319 struct BuiltinIntegerType : public IntegerType {
320 explicit BuiltinIntegerType(unsigned W) : IntegerType(W) {}
324 const Type *Type::getVoidTy(LLVMContext &C) {
325 static const Type *VoidTy = new Type(Type::VoidTyID);
329 const Type *Type::getLabelTy(LLVMContext &C) {
330 static const Type *LabelTy = new Type(Type::LabelTyID);
334 const Type *Type::getFloatTy(LLVMContext &C) {
335 static const Type *FloatTy = new Type(Type::FloatTyID);
339 const Type *Type::getDoubleTy(LLVMContext &C) {
340 static const Type *DoubleTy = new Type(Type::DoubleTyID);
344 const Type *Type::getMetadataTy(LLVMContext &C) {
345 static const Type *MetadataTy = new Type(Type::MetadataTyID);
349 const Type *Type::getX86_FP80Ty(LLVMContext &C) {
350 static const Type *X86_FP80Ty = new Type(Type::X86_FP80TyID);
354 const Type *Type::getFP128Ty(LLVMContext &C) {
355 static const Type *FP128Ty = new Type(Type::FP128TyID);
359 const Type *Type::getPPC_FP128Ty(LLVMContext &C) {
360 static const Type *PPC_FP128Ty = new Type(Type::PPC_FP128TyID);
364 const IntegerType *Type::getInt1Ty(LLVMContext &C) {
365 static const IntegerType *Int1Ty = new BuiltinIntegerType(1);
369 const IntegerType *Type::getInt8Ty(LLVMContext &C) {
370 static const IntegerType *Int8Ty = new BuiltinIntegerType(8);
374 const IntegerType *Type::getInt16Ty(LLVMContext &C) {
375 static const IntegerType *Int16Ty = new BuiltinIntegerType(16);
379 const IntegerType *Type::getInt32Ty(LLVMContext &C) {
380 static const IntegerType *Int32Ty = new BuiltinIntegerType(32);
384 const IntegerType *Type::getInt64Ty(LLVMContext &C) {
385 static const IntegerType *Int64Ty = new BuiltinIntegerType(64);
389 //===----------------------------------------------------------------------===//
390 // Derived Type Constructors
391 //===----------------------------------------------------------------------===//
393 /// isValidReturnType - Return true if the specified type is valid as a return
395 bool FunctionType::isValidReturnType(const Type *RetTy) {
396 if (RetTy->isFirstClassType()) {
397 if (const PointerType *PTy = dyn_cast<PointerType>(RetTy))
398 return PTy->getElementType() != Type::getMetadataTy(RetTy->getContext());
401 if (RetTy == Type::getVoidTy(RetTy->getContext()) ||
402 RetTy == Type::getMetadataTy(RetTy->getContext()) ||
403 isa<OpaqueType>(RetTy))
406 // If this is a multiple return case, verify that each return is a first class
407 // value and that there is at least one value.
408 const StructType *SRetTy = dyn_cast<StructType>(RetTy);
409 if (SRetTy == 0 || SRetTy->getNumElements() == 0)
412 for (unsigned i = 0, e = SRetTy->getNumElements(); i != e; ++i)
413 if (!SRetTy->getElementType(i)->isFirstClassType())
418 /// isValidArgumentType - Return true if the specified type is valid as an
420 bool FunctionType::isValidArgumentType(const Type *ArgTy) {
421 if ((!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy)) ||
422 (isa<PointerType>(ArgTy) &&
423 cast<PointerType>(ArgTy)->getElementType() ==
424 Type::getMetadataTy(ArgTy->getContext())))
430 FunctionType::FunctionType(const Type *Result,
431 const std::vector<const Type*> &Params,
433 : DerivedType(FunctionTyID), isVarArgs(IsVarArgs) {
434 ContainedTys = reinterpret_cast<PATypeHandle*>(this+1);
435 NumContainedTys = Params.size() + 1; // + 1 for result type
436 assert(isValidReturnType(Result) && "invalid return type for function");
439 bool isAbstract = Result->isAbstract();
440 new (&ContainedTys[0]) PATypeHandle(Result, this);
442 for (unsigned i = 0; i != Params.size(); ++i) {
443 assert(isValidArgumentType(Params[i]) &&
444 "Not a valid type for function argument!");
445 new (&ContainedTys[i+1]) PATypeHandle(Params[i], this);
446 isAbstract |= Params[i]->isAbstract();
449 // Calculate whether or not this type is abstract
450 setAbstract(isAbstract);
453 StructType::StructType(const std::vector<const Type*> &Types, bool isPacked)
454 : CompositeType(StructTyID) {
455 ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
456 NumContainedTys = Types.size();
457 setSubclassData(isPacked);
458 bool isAbstract = false;
459 for (unsigned i = 0; i < Types.size(); ++i) {
460 assert(Types[i] && "<null> type for structure field!");
461 assert(isValidElementType(Types[i]) &&
462 "Invalid type for structure element!");
463 new (&ContainedTys[i]) PATypeHandle(Types[i], this);
464 isAbstract |= Types[i]->isAbstract();
467 // Calculate whether or not this type is abstract
468 setAbstract(isAbstract);
471 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
472 : SequentialType(ArrayTyID, ElType) {
475 // Calculate whether or not this type is abstract
476 setAbstract(ElType->isAbstract());
479 VectorType::VectorType(const Type *ElType, unsigned NumEl)
480 : SequentialType(VectorTyID, ElType) {
482 setAbstract(ElType->isAbstract());
483 assert(NumEl > 0 && "NumEl of a VectorType must be greater than 0");
484 assert(isValidElementType(ElType) &&
485 "Elements of a VectorType must be a primitive type");
490 PointerType::PointerType(const Type *E, unsigned AddrSpace)
491 : SequentialType(PointerTyID, E) {
492 AddressSpace = AddrSpace;
493 // Calculate whether or not this type is abstract
494 setAbstract(E->isAbstract());
497 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
499 #ifdef DEBUG_MERGE_TYPES
500 DOUT << "Derived new type: " << *this << "\n";
504 void PATypeHolder::destroy() {
508 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
509 // another (more concrete) type, we must eliminate all references to other
510 // types, to avoid some circular reference problems.
511 void DerivedType::dropAllTypeUses() {
512 if (NumContainedTys != 0) {
513 // The type must stay abstract. To do this, we insert a pointer to a type
514 // that will never get resolved, thus will always be abstract.
515 static Type *AlwaysOpaqueTy = 0;
516 static PATypeHolder* Holder = 0;
517 Type *tmp = AlwaysOpaqueTy;
518 if (llvm_is_multithreaded()) {
521 llvm_acquire_global_lock();
522 tmp = AlwaysOpaqueTy;
524 tmp = OpaqueType::get();
525 PATypeHolder* tmp2 = new PATypeHolder(AlwaysOpaqueTy);
527 AlwaysOpaqueTy = tmp;
531 llvm_release_global_lock();
534 AlwaysOpaqueTy = OpaqueType::get();
535 Holder = new PATypeHolder(AlwaysOpaqueTy);
538 ContainedTys[0] = AlwaysOpaqueTy;
540 // Change the rest of the types to be Int32Ty's. It doesn't matter what we
541 // pick so long as it doesn't point back to this type. We choose something
542 // concrete to avoid overhead for adding to AbstracTypeUser lists and stuff.
543 for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
544 ContainedTys[i] = Type::getInt32Ty(getContext());
551 /// TypePromotionGraph and graph traits - this is designed to allow us to do
552 /// efficient SCC processing of type graphs. This is the exact same as
553 /// GraphTraits<Type*>, except that we pretend that concrete types have no
554 /// children to avoid processing them.
555 struct TypePromotionGraph {
557 TypePromotionGraph(Type *T) : Ty(T) {}
563 template <> struct GraphTraits<TypePromotionGraph> {
564 typedef Type NodeType;
565 typedef Type::subtype_iterator ChildIteratorType;
567 static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
568 static inline ChildIteratorType child_begin(NodeType *N) {
570 return N->subtype_begin();
571 else // No need to process children of concrete types.
572 return N->subtype_end();
574 static inline ChildIteratorType child_end(NodeType *N) {
575 return N->subtype_end();
581 // PromoteAbstractToConcrete - This is a recursive function that walks a type
582 // graph calculating whether or not a type is abstract.
584 void Type::PromoteAbstractToConcrete() {
585 if (!isAbstract()) return;
587 scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
588 scc_iterator<TypePromotionGraph> SE = scc_end (TypePromotionGraph(this));
590 for (; SI != SE; ++SI) {
591 std::vector<Type*> &SCC = *SI;
593 // Concrete types are leaves in the tree. Since an SCC will either be all
594 // abstract or all concrete, we only need to check one type.
595 if (SCC[0]->isAbstract()) {
596 if (isa<OpaqueType>(SCC[0]))
597 return; // Not going to be concrete, sorry.
599 // If all of the children of all of the types in this SCC are concrete,
600 // then this SCC is now concrete as well. If not, neither this SCC, nor
601 // any parent SCCs will be concrete, so we might as well just exit.
602 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
603 for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
604 E = SCC[i]->subtype_end(); CI != E; ++CI)
605 if ((*CI)->isAbstract())
606 // If the child type is in our SCC, it doesn't make the entire SCC
607 // abstract unless there is a non-SCC abstract type.
608 if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
609 return; // Not going to be concrete, sorry.
611 // Okay, we just discovered this whole SCC is now concrete, mark it as
613 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
614 assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
616 SCC[i]->setAbstract(false);
619 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
620 assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
621 // The type just became concrete, notify all users!
622 cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
629 //===----------------------------------------------------------------------===//
630 // Type Structural Equality Testing
631 //===----------------------------------------------------------------------===//
633 // TypesEqual - Two types are considered structurally equal if they have the
634 // same "shape": Every level and element of the types have identical primitive
635 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
636 // be pointer equals to be equivalent though. This uses an optimistic algorithm
637 // that assumes that two graphs are the same until proven otherwise.
639 static bool TypesEqual(const Type *Ty, const Type *Ty2,
640 std::map<const Type *, const Type *> &EqTypes) {
641 if (Ty == Ty2) return true;
642 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
643 if (isa<OpaqueType>(Ty))
644 return false; // Two unequal opaque types are never equal
646 std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
647 if (It != EqTypes.end())
648 return It->second == Ty2; // Looping back on a type, check for equality
650 // Otherwise, add the mapping to the table to make sure we don't get
651 // recursion on the types...
652 EqTypes.insert(It, std::make_pair(Ty, Ty2));
654 // Two really annoying special cases that breaks an otherwise nice simple
655 // algorithm is the fact that arraytypes have sizes that differentiates types,
656 // and that function types can be varargs or not. Consider this now.
658 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
659 const IntegerType *ITy2 = cast<IntegerType>(Ty2);
660 return ITy->getBitWidth() == ITy2->getBitWidth();
661 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
662 const PointerType *PTy2 = cast<PointerType>(Ty2);
663 return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
664 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
665 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
666 const StructType *STy2 = cast<StructType>(Ty2);
667 if (STy->getNumElements() != STy2->getNumElements()) return false;
668 if (STy->isPacked() != STy2->isPacked()) return false;
669 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
670 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
673 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
674 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
675 return ATy->getNumElements() == ATy2->getNumElements() &&
676 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
677 } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
678 const VectorType *PTy2 = cast<VectorType>(Ty2);
679 return PTy->getNumElements() == PTy2->getNumElements() &&
680 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
681 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
682 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
683 if (FTy->isVarArg() != FTy2->isVarArg() ||
684 FTy->getNumParams() != FTy2->getNumParams() ||
685 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
687 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
688 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
693 llvm_unreachable("Unknown derived type!");
698 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
699 std::map<const Type *, const Type *> EqTypes;
700 return TypesEqual(Ty, Ty2, EqTypes);
703 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
704 // TargetTy in the type graph. We know that Ty is an abstract type, so if we
705 // ever reach a non-abstract type, we know that we don't need to search the
707 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
708 SmallPtrSet<const Type*, 128> &VisitedTypes) {
709 if (TargetTy == CurTy) return true;
710 if (!CurTy->isAbstract()) return false;
712 if (!VisitedTypes.insert(CurTy))
713 return false; // Already been here.
715 for (Type::subtype_iterator I = CurTy->subtype_begin(),
716 E = CurTy->subtype_end(); I != E; ++I)
717 if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
722 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
723 SmallPtrSet<const Type*, 128> &VisitedTypes) {
724 if (TargetTy == CurTy) return true;
726 if (!VisitedTypes.insert(CurTy))
727 return false; // Already been here.
729 for (Type::subtype_iterator I = CurTy->subtype_begin(),
730 E = CurTy->subtype_end(); I != E; ++I)
731 if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
736 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
738 static bool TypeHasCycleThroughItself(const Type *Ty) {
739 SmallPtrSet<const Type*, 128> VisitedTypes;
741 if (Ty->isAbstract()) { // Optimized case for abstract types.
742 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
744 if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
747 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
749 if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
755 //===----------------------------------------------------------------------===//
756 // Function Type Factory and Value Class...
759 static ManagedStatic<TypeMap<IntegerValType, IntegerType> > IntegerTypes;
761 const IntegerType *IntegerType::get(LLVMContext &C, unsigned NumBits) {
762 assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
763 assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
765 // Check for the built-in integer types
767 case 1: return cast<IntegerType>(Type::getInt1Ty(C));
768 case 8: return cast<IntegerType>(Type::getInt8Ty(C));
769 case 16: return cast<IntegerType>(Type::getInt16Ty(C));
770 case 32: return cast<IntegerType>(Type::getInt32Ty(C));
771 case 64: return cast<IntegerType>(Type::getInt64Ty(C));
776 IntegerValType IVT(NumBits);
777 IntegerType *ITy = 0;
779 // First, see if the type is already in the table, for which
780 // a reader lock suffices.
781 sys::SmartScopedLock<true> L(*TypeMapLock);
782 ITy = IntegerTypes->get(IVT);
785 // Value not found. Derive a new type!
786 ITy = new IntegerType(NumBits);
787 IntegerTypes->add(IVT, ITy);
789 #ifdef DEBUG_MERGE_TYPES
790 DOUT << "Derived new type: " << *ITy << "\n";
795 bool IntegerType::isPowerOf2ByteWidth() const {
796 unsigned BitWidth = getBitWidth();
797 return (BitWidth > 7) && isPowerOf2_32(BitWidth);
800 APInt IntegerType::getMask() const {
801 return APInt::getAllOnesValue(getBitWidth());
804 FunctionValType FunctionValType::get(const FunctionType *FT) {
805 // Build up a FunctionValType
806 std::vector<const Type *> ParamTypes;
807 ParamTypes.reserve(FT->getNumParams());
808 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
809 ParamTypes.push_back(FT->getParamType(i));
810 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
814 // FunctionType::get - The factory function for the FunctionType class...
815 FunctionType *FunctionType::get(const Type *ReturnType,
816 const std::vector<const Type*> &Params,
818 FunctionValType VT(ReturnType, Params, isVarArg);
819 FunctionType *FT = 0;
821 LLVMContextImpl *pImpl = ReturnType->getContext().pImpl;
823 sys::SmartScopedLock<true> L(*TypeMapLock);
824 FT = pImpl->FunctionTypes.get(VT);
827 FT = (FunctionType*) operator new(sizeof(FunctionType) +
828 sizeof(PATypeHandle)*(Params.size()+1));
829 new (FT) FunctionType(ReturnType, Params, isVarArg);
830 pImpl->FunctionTypes.add(VT, FT);
833 #ifdef DEBUG_MERGE_TYPES
834 DOUT << "Derived new type: " << FT << "\n";
839 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
840 assert(ElementType && "Can't get array of <null> types!");
841 assert(isValidElementType(ElementType) && "Invalid type for array element!");
843 ArrayValType AVT(ElementType, NumElements);
846 LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
848 sys::SmartScopedLock<true> L(*TypeMapLock);
849 AT = pImpl->ArrayTypes.get(AVT);
852 // Value not found. Derive a new type!
853 pImpl->ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
855 #ifdef DEBUG_MERGE_TYPES
856 DOUT << "Derived new type: " << *AT << "\n";
861 bool ArrayType::isValidElementType(const Type *ElemTy) {
862 if (ElemTy == Type::getVoidTy(ElemTy->getContext()) ||
863 ElemTy == Type::getLabelTy(ElemTy->getContext()) ||
864 ElemTy == Type::getMetadataTy(ElemTy->getContext()))
867 if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
868 if (PTy->getElementType() == Type::getMetadataTy(ElemTy->getContext()))
874 VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) {
875 assert(ElementType && "Can't get vector of <null> types!");
877 VectorValType PVT(ElementType, NumElements);
880 LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
882 sys::SmartScopedLock<true> L(*TypeMapLock);
883 PT = pImpl->VectorTypes.get(PVT);
886 pImpl->VectorTypes.add(PVT, PT = new VectorType(ElementType, NumElements));
888 #ifdef DEBUG_MERGE_TYPES
889 DOUT << "Derived new type: " << *PT << "\n";
894 bool VectorType::isValidElementType(const Type *ElemTy) {
895 if (ElemTy->isInteger() || ElemTy->isFloatingPoint() ||
896 isa<OpaqueType>(ElemTy))
902 //===----------------------------------------------------------------------===//
903 // Struct Type Factory...
906 StructType *StructType::get(LLVMContext &Context,
907 const std::vector<const Type*> &ETypes,
909 StructValType STV(ETypes, isPacked);
912 LLVMContextImpl *pImpl = Context.pImpl;
914 sys::SmartScopedLock<true> L(*TypeMapLock);
915 ST = pImpl->StructTypes.get(STV);
918 // Value not found. Derive a new type!
919 ST = (StructType*) operator new(sizeof(StructType) +
920 sizeof(PATypeHandle) * ETypes.size());
921 new (ST) StructType(ETypes, isPacked);
922 pImpl->StructTypes.add(STV, ST);
924 #ifdef DEBUG_MERGE_TYPES
925 DOUT << "Derived new type: " << *ST << "\n";
930 StructType *StructType::get(LLVMContext &Context, const Type *type, ...) {
932 std::vector<const llvm::Type*> StructFields;
935 StructFields.push_back(type);
936 type = va_arg(ap, llvm::Type*);
938 return llvm::StructType::get(Context, StructFields);
941 bool StructType::isValidElementType(const Type *ElemTy) {
942 if (ElemTy == Type::getVoidTy(ElemTy->getContext()) ||
943 ElemTy == Type::getLabelTy(ElemTy->getContext()) ||
944 ElemTy == Type::getMetadataTy(ElemTy->getContext()))
947 if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
948 if (PTy->getElementType() == Type::getMetadataTy(ElemTy->getContext()))
955 //===----------------------------------------------------------------------===//
956 // Pointer Type Factory...
959 PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) {
960 assert(ValueType && "Can't get a pointer to <null> type!");
961 assert(ValueType != Type::getVoidTy(ValueType->getContext()) &&
962 "Pointer to void is not valid, use i8* instead!");
963 assert(isValidElementType(ValueType) && "Invalid type for pointer element!");
964 PointerValType PVT(ValueType, AddressSpace);
968 LLVMContextImpl *pImpl = ValueType->getContext().pImpl;
970 sys::SmartScopedLock<true> L(*TypeMapLock);
971 PT = pImpl->PointerTypes.get(PVT);
974 // Value not found. Derive a new type!
975 pImpl->PointerTypes.add(PVT, PT = new PointerType(ValueType, AddressSpace));
977 #ifdef DEBUG_MERGE_TYPES
978 DOUT << "Derived new type: " << *PT << "\n";
983 PointerType *Type::getPointerTo(unsigned addrs) const {
984 return PointerType::get(this, addrs);
987 bool PointerType::isValidElementType(const Type *ElemTy) {
988 if (ElemTy == Type::getVoidTy(ElemTy->getContext()) ||
989 ElemTy == Type::getLabelTy(ElemTy->getContext()))
992 if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
993 if (PTy->getElementType() == Type::getMetadataTy(ElemTy->getContext()))
1000 //===----------------------------------------------------------------------===//
1001 // Derived Type Refinement Functions
1002 //===----------------------------------------------------------------------===//
1004 // addAbstractTypeUser - Notify an abstract type that there is a new user of
1005 // it. This function is called primarily by the PATypeHandle class.
1006 void Type::addAbstractTypeUser(AbstractTypeUser *U) const {
1007 assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
1008 AbstractTypeUsersLock->acquire();
1009 AbstractTypeUsers.push_back(U);
1010 AbstractTypeUsersLock->release();
1014 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1015 // no longer has a handle to the type. This function is called primarily by
1016 // the PATypeHandle class. When there are no users of the abstract type, it
1017 // is annihilated, because there is no way to get a reference to it ever again.
1019 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
1020 AbstractTypeUsersLock->acquire();
1022 // Search from back to front because we will notify users from back to
1023 // front. Also, it is likely that there will be a stack like behavior to
1024 // users that register and unregister users.
1027 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1028 assert(i != 0 && "AbstractTypeUser not in user list!");
1030 --i; // Convert to be in range 0 <= i < size()
1031 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1033 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1035 #ifdef DEBUG_MERGE_TYPES
1036 DOUT << " remAbstractTypeUser[" << (void*)this << ", "
1037 << *this << "][" << i << "] User = " << U << "\n";
1040 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1041 #ifdef DEBUG_MERGE_TYPES
1042 DOUT << "DELETEing unused abstract type: <" << *this
1043 << ">[" << (void*)this << "]" << "\n";
1049 AbstractTypeUsersLock->release();
1052 // unlockedRefineAbstractTypeTo - This function is used when it is discovered
1053 // that the 'this' abstract type is actually equivalent to the NewType
1054 // specified. This causes all users of 'this' to switch to reference the more
1055 // concrete type NewType and for 'this' to be deleted. Only used for internal
1058 void DerivedType::unlockedRefineAbstractTypeTo(const Type *NewType) {
1059 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1060 assert(this != NewType && "Can't refine to myself!");
1061 assert(ForwardType == 0 && "This type has already been refined!");
1063 // The descriptions may be out of date. Conservatively clear them all!
1064 if (AbstractTypeDescriptions.isConstructed())
1065 AbstractTypeDescriptions->clear();
1067 #ifdef DEBUG_MERGE_TYPES
1068 DOUT << "REFINING abstract type [" << (void*)this << " "
1069 << *this << "] to [" << (void*)NewType << " "
1070 << *NewType << "]!\n";
1073 // Make sure to put the type to be refined to into a holder so that if IT gets
1074 // refined, that we will not continue using a dead reference...
1076 PATypeHolder NewTy(NewType);
1077 // Any PATypeHolders referring to this type will now automatically forward o
1078 // the type we are resolved to.
1079 ForwardType = NewType;
1080 if (NewType->isAbstract())
1081 cast<DerivedType>(NewType)->addRef();
1083 // Add a self use of the current type so that we don't delete ourself until
1084 // after the function exits.
1086 PATypeHolder CurrentTy(this);
1088 // To make the situation simpler, we ask the subclass to remove this type from
1089 // the type map, and to replace any type uses with uses of non-abstract types.
1090 // This dramatically limits the amount of recursive type trouble we can find
1094 // Iterate over all of the uses of this type, invoking callback. Each user
1095 // should remove itself from our use list automatically. We have to check to
1096 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1097 // will not cause users to drop off of the use list. If we resolve to ourself
1100 AbstractTypeUsersLock->acquire();
1101 while (!AbstractTypeUsers.empty() && NewTy != this) {
1102 AbstractTypeUser *User = AbstractTypeUsers.back();
1104 unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1105 #ifdef DEBUG_MERGE_TYPES
1106 DOUT << " REFINING user " << OldSize-1 << "[" << (void*)User
1107 << "] of abstract type [" << (void*)this << " "
1108 << *this << "] to [" << (void*)NewTy.get() << " "
1109 << *NewTy << "]!\n";
1111 User->refineAbstractType(this, NewTy);
1113 assert(AbstractTypeUsers.size() != OldSize &&
1114 "AbsTyUser did not remove self from user list!");
1116 AbstractTypeUsersLock->release();
1118 // If we were successful removing all users from the type, 'this' will be
1119 // deleted when the last PATypeHolder is destroyed or updated from this type.
1120 // This may occur on exit of this function, as the CurrentTy object is
1124 // refineAbstractTypeTo - This function is used by external callers to notify
1125 // us that this abstract type is equivalent to another type.
1127 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1128 // All recursive calls will go through unlockedRefineAbstractTypeTo,
1129 // to avoid deadlock problems.
1130 sys::SmartScopedLock<true> L(*TypeMapLock);
1131 unlockedRefineAbstractTypeTo(NewType);
1134 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1135 // the current type has transitioned from being abstract to being concrete.
1137 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1138 #ifdef DEBUG_MERGE_TYPES
1139 DOUT << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1142 AbstractTypeUsersLock->acquire();
1143 unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1144 while (!AbstractTypeUsers.empty()) {
1145 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1146 ATU->typeBecameConcrete(this);
1148 assert(AbstractTypeUsers.size() < OldSize-- &&
1149 "AbstractTypeUser did not remove itself from the use list!");
1151 AbstractTypeUsersLock->release();
1154 // refineAbstractType - Called when a contained type is found to be more
1155 // concrete - this could potentially change us from an abstract type to a
1158 void FunctionType::refineAbstractType(const DerivedType *OldType,
1159 const Type *NewType) {
1160 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1161 pImpl->FunctionTypes.RefineAbstractType(this, OldType, NewType);
1164 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1165 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1166 pImpl->FunctionTypes.TypeBecameConcrete(this, AbsTy);
1170 // refineAbstractType - Called when a contained type is found to be more
1171 // concrete - this could potentially change us from an abstract type to a
1174 void ArrayType::refineAbstractType(const DerivedType *OldType,
1175 const Type *NewType) {
1176 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1177 pImpl->ArrayTypes.RefineAbstractType(this, OldType, NewType);
1180 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1181 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1182 pImpl->ArrayTypes.TypeBecameConcrete(this, AbsTy);
1185 // refineAbstractType - Called when a contained type is found to be more
1186 // concrete - this could potentially change us from an abstract type to a
1189 void VectorType::refineAbstractType(const DerivedType *OldType,
1190 const Type *NewType) {
1191 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1192 pImpl->VectorTypes.RefineAbstractType(this, OldType, NewType);
1195 void VectorType::typeBecameConcrete(const DerivedType *AbsTy) {
1196 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1197 pImpl->VectorTypes.TypeBecameConcrete(this, AbsTy);
1200 // refineAbstractType - Called when a contained type is found to be more
1201 // concrete - this could potentially change us from an abstract type to a
1204 void StructType::refineAbstractType(const DerivedType *OldType,
1205 const Type *NewType) {
1206 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1207 pImpl->StructTypes.RefineAbstractType(this, OldType, NewType);
1210 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1211 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1212 pImpl->StructTypes.TypeBecameConcrete(this, AbsTy);
1215 // refineAbstractType - Called when a contained type is found to be more
1216 // concrete - this could potentially change us from an abstract type to a
1219 void PointerType::refineAbstractType(const DerivedType *OldType,
1220 const Type *NewType) {
1221 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1222 pImpl->PointerTypes.RefineAbstractType(this, OldType, NewType);
1225 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1226 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1227 pImpl->PointerTypes.TypeBecameConcrete(this, AbsTy);
1230 bool SequentialType::indexValid(const Value *V) const {
1231 if (isa<IntegerType>(V->getType()))
1237 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1239 OS << "<null> value!\n";
1245 std::ostream &operator<<(std::ostream &OS, const Type &T) {
1250 raw_ostream &operator<<(raw_ostream &OS, const Type &T) {