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/ArrayRef.h"
21 #include "llvm/ADT/DepthFirstIterator.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/SCCIterator.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/Threading.h"
36 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
37 // created and later destroyed, all in an effort to make sure that there is only
38 // a single canonical version of a type.
40 // #define DEBUG_MERGE_TYPES 1
42 AbstractTypeUser::~AbstractTypeUser() {}
44 void AbstractTypeUser::setType(Value *V, const Type *NewTy) {
48 //===----------------------------------------------------------------------===//
49 // Type Class Implementation
50 //===----------------------------------------------------------------------===//
52 /// Because of the way Type subclasses are allocated, this function is necessary
53 /// to use the correct kind of "delete" operator to deallocate the Type object.
54 /// Some type objects (FunctionTy, StructTy) allocate additional space
55 /// after the space for their derived type to hold the contained types array of
56 /// PATypeHandles. Using this allocation scheme means all the PATypeHandles are
57 /// allocated with the type object, decreasing allocations and eliminating the
58 /// need for a std::vector to be used in the Type class itself.
59 /// @brief Type destruction function
60 void Type::destroy() const {
61 // Nothing calls getForwardedType from here on.
62 if (ForwardType && ForwardType->isAbstract()) {
63 ForwardType->dropRef();
67 // Structures and Functions allocate their contained types past the end of
68 // the type object itself. These need to be destroyed differently than the
70 if (this->isFunctionTy() || this->isStructTy()) {
71 // First, make sure we destruct any PATypeHandles allocated by these
72 // subclasses. They must be manually destructed.
73 for (unsigned i = 0; i < NumContainedTys; ++i)
74 ContainedTys[i].PATypeHandle::~PATypeHandle();
76 // Now call the destructor for the subclass directly because we're going
77 // to delete this as an array of char.
78 if (this->isFunctionTy())
79 static_cast<const FunctionType*>(this)->FunctionType::~FunctionType();
82 static_cast<const StructType*>(this)->StructType::~StructType();
85 // Finally, remove the memory as an array deallocation of the chars it was
87 operator delete(const_cast<Type *>(this));
90 } else if (const OpaqueType *opaque_this = dyn_cast<OpaqueType>(this)) {
91 LLVMContextImpl *pImpl = this->getContext().pImpl;
92 pImpl->OpaqueTypes.erase(opaque_this);
95 // For all the other type subclasses, there is either no contained types or
96 // just one (all Sequentials). For Sequentials, the PATypeHandle is not
97 // allocated past the type object, its included directly in the SequentialType
98 // class. This means we can safely just do "normal" delete of this object and
99 // all the destructors that need to run will be run.
103 const Type *Type::getPrimitiveType(LLVMContext &C, TypeID IDNumber) {
105 case VoidTyID : return getVoidTy(C);
106 case FloatTyID : return getFloatTy(C);
107 case DoubleTyID : return getDoubleTy(C);
108 case X86_FP80TyID : return getX86_FP80Ty(C);
109 case FP128TyID : return getFP128Ty(C);
110 case PPC_FP128TyID : return getPPC_FP128Ty(C);
111 case LabelTyID : return getLabelTy(C);
112 case MetadataTyID : return getMetadataTy(C);
113 case X86_MMXTyID : return getX86_MMXTy(C);
119 const Type *Type::getVAArgsPromotedType(LLVMContext &C) const {
120 if (ID == IntegerTyID && getSubclassData() < 32)
121 return Type::getInt32Ty(C);
122 else if (ID == FloatTyID)
123 return Type::getDoubleTy(C);
128 /// getScalarType - If this is a vector type, return the element type,
129 /// otherwise return this.
130 const Type *Type::getScalarType() const {
131 if (const VectorType *VTy = dyn_cast<VectorType>(this))
132 return VTy->getElementType();
136 /// isIntegerTy - Return true if this is an IntegerType of the specified width.
137 bool Type::isIntegerTy(unsigned Bitwidth) const {
138 return isIntegerTy() && cast<IntegerType>(this)->getBitWidth() == Bitwidth;
141 /// isIntOrIntVectorTy - Return true if this is an integer type or a vector of
144 bool Type::isIntOrIntVectorTy() const {
147 if (ID != Type::VectorTyID) return false;
149 return cast<VectorType>(this)->getElementType()->isIntegerTy();
152 /// isFPOrFPVectorTy - Return true if this is a FP type or a vector of FP types.
154 bool Type::isFPOrFPVectorTy() const {
155 if (ID == Type::FloatTyID || ID == Type::DoubleTyID ||
156 ID == Type::FP128TyID || ID == Type::X86_FP80TyID ||
157 ID == Type::PPC_FP128TyID)
159 if (ID != Type::VectorTyID) return false;
161 return cast<VectorType>(this)->getElementType()->isFloatingPointTy();
164 // canLosslesslyBitCastTo - Return true if this type can be converted to
165 // 'Ty' without any reinterpretation of bits. For example, i8* to i32*.
167 bool Type::canLosslesslyBitCastTo(const Type *Ty) const {
168 // Identity cast means no change so return true
172 // They are not convertible unless they are at least first class types
173 if (!this->isFirstClassType() || !Ty->isFirstClassType())
176 // Vector -> Vector conversions are always lossless if the two vector types
177 // have the same size, otherwise not. Also, 64-bit vector types can be
178 // converted to x86mmx.
179 if (const VectorType *thisPTy = dyn_cast<VectorType>(this)) {
180 if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
181 return thisPTy->getBitWidth() == thatPTy->getBitWidth();
182 if (Ty->getTypeID() == Type::X86_MMXTyID &&
183 thisPTy->getBitWidth() == 64)
187 if (this->getTypeID() == Type::X86_MMXTyID)
188 if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
189 if (thatPTy->getBitWidth() == 64)
192 // At this point we have only various mismatches of the first class types
193 // remaining and ptr->ptr. Just select the lossless conversions. Everything
194 // else is not lossless.
195 if (this->isPointerTy())
196 return Ty->isPointerTy();
197 return false; // Other types have no identity values
200 unsigned Type::getPrimitiveSizeInBits() const {
201 switch (getTypeID()) {
202 case Type::FloatTyID: return 32;
203 case Type::DoubleTyID: return 64;
204 case Type::X86_FP80TyID: return 80;
205 case Type::FP128TyID: return 128;
206 case Type::PPC_FP128TyID: return 128;
207 case Type::X86_MMXTyID: return 64;
208 case Type::IntegerTyID: return cast<IntegerType>(this)->getBitWidth();
209 case Type::VectorTyID: return cast<VectorType>(this)->getBitWidth();
214 /// getScalarSizeInBits - If this is a vector type, return the
215 /// getPrimitiveSizeInBits value for the element type. Otherwise return the
216 /// getPrimitiveSizeInBits value for this type.
217 unsigned Type::getScalarSizeInBits() const {
218 return getScalarType()->getPrimitiveSizeInBits();
221 /// getFPMantissaWidth - Return the width of the mantissa of this type. This
222 /// is only valid on floating point types. If the FP type does not
223 /// have a stable mantissa (e.g. ppc long double), this method returns -1.
224 int Type::getFPMantissaWidth() const {
225 if (const VectorType *VTy = dyn_cast<VectorType>(this))
226 return VTy->getElementType()->getFPMantissaWidth();
227 assert(isFloatingPointTy() && "Not a floating point type!");
228 if (ID == FloatTyID) return 24;
229 if (ID == DoubleTyID) return 53;
230 if (ID == X86_FP80TyID) return 64;
231 if (ID == FP128TyID) return 113;
232 assert(ID == PPC_FP128TyID && "unknown fp type");
236 /// isSizedDerivedType - Derived types like structures and arrays are sized
237 /// iff all of the members of the type are sized as well. Since asking for
238 /// their size is relatively uncommon, move this operation out of line.
239 bool Type::isSizedDerivedType() const {
240 if (this->isIntegerTy())
243 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
244 return ATy->getElementType()->isSized();
246 if (const VectorType *PTy = dyn_cast<VectorType>(this))
247 return PTy->getElementType()->isSized();
249 if (!this->isStructTy())
252 // Okay, our struct is sized if all of the elements are...
253 for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
254 if (!(*I)->isSized())
260 /// getForwardedTypeInternal - This method is used to implement the union-find
261 /// algorithm for when a type is being forwarded to another type.
262 const Type *Type::getForwardedTypeInternal() const {
263 assert(ForwardType && "This type is not being forwarded to another type!");
265 // Check to see if the forwarded type has been forwarded on. If so, collapse
266 // the forwarding links.
267 const Type *RealForwardedType = ForwardType->getForwardedType();
268 if (!RealForwardedType)
269 return ForwardType; // No it's not forwarded again
271 // Yes, it is forwarded again. First thing, add the reference to the new
273 if (RealForwardedType->isAbstract())
274 RealForwardedType->addRef();
276 // Now drop the old reference. This could cause ForwardType to get deleted.
277 // ForwardType must be abstract because only abstract types can have their own
279 ForwardType->dropRef();
281 // Return the updated type.
282 ForwardType = RealForwardedType;
286 void Type::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
287 llvm_unreachable("Attempting to refine a derived type!");
289 void Type::typeBecameConcrete(const DerivedType *AbsTy) {
290 llvm_unreachable("DerivedType is already a concrete type!");
294 std::string Type::getDescription() const {
295 LLVMContextImpl *pImpl = getContext().pImpl;
298 pImpl->AbstractTypeDescriptions :
299 pImpl->ConcreteTypeDescriptions;
302 raw_string_ostream DescOS(DescStr);
303 Map.print(this, DescOS);
308 bool StructType::indexValid(const Value *V) const {
309 // Structure indexes require 32-bit integer constants.
310 if (V->getType()->isIntegerTy(32))
311 if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
312 return indexValid(CU->getZExtValue());
316 bool StructType::indexValid(unsigned V) const {
317 return V < NumContainedTys;
320 // getTypeAtIndex - Given an index value into the type, return the type of the
321 // element. For a structure type, this must be a constant value...
323 const Type *StructType::getTypeAtIndex(const Value *V) const {
324 unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
325 return getTypeAtIndex(Idx);
328 const Type *StructType::getTypeAtIndex(unsigned Idx) const {
329 assert(indexValid(Idx) && "Invalid structure index!");
330 return ContainedTys[Idx];
334 //===----------------------------------------------------------------------===//
335 // Primitive 'Type' data
336 //===----------------------------------------------------------------------===//
338 const Type *Type::getVoidTy(LLVMContext &C) {
339 return &C.pImpl->VoidTy;
342 const Type *Type::getLabelTy(LLVMContext &C) {
343 return &C.pImpl->LabelTy;
346 const Type *Type::getFloatTy(LLVMContext &C) {
347 return &C.pImpl->FloatTy;
350 const Type *Type::getDoubleTy(LLVMContext &C) {
351 return &C.pImpl->DoubleTy;
354 const Type *Type::getMetadataTy(LLVMContext &C) {
355 return &C.pImpl->MetadataTy;
358 const Type *Type::getX86_FP80Ty(LLVMContext &C) {
359 return &C.pImpl->X86_FP80Ty;
362 const Type *Type::getFP128Ty(LLVMContext &C) {
363 return &C.pImpl->FP128Ty;
366 const Type *Type::getPPC_FP128Ty(LLVMContext &C) {
367 return &C.pImpl->PPC_FP128Ty;
370 const Type *Type::getX86_MMXTy(LLVMContext &C) {
371 return &C.pImpl->X86_MMXTy;
374 const IntegerType *Type::getIntNTy(LLVMContext &C, unsigned N) {
375 return IntegerType::get(C, N);
378 const IntegerType *Type::getInt1Ty(LLVMContext &C) {
379 return &C.pImpl->Int1Ty;
382 const IntegerType *Type::getInt8Ty(LLVMContext &C) {
383 return &C.pImpl->Int8Ty;
386 const IntegerType *Type::getInt16Ty(LLVMContext &C) {
387 return &C.pImpl->Int16Ty;
390 const IntegerType *Type::getInt32Ty(LLVMContext &C) {
391 return &C.pImpl->Int32Ty;
394 const IntegerType *Type::getInt64Ty(LLVMContext &C) {
395 return &C.pImpl->Int64Ty;
398 const PointerType *Type::getFloatPtrTy(LLVMContext &C, unsigned AS) {
399 return getFloatTy(C)->getPointerTo(AS);
402 const PointerType *Type::getDoublePtrTy(LLVMContext &C, unsigned AS) {
403 return getDoubleTy(C)->getPointerTo(AS);
406 const PointerType *Type::getX86_FP80PtrTy(LLVMContext &C, unsigned AS) {
407 return getX86_FP80Ty(C)->getPointerTo(AS);
410 const PointerType *Type::getFP128PtrTy(LLVMContext &C, unsigned AS) {
411 return getFP128Ty(C)->getPointerTo(AS);
414 const PointerType *Type::getPPC_FP128PtrTy(LLVMContext &C, unsigned AS) {
415 return getPPC_FP128Ty(C)->getPointerTo(AS);
418 const PointerType *Type::getX86_MMXPtrTy(LLVMContext &C, unsigned AS) {
419 return getX86_MMXTy(C)->getPointerTo(AS);
422 const PointerType *Type::getIntNPtrTy(LLVMContext &C, unsigned N, unsigned AS) {
423 return getIntNTy(C, N)->getPointerTo(AS);
426 const PointerType *Type::getInt1PtrTy(LLVMContext &C, unsigned AS) {
427 return getInt1Ty(C)->getPointerTo(AS);
430 const PointerType *Type::getInt8PtrTy(LLVMContext &C, unsigned AS) {
431 return getInt8Ty(C)->getPointerTo(AS);
434 const PointerType *Type::getInt16PtrTy(LLVMContext &C, unsigned AS) {
435 return getInt16Ty(C)->getPointerTo(AS);
438 const PointerType *Type::getInt32PtrTy(LLVMContext &C, unsigned AS) {
439 return getInt32Ty(C)->getPointerTo(AS);
442 const PointerType *Type::getInt64PtrTy(LLVMContext &C, unsigned AS) {
443 return getInt64Ty(C)->getPointerTo(AS);
446 //===----------------------------------------------------------------------===//
447 // Derived Type Constructors
448 //===----------------------------------------------------------------------===//
450 /// isValidReturnType - Return true if the specified type is valid as a return
452 bool FunctionType::isValidReturnType(const Type *RetTy) {
453 return !RetTy->isFunctionTy() && !RetTy->isLabelTy() &&
454 !RetTy->isMetadataTy();
457 /// isValidArgumentType - Return true if the specified type is valid as an
459 bool FunctionType::isValidArgumentType(const Type *ArgTy) {
460 return ArgTy->isFirstClassType() || ArgTy->isOpaqueTy();
463 FunctionType::FunctionType(const Type *Result,
464 ArrayRef<const Type*> Params,
466 : DerivedType(Result->getContext(), FunctionTyID), isVarArgs(IsVarArgs) {
467 ContainedTys = reinterpret_cast<PATypeHandle*>(this+1);
468 NumContainedTys = Params.size() + 1; // + 1 for result type
469 assert(isValidReturnType(Result) && "invalid return type for function");
472 bool isAbstract = Result->isAbstract();
473 new (&ContainedTys[0]) PATypeHandle(Result, this);
475 for (unsigned i = 0; i != Params.size(); ++i) {
476 assert(isValidArgumentType(Params[i]) &&
477 "Not a valid type for function argument!");
478 new (&ContainedTys[i+1]) PATypeHandle(Params[i], this);
479 isAbstract |= Params[i]->isAbstract();
482 // Calculate whether or not this type is abstract
483 setAbstract(isAbstract);
486 StructType::StructType(LLVMContext &C,
487 ArrayRef<const Type*> Types, bool isPacked)
488 : CompositeType(C, StructTyID) {
489 ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
490 NumContainedTys = Types.size();
491 setSubclassData(isPacked);
492 bool isAbstract = false;
493 for (unsigned i = 0; i < Types.size(); ++i) {
494 assert(Types[i] && "<null> type for structure field!");
495 assert(isValidElementType(Types[i]) &&
496 "Invalid type for structure element!");
497 new (&ContainedTys[i]) PATypeHandle(Types[i], this);
498 isAbstract |= Types[i]->isAbstract();
501 // Calculate whether or not this type is abstract
502 setAbstract(isAbstract);
505 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
506 : SequentialType(ArrayTyID, ElType) {
509 // Calculate whether or not this type is abstract
510 setAbstract(ElType->isAbstract());
513 VectorType::VectorType(const Type *ElType, unsigned NumEl)
514 : SequentialType(VectorTyID, ElType) {
516 setAbstract(ElType->isAbstract());
517 assert(NumEl > 0 && "NumEl of a VectorType must be greater than 0");
518 assert(isValidElementType(ElType) &&
519 "Elements of a VectorType must be a primitive type");
524 PointerType::PointerType(const Type *E, unsigned AddrSpace)
525 : SequentialType(PointerTyID, E) {
526 AddressSpace = AddrSpace;
527 // Calculate whether or not this type is abstract
528 setAbstract(E->isAbstract());
531 OpaqueType::OpaqueType(LLVMContext &C) : DerivedType(C, OpaqueTyID) {
533 #ifdef DEBUG_MERGE_TYPES
534 DEBUG(dbgs() << "Derived new type: " << *this << "\n");
538 void PATypeHolder::destroy() {
542 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
543 // another (more concrete) type, we must eliminate all references to other
544 // types, to avoid some circular reference problems.
545 void DerivedType::dropAllTypeUses() {
546 if (NumContainedTys != 0) {
547 // The type must stay abstract. To do this, we insert a pointer to a type
548 // that will never get resolved, thus will always be abstract.
549 ContainedTys[0] = getContext().pImpl->AlwaysOpaqueTy;
551 // Change the rest of the types to be Int32Ty's. It doesn't matter what we
552 // pick so long as it doesn't point back to this type. We choose something
553 // concrete to avoid overhead for adding to AbstractTypeUser lists and
555 const Type *ConcreteTy = Type::getInt32Ty(getContext());
556 for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
557 ContainedTys[i] = ConcreteTy;
564 /// TypePromotionGraph and graph traits - this is designed to allow us to do
565 /// efficient SCC processing of type graphs. This is the exact same as
566 /// GraphTraits<Type*>, except that we pretend that concrete types have no
567 /// children to avoid processing them.
568 struct TypePromotionGraph {
570 TypePromotionGraph(Type *T) : Ty(T) {}
576 template <> struct GraphTraits<TypePromotionGraph> {
577 typedef Type NodeType;
578 typedef Type::subtype_iterator ChildIteratorType;
580 static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
581 static inline ChildIteratorType child_begin(NodeType *N) {
583 return N->subtype_begin();
584 // No need to process children of concrete types.
585 return N->subtype_end();
587 static inline ChildIteratorType child_end(NodeType *N) {
588 return N->subtype_end();
594 // PromoteAbstractToConcrete - This is a recursive function that walks a type
595 // graph calculating whether or not a type is abstract.
597 void Type::PromoteAbstractToConcrete() {
598 if (!isAbstract()) return;
600 scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
601 scc_iterator<TypePromotionGraph> SE = scc_end (TypePromotionGraph(this));
603 for (; SI != SE; ++SI) {
604 std::vector<Type*> &SCC = *SI;
606 // Concrete types are leaves in the tree. Since an SCC will either be all
607 // abstract or all concrete, we only need to check one type.
608 if (!SCC[0]->isAbstract()) continue;
610 if (SCC[0]->isOpaqueTy())
611 return; // Not going to be concrete, sorry.
613 // If all of the children of all of the types in this SCC are concrete,
614 // then this SCC is now concrete as well. If not, neither this SCC, nor
615 // any parent SCCs will be concrete, so we might as well just exit.
616 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
617 for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
618 E = SCC[i]->subtype_end(); CI != E; ++CI)
619 if ((*CI)->isAbstract())
620 // If the child type is in our SCC, it doesn't make the entire SCC
621 // abstract unless there is a non-SCC abstract type.
622 if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
623 return; // Not going to be concrete, sorry.
625 // Okay, we just discovered this whole SCC is now concrete, mark it as
627 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
628 assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
630 SCC[i]->setAbstract(false);
633 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
634 assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
635 // The type just became concrete, notify all users!
636 cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
642 //===----------------------------------------------------------------------===//
643 // Type Structural Equality Testing
644 //===----------------------------------------------------------------------===//
646 // TypesEqual - Two types are considered structurally equal if they have the
647 // same "shape": Every level and element of the types have identical primitive
648 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
649 // be pointer equals to be equivalent though. This uses an optimistic algorithm
650 // that assumes that two graphs are the same until proven otherwise.
652 static bool TypesEqual(const Type *Ty, const Type *Ty2,
653 std::map<const Type *, const Type *> &EqTypes) {
654 if (Ty == Ty2) return true;
655 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
656 if (Ty->isOpaqueTy())
657 return false; // Two unequal opaque types are never equal
659 std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
660 if (It != EqTypes.end())
661 return It->second == Ty2; // Looping back on a type, check for equality
663 // Otherwise, add the mapping to the table to make sure we don't get
664 // recursion on the types...
665 EqTypes.insert(It, std::make_pair(Ty, Ty2));
667 // Two really annoying special cases that breaks an otherwise nice simple
668 // algorithm is the fact that arraytypes have sizes that differentiates types,
669 // and that function types can be varargs or not. Consider this now.
671 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
672 const IntegerType *ITy2 = cast<IntegerType>(Ty2);
673 return ITy->getBitWidth() == ITy2->getBitWidth();
676 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
677 const PointerType *PTy2 = cast<PointerType>(Ty2);
678 return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
679 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
682 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
683 const StructType *STy2 = cast<StructType>(Ty2);
684 if (STy->getNumElements() != STy2->getNumElements()) return false;
685 if (STy->isPacked() != STy2->isPacked()) return false;
686 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
687 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
692 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
693 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
694 return ATy->getNumElements() == ATy2->getNumElements() &&
695 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
698 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
699 const VectorType *PTy2 = cast<VectorType>(Ty2);
700 return PTy->getNumElements() == PTy2->getNumElements() &&
701 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
704 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
705 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
706 if (FTy->isVarArg() != FTy2->isVarArg() ||
707 FTy->getNumParams() != FTy2->getNumParams() ||
708 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
710 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
711 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
717 llvm_unreachable("Unknown derived type!");
721 namespace llvm { // in namespace llvm so findable by ADL
722 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
723 std::map<const Type *, const Type *> EqTypes;
724 return ::TypesEqual(Ty, Ty2, EqTypes);
728 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
729 // TargetTy in the type graph. We know that Ty is an abstract type, so if we
730 // ever reach a non-abstract type, we know that we don't need to search the
732 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
733 SmallPtrSet<const Type*, 128> &VisitedTypes) {
734 if (TargetTy == CurTy) return true;
735 if (!CurTy->isAbstract()) return false;
737 if (!VisitedTypes.insert(CurTy))
738 return false; // Already been here.
740 for (Type::subtype_iterator I = CurTy->subtype_begin(),
741 E = CurTy->subtype_end(); I != E; ++I)
742 if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
747 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
748 SmallPtrSet<const Type*, 128> &VisitedTypes) {
749 if (TargetTy == CurTy) return true;
751 if (!VisitedTypes.insert(CurTy))
752 return false; // Already been here.
754 for (Type::subtype_iterator I = CurTy->subtype_begin(),
755 E = CurTy->subtype_end(); I != E; ++I)
756 if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
761 /// TypeHasCycleThroughItself - Return true if the specified type has
762 /// a cycle back to itself.
764 namespace llvm { // in namespace llvm so it's findable by ADL
765 static bool TypeHasCycleThroughItself(const Type *Ty) {
766 SmallPtrSet<const Type*, 128> VisitedTypes;
768 if (Ty->isAbstract()) { // Optimized case for abstract types.
769 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
771 if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
774 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
776 if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
783 //===----------------------------------------------------------------------===//
784 // Function Type Factory and Value Class...
786 const IntegerType *IntegerType::get(LLVMContext &C, unsigned NumBits) {
787 assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
788 assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
790 // Check for the built-in integer types
792 case 1: return cast<IntegerType>(Type::getInt1Ty(C));
793 case 8: return cast<IntegerType>(Type::getInt8Ty(C));
794 case 16: return cast<IntegerType>(Type::getInt16Ty(C));
795 case 32: return cast<IntegerType>(Type::getInt32Ty(C));
796 case 64: return cast<IntegerType>(Type::getInt64Ty(C));
801 LLVMContextImpl *pImpl = C.pImpl;
803 IntegerValType IVT(NumBits);
804 IntegerType *ITy = 0;
806 // First, see if the type is already in the table, for which
807 // a reader lock suffices.
808 ITy = pImpl->IntegerTypes.get(IVT);
811 // Value not found. Derive a new type!
812 ITy = new IntegerType(C, NumBits);
813 pImpl->IntegerTypes.add(IVT, ITy);
815 #ifdef DEBUG_MERGE_TYPES
816 DEBUG(dbgs() << "Derived new type: " << *ITy << "\n");
821 bool IntegerType::isPowerOf2ByteWidth() const {
822 unsigned BitWidth = getBitWidth();
823 return (BitWidth > 7) && isPowerOf2_32(BitWidth);
826 APInt IntegerType::getMask() const {
827 return APInt::getAllOnesValue(getBitWidth());
830 FunctionValType FunctionValType::get(const FunctionType *FT) {
831 // Build up a FunctionValType
832 std::vector<const Type *> ParamTypes;
833 ParamTypes.reserve(FT->getNumParams());
834 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
835 ParamTypes.push_back(FT->getParamType(i));
836 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
840 // FunctionType::get - The factory function for the FunctionType class...
841 FunctionType *FunctionType::get(const Type *ReturnType,
842 ArrayRef<const Type*> Params,
844 FunctionValType VT(ReturnType, Params, isVarArg);
845 FunctionType *FT = 0;
847 LLVMContextImpl *pImpl = ReturnType->getContext().pImpl;
849 FT = pImpl->FunctionTypes.get(VT);
852 FT = (FunctionType*) operator new(sizeof(FunctionType) +
853 sizeof(PATypeHandle)*(Params.size()+1));
854 new (FT) FunctionType(ReturnType, Params, isVarArg);
855 pImpl->FunctionTypes.add(VT, FT);
858 #ifdef DEBUG_MERGE_TYPES
859 DEBUG(dbgs() << "Derived new type: " << FT << "\n");
864 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
865 assert(ElementType && "Can't get array of <null> types!");
866 assert(isValidElementType(ElementType) && "Invalid type for array element!");
868 ArrayValType AVT(ElementType, NumElements);
871 LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
873 AT = pImpl->ArrayTypes.get(AVT);
876 // Value not found. Derive a new type!
877 pImpl->ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
879 #ifdef DEBUG_MERGE_TYPES
880 DEBUG(dbgs() << "Derived new type: " << *AT << "\n");
885 bool ArrayType::isValidElementType(const Type *ElemTy) {
886 return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
887 !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
890 VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) {
891 assert(ElementType && "Can't get vector of <null> types!");
893 VectorValType PVT(ElementType, NumElements);
896 LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
898 PT = pImpl->VectorTypes.get(PVT);
901 pImpl->VectorTypes.add(PVT, PT = new VectorType(ElementType, NumElements));
903 #ifdef DEBUG_MERGE_TYPES
904 DEBUG(dbgs() << "Derived new type: " << *PT << "\n");
909 bool VectorType::isValidElementType(const Type *ElemTy) {
910 return ElemTy->isIntegerTy() || ElemTy->isFloatingPointTy() ||
911 ElemTy->isOpaqueTy();
914 //===----------------------------------------------------------------------===//
915 // Struct Type Factory...
918 StructType *StructType::get(LLVMContext &Context,
919 ArrayRef<const Type*> ETypes,
921 StructValType STV(ETypes, isPacked);
924 LLVMContextImpl *pImpl = Context.pImpl;
926 ST = pImpl->StructTypes.get(STV);
929 // Value not found. Derive a new type!
930 ST = (StructType*) operator new(sizeof(StructType) +
931 sizeof(PATypeHandle) * ETypes.size());
932 new (ST) StructType(Context, ETypes, isPacked);
933 pImpl->StructTypes.add(STV, ST);
935 #ifdef DEBUG_MERGE_TYPES
936 DEBUG(dbgs() << "Derived new type: " << *ST << "\n");
941 StructType *StructType::get(LLVMContext &Context, const Type *type, ...) {
943 std::vector<const llvm::Type*> StructFields;
946 StructFields.push_back(type);
947 type = va_arg(ap, llvm::Type*);
949 return llvm::StructType::get(Context, StructFields);
952 bool StructType::isValidElementType(const Type *ElemTy) {
953 return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
954 !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
958 //===----------------------------------------------------------------------===//
959 // Pointer Type Factory...
962 PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) {
963 assert(ValueType && "Can't get a pointer to <null> type!");
964 assert(ValueType->getTypeID() != VoidTyID &&
965 "Pointer to void is not valid, use i8* instead!");
966 assert(isValidElementType(ValueType) && "Invalid type for pointer element!");
967 PointerValType PVT(ValueType, AddressSpace);
971 LLVMContextImpl *pImpl = ValueType->getContext().pImpl;
973 PT = pImpl->PointerTypes.get(PVT);
976 // Value not found. Derive a new type!
977 pImpl->PointerTypes.add(PVT, PT = new PointerType(ValueType, AddressSpace));
979 #ifdef DEBUG_MERGE_TYPES
980 DEBUG(dbgs() << "Derived new type: " << *PT << "\n");
985 const PointerType *Type::getPointerTo(unsigned addrs) const {
986 return PointerType::get(this, addrs);
989 bool PointerType::isValidElementType(const Type *ElemTy) {
990 return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
991 !ElemTy->isMetadataTy();
995 //===----------------------------------------------------------------------===//
996 // Opaque Type Factory...
999 OpaqueType *OpaqueType::get(LLVMContext &C) {
1000 OpaqueType *OT = new OpaqueType(C); // All opaque types are distinct.
1001 LLVMContextImpl *pImpl = C.pImpl;
1002 pImpl->OpaqueTypes.insert(OT);
1008 //===----------------------------------------------------------------------===//
1009 // Derived Type Refinement Functions
1010 //===----------------------------------------------------------------------===//
1012 // addAbstractTypeUser - Notify an abstract type that there is a new user of
1013 // it. This function is called primarily by the PATypeHandle class.
1014 void Type::addAbstractTypeUser(AbstractTypeUser *U) const {
1015 assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
1016 AbstractTypeUsers.push_back(U);
1020 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1021 // no longer has a handle to the type. This function is called primarily by
1022 // the PATypeHandle class. When there are no users of the abstract type, it
1023 // is annihilated, because there is no way to get a reference to it ever again.
1025 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
1027 // Search from back to front because we will notify users from back to
1028 // front. Also, it is likely that there will be a stack like behavior to
1029 // users that register and unregister users.
1032 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1033 assert(i != 0 && "AbstractTypeUser not in user list!");
1035 --i; // Convert to be in range 0 <= i < size()
1036 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1038 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1040 #ifdef DEBUG_MERGE_TYPES
1041 DEBUG(dbgs() << " remAbstractTypeUser[" << (void*)this << ", "
1042 << *this << "][" << i << "] User = " << U << "\n");
1045 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1046 #ifdef DEBUG_MERGE_TYPES
1047 DEBUG(dbgs() << "DELETEing unused abstract type: <" << *this
1048 << ">[" << (void*)this << "]" << "\n");
1055 // refineAbstractTypeTo - This function is used when it is discovered
1056 // that the 'this' abstract type is actually equivalent to the NewType
1057 // specified. This causes all users of 'this' to switch to reference the more
1058 // concrete type NewType and for 'this' to be deleted. Only used for internal
1061 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1062 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1063 assert(this != NewType && "Can't refine to myself!");
1064 assert(ForwardType == 0 && "This type has already been refined!");
1066 LLVMContextImpl *pImpl = getContext().pImpl;
1068 // The descriptions may be out of date. Conservatively clear them all!
1069 pImpl->AbstractTypeDescriptions.clear();
1071 #ifdef DEBUG_MERGE_TYPES
1072 DEBUG(dbgs() << "REFINING abstract type [" << (void*)this << " "
1073 << *this << "] to [" << (void*)NewType << " "
1074 << *NewType << "]!\n");
1077 // Make sure to put the type to be refined to into a holder so that if IT gets
1078 // refined, that we will not continue using a dead reference...
1080 PATypeHolder NewTy(NewType);
1081 // Any PATypeHolders referring to this type will now automatically forward to
1082 // the type we are resolved to.
1083 ForwardType = NewType;
1084 if (ForwardType->isAbstract())
1085 ForwardType->addRef();
1087 // Add a self use of the current type so that we don't delete ourself until
1088 // after the function exits.
1090 PATypeHolder CurrentTy(this);
1092 // To make the situation simpler, we ask the subclass to remove this type from
1093 // the type map, and to replace any type uses with uses of non-abstract types.
1094 // This dramatically limits the amount of recursive type trouble we can find
1098 // Iterate over all of the uses of this type, invoking callback. Each user
1099 // should remove itself from our use list automatically. We have to check to
1100 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1101 // will not cause users to drop off of the use list. If we resolve to ourself
1104 while (!AbstractTypeUsers.empty() && NewTy != this) {
1105 AbstractTypeUser *User = AbstractTypeUsers.back();
1107 unsigned OldSize = AbstractTypeUsers.size(); (void)OldSize;
1108 #ifdef DEBUG_MERGE_TYPES
1109 DEBUG(dbgs() << " REFINING user " << OldSize-1 << "[" << (void*)User
1110 << "] of abstract type [" << (void*)this << " "
1111 << *this << "] to [" << (void*)NewTy.get() << " "
1112 << *NewTy << "]!\n");
1114 User->refineAbstractType(this, NewTy);
1116 assert(AbstractTypeUsers.size() != OldSize &&
1117 "AbsTyUser did not remove self from user list!");
1120 // If we were successful removing all users from the type, 'this' will be
1121 // deleted when the last PATypeHolder is destroyed or updated from this type.
1122 // This may occur on exit of this function, as the CurrentTy object is
1126 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1127 // the current type has transitioned from being abstract to being concrete.
1129 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1130 #ifdef DEBUG_MERGE_TYPES
1131 DEBUG(dbgs() << "typeIsREFINED type: " << (void*)this << " " << *this <<"\n");
1134 unsigned OldSize = AbstractTypeUsers.size(); (void)OldSize;
1135 while (!AbstractTypeUsers.empty()) {
1136 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1137 ATU->typeBecameConcrete(this);
1139 assert(AbstractTypeUsers.size() < OldSize-- &&
1140 "AbstractTypeUser did not remove itself from the use list!");
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 FunctionType::refineAbstractType(const DerivedType *OldType,
1149 const Type *NewType) {
1150 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1151 pImpl->FunctionTypes.RefineAbstractType(this, OldType, NewType);
1154 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1155 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1156 pImpl->FunctionTypes.TypeBecameConcrete(this, AbsTy);
1160 // refineAbstractType - Called when a contained type is found to be more
1161 // concrete - this could potentially change us from an abstract type to a
1164 void ArrayType::refineAbstractType(const DerivedType *OldType,
1165 const Type *NewType) {
1166 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1167 pImpl->ArrayTypes.RefineAbstractType(this, OldType, NewType);
1170 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1171 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1172 pImpl->ArrayTypes.TypeBecameConcrete(this, AbsTy);
1175 // refineAbstractType - Called when a contained type is found to be more
1176 // concrete - this could potentially change us from an abstract type to a
1179 void VectorType::refineAbstractType(const DerivedType *OldType,
1180 const Type *NewType) {
1181 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1182 pImpl->VectorTypes.RefineAbstractType(this, OldType, NewType);
1185 void VectorType::typeBecameConcrete(const DerivedType *AbsTy) {
1186 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1187 pImpl->VectorTypes.TypeBecameConcrete(this, AbsTy);
1190 // refineAbstractType - Called when a contained type is found to be more
1191 // concrete - this could potentially change us from an abstract type to a
1194 void StructType::refineAbstractType(const DerivedType *OldType,
1195 const Type *NewType) {
1196 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1197 pImpl->StructTypes.RefineAbstractType(this, OldType, NewType);
1200 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1201 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1202 pImpl->StructTypes.TypeBecameConcrete(this, AbsTy);
1205 // refineAbstractType - Called when a contained type is found to be more
1206 // concrete - this could potentially change us from an abstract type to a
1209 void PointerType::refineAbstractType(const DerivedType *OldType,
1210 const Type *NewType) {
1211 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1212 pImpl->PointerTypes.RefineAbstractType(this, OldType, NewType);
1215 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1216 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1217 pImpl->PointerTypes.TypeBecameConcrete(this, AbsTy);
1220 bool SequentialType::indexValid(const Value *V) const {
1221 if (V->getType()->isIntegerTy())
1227 raw_ostream &operator<<(raw_ostream &OS, const Type &T) {