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/ADT/SCCIterator.h"
20 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
21 // created and later destroyed, all in an effort to make sure that there is only
22 // a single canonical version of a type.
24 // #define DEBUG_MERGE_TYPES 1
26 AbstractTypeUser::~AbstractTypeUser() {}
28 void AbstractTypeUser::setType(Value *V, const Type *NewTy) {
32 //===----------------------------------------------------------------------===//
33 // Type Class Implementation
34 //===----------------------------------------------------------------------===//
36 /// Because of the way Type subclasses are allocated, this function is necessary
37 /// to use the correct kind of "delete" operator to deallocate the Type object.
38 /// Some type objects (FunctionTy, StructTy) allocate additional space
39 /// after the space for their derived type to hold the contained types array of
40 /// PATypeHandles. Using this allocation scheme means all the PATypeHandles are
41 /// allocated with the type object, decreasing allocations and eliminating the
42 /// need for a std::vector to be used in the Type class itself.
43 /// @brief Type destruction function
44 void Type::destroy() const {
45 // Nothing calls getForwardedType from here on.
46 if (ForwardType && ForwardType->isAbstract()) {
47 ForwardType->dropRef();
51 // Structures and Functions allocate their contained types past the end of
52 // the type object itself. These need to be destroyed differently than the
54 if (this->isFunctionTy() || this->isStructTy()) {
55 // First, make sure we destruct any PATypeHandles allocated by these
56 // subclasses. They must be manually destructed.
57 for (unsigned i = 0; i < NumContainedTys; ++i)
58 ContainedTys[i].PATypeHandle::~PATypeHandle();
60 // Now call the destructor for the subclass directly because we're going
61 // to delete this as an array of char.
62 if (this->isFunctionTy())
63 static_cast<const FunctionType*>(this)->FunctionType::~FunctionType();
66 static_cast<const StructType*>(this)->StructType::~StructType();
69 // Finally, remove the memory as an array deallocation of the chars it was
71 operator delete(const_cast<Type *>(this));
76 if (const OpaqueType *opaque_this = dyn_cast<OpaqueType>(this)) {
77 LLVMContextImpl *pImpl = this->getContext().pImpl;
78 pImpl->OpaqueTypes.erase(opaque_this);
81 // For all the other type subclasses, there is either no contained types or
82 // just one (all Sequentials). For Sequentials, the PATypeHandle is not
83 // allocated past the type object, its included directly in the SequentialType
84 // class. This means we can safely just do "normal" delete of this object and
85 // all the destructors that need to run will be run.
89 const Type *Type::getPrimitiveType(LLVMContext &C, TypeID IDNumber) {
91 case VoidTyID : return getVoidTy(C);
92 case FloatTyID : return getFloatTy(C);
93 case DoubleTyID : return getDoubleTy(C);
94 case X86_FP80TyID : return getX86_FP80Ty(C);
95 case FP128TyID : return getFP128Ty(C);
96 case PPC_FP128TyID : return getPPC_FP128Ty(C);
97 case LabelTyID : return getLabelTy(C);
98 case MetadataTyID : return getMetadataTy(C);
99 case X86_MMXTyID : return getX86_MMXTy(C);
105 /// getScalarType - If this is a vector type, return the element type,
106 /// otherwise return this.
107 const Type *Type::getScalarType() const {
108 if (const VectorType *VTy = dyn_cast<VectorType>(this))
109 return VTy->getElementType();
113 /// isIntegerTy - Return true if this is an IntegerType of the specified width.
114 bool Type::isIntegerTy(unsigned Bitwidth) const {
115 return isIntegerTy() && cast<IntegerType>(this)->getBitWidth() == Bitwidth;
118 /// isIntOrIntVectorTy - Return true if this is an integer type or a vector of
121 bool Type::isIntOrIntVectorTy() const {
124 if (ID != Type::VectorTyID) return false;
126 return cast<VectorType>(this)->getElementType()->isIntegerTy();
129 /// isFPOrFPVectorTy - Return true if this is a FP type or a vector of FP types.
131 bool Type::isFPOrFPVectorTy() const {
132 if (ID == Type::FloatTyID || ID == Type::DoubleTyID ||
133 ID == Type::FP128TyID || ID == Type::X86_FP80TyID ||
134 ID == Type::PPC_FP128TyID)
136 if (ID != Type::VectorTyID) return false;
138 return cast<VectorType>(this)->getElementType()->isFloatingPointTy();
141 // canLosslesslyBitCastTo - Return true if this type can be converted to
142 // 'Ty' without any reinterpretation of bits. For example, i8* to i32*.
144 bool Type::canLosslesslyBitCastTo(const Type *Ty) const {
145 // Identity cast means no change so return true
149 // They are not convertible unless they are at least first class types
150 if (!this->isFirstClassType() || !Ty->isFirstClassType())
153 // Vector -> Vector conversions are always lossless if the two vector types
154 // have the same size, otherwise not. Also, 64-bit vector types can be
155 // converted to x86mmx.
156 if (const VectorType *thisPTy = dyn_cast<VectorType>(this)) {
157 if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
158 return thisPTy->getBitWidth() == thatPTy->getBitWidth();
159 if (Ty->getTypeID() == Type::X86_MMXTyID &&
160 thisPTy->getBitWidth() == 64)
164 if (this->getTypeID() == Type::X86_MMXTyID)
165 if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
166 if (thatPTy->getBitWidth() == 64)
169 // At this point we have only various mismatches of the first class types
170 // remaining and ptr->ptr. Just select the lossless conversions. Everything
171 // else is not lossless.
172 if (this->isPointerTy())
173 return Ty->isPointerTy();
174 return false; // Other types have no identity values
177 bool Type::isEmptyTy() const {
178 const ArrayType *ATy = dyn_cast<ArrayType>(this);
180 unsigned NumElements = ATy->getNumElements();
181 return NumElements == 0 || ATy->getElementType()->isEmptyTy();
184 const StructType *STy = dyn_cast<StructType>(this);
186 unsigned NumElements = STy->getNumElements();
187 for (unsigned i = 0; i < NumElements; ++i)
188 if (!STy->getElementType(i)->isEmptyTy())
196 unsigned Type::getPrimitiveSizeInBits() const {
197 switch (getTypeID()) {
198 case Type::FloatTyID: return 32;
199 case Type::DoubleTyID: return 64;
200 case Type::X86_FP80TyID: return 80;
201 case Type::FP128TyID: return 128;
202 case Type::PPC_FP128TyID: return 128;
203 case Type::X86_MMXTyID: return 64;
204 case Type::IntegerTyID: return cast<IntegerType>(this)->getBitWidth();
205 case Type::VectorTyID: return cast<VectorType>(this)->getBitWidth();
210 /// getScalarSizeInBits - If this is a vector type, return the
211 /// getPrimitiveSizeInBits value for the element type. Otherwise return the
212 /// getPrimitiveSizeInBits value for this type.
213 unsigned Type::getScalarSizeInBits() const {
214 return getScalarType()->getPrimitiveSizeInBits();
217 /// getFPMantissaWidth - Return the width of the mantissa of this type. This
218 /// is only valid on floating point types. If the FP type does not
219 /// have a stable mantissa (e.g. ppc long double), this method returns -1.
220 int Type::getFPMantissaWidth() const {
221 if (const VectorType *VTy = dyn_cast<VectorType>(this))
222 return VTy->getElementType()->getFPMantissaWidth();
223 assert(isFloatingPointTy() && "Not a floating point type!");
224 if (ID == FloatTyID) return 24;
225 if (ID == DoubleTyID) return 53;
226 if (ID == X86_FP80TyID) return 64;
227 if (ID == FP128TyID) return 113;
228 assert(ID == PPC_FP128TyID && "unknown fp type");
232 /// isSizedDerivedType - Derived types like structures and arrays are sized
233 /// iff all of the members of the type are sized as well. Since asking for
234 /// their size is relatively uncommon, move this operation out of line.
235 bool Type::isSizedDerivedType() const {
236 if (this->isIntegerTy())
239 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
240 return ATy->getElementType()->isSized();
242 if (const VectorType *VTy = dyn_cast<VectorType>(this))
243 return VTy->getElementType()->isSized();
245 if (!this->isStructTy())
248 // Okay, our struct is sized if all of the elements are...
249 for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
250 if (!(*I)->isSized())
256 /// getForwardedTypeInternal - This method is used to implement the union-find
257 /// algorithm for when a type is being forwarded to another type.
258 const Type *Type::getForwardedTypeInternal() const {
259 assert(ForwardType && "This type is not being forwarded to another type!");
261 // Check to see if the forwarded type has been forwarded on. If so, collapse
262 // the forwarding links.
263 const Type *RealForwardedType = ForwardType->getForwardedType();
264 if (!RealForwardedType)
265 return ForwardType; // No it's not forwarded again
267 // Yes, it is forwarded again. First thing, add the reference to the new
269 if (RealForwardedType->isAbstract())
270 RealForwardedType->addRef();
272 // Now drop the old reference. This could cause ForwardType to get deleted.
273 // ForwardType must be abstract because only abstract types can have their own
275 ForwardType->dropRef();
277 // Return the updated type.
278 ForwardType = RealForwardedType;
282 void Type::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
283 llvm_unreachable("Attempting to refine a derived type!");
285 void Type::typeBecameConcrete(const DerivedType *AbsTy) {
286 llvm_unreachable("DerivedType is already a concrete type!");
289 bool StructType::indexValid(const Value *V) const {
290 // Structure indexes require 32-bit integer constants.
291 if (V->getType()->isIntegerTy(32))
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];
315 //===----------------------------------------------------------------------===//
316 // Primitive 'Type' data
317 //===----------------------------------------------------------------------===//
319 const Type *Type::getVoidTy(LLVMContext &C) {
320 return &C.pImpl->VoidTy;
323 const Type *Type::getLabelTy(LLVMContext &C) {
324 return &C.pImpl->LabelTy;
327 const Type *Type::getFloatTy(LLVMContext &C) {
328 return &C.pImpl->FloatTy;
331 const Type *Type::getDoubleTy(LLVMContext &C) {
332 return &C.pImpl->DoubleTy;
335 const Type *Type::getMetadataTy(LLVMContext &C) {
336 return &C.pImpl->MetadataTy;
339 const Type *Type::getX86_FP80Ty(LLVMContext &C) {
340 return &C.pImpl->X86_FP80Ty;
343 const Type *Type::getFP128Ty(LLVMContext &C) {
344 return &C.pImpl->FP128Ty;
347 const Type *Type::getPPC_FP128Ty(LLVMContext &C) {
348 return &C.pImpl->PPC_FP128Ty;
351 const Type *Type::getX86_MMXTy(LLVMContext &C) {
352 return &C.pImpl->X86_MMXTy;
355 const IntegerType *Type::getIntNTy(LLVMContext &C, unsigned N) {
356 return IntegerType::get(C, N);
359 const IntegerType *Type::getInt1Ty(LLVMContext &C) {
360 return &C.pImpl->Int1Ty;
363 const IntegerType *Type::getInt8Ty(LLVMContext &C) {
364 return &C.pImpl->Int8Ty;
367 const IntegerType *Type::getInt16Ty(LLVMContext &C) {
368 return &C.pImpl->Int16Ty;
371 const IntegerType *Type::getInt32Ty(LLVMContext &C) {
372 return &C.pImpl->Int32Ty;
375 const IntegerType *Type::getInt64Ty(LLVMContext &C) {
376 return &C.pImpl->Int64Ty;
379 const PointerType *Type::getFloatPtrTy(LLVMContext &C, unsigned AS) {
380 return getFloatTy(C)->getPointerTo(AS);
383 const PointerType *Type::getDoublePtrTy(LLVMContext &C, unsigned AS) {
384 return getDoubleTy(C)->getPointerTo(AS);
387 const PointerType *Type::getX86_FP80PtrTy(LLVMContext &C, unsigned AS) {
388 return getX86_FP80Ty(C)->getPointerTo(AS);
391 const PointerType *Type::getFP128PtrTy(LLVMContext &C, unsigned AS) {
392 return getFP128Ty(C)->getPointerTo(AS);
395 const PointerType *Type::getPPC_FP128PtrTy(LLVMContext &C, unsigned AS) {
396 return getPPC_FP128Ty(C)->getPointerTo(AS);
399 const PointerType *Type::getX86_MMXPtrTy(LLVMContext &C, unsigned AS) {
400 return getX86_MMXTy(C)->getPointerTo(AS);
403 const PointerType *Type::getIntNPtrTy(LLVMContext &C, unsigned N, unsigned AS) {
404 return getIntNTy(C, N)->getPointerTo(AS);
407 const PointerType *Type::getInt1PtrTy(LLVMContext &C, unsigned AS) {
408 return getInt1Ty(C)->getPointerTo(AS);
411 const PointerType *Type::getInt8PtrTy(LLVMContext &C, unsigned AS) {
412 return getInt8Ty(C)->getPointerTo(AS);
415 const PointerType *Type::getInt16PtrTy(LLVMContext &C, unsigned AS) {
416 return getInt16Ty(C)->getPointerTo(AS);
419 const PointerType *Type::getInt32PtrTy(LLVMContext &C, unsigned AS) {
420 return getInt32Ty(C)->getPointerTo(AS);
423 const PointerType *Type::getInt64PtrTy(LLVMContext &C, unsigned AS) {
424 return getInt64Ty(C)->getPointerTo(AS);
427 //===----------------------------------------------------------------------===//
428 // Derived Type Constructors
429 //===----------------------------------------------------------------------===//
431 /// isValidReturnType - Return true if the specified type is valid as a return
433 bool FunctionType::isValidReturnType(const Type *RetTy) {
434 return !RetTy->isFunctionTy() && !RetTy->isLabelTy() &&
435 !RetTy->isMetadataTy();
438 /// isValidArgumentType - Return true if the specified type is valid as an
440 bool FunctionType::isValidArgumentType(const Type *ArgTy) {
441 return ArgTy->isFirstClassType() || ArgTy->isOpaqueTy();
444 FunctionType::FunctionType(const Type *Result,
445 ArrayRef<const Type*> Params,
447 : DerivedType(Result->getContext(), FunctionTyID) {
448 ContainedTys = reinterpret_cast<PATypeHandle*>(this+1);
449 NumContainedTys = Params.size() + 1; // + 1 for result type
450 assert(isValidReturnType(Result) && "invalid return type for function");
451 setSubclassData(IsVarArgs);
453 bool isAbstract = Result->isAbstract();
454 new (&ContainedTys[0]) PATypeHandle(Result, this);
456 for (unsigned i = 0; i != Params.size(); ++i) {
457 assert(isValidArgumentType(Params[i]) &&
458 "Not a valid type for function argument!");
459 new (&ContainedTys[i+1]) PATypeHandle(Params[i], this);
460 isAbstract |= Params[i]->isAbstract();
463 // Calculate whether or not this type is abstract
464 setAbstract(isAbstract);
467 StructType::StructType(LLVMContext &C,
468 ArrayRef<const Type*> Types, bool isPacked)
469 : CompositeType(C, StructTyID) {
470 ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
471 NumContainedTys = Types.size();
472 setSubclassData(isPacked);
473 bool isAbstract = false;
474 for (unsigned i = 0; i < Types.size(); ++i) {
475 assert(Types[i] && "<null> type for structure field!");
476 assert(isValidElementType(Types[i]) &&
477 "Invalid type for structure element!");
478 new (&ContainedTys[i]) PATypeHandle(Types[i], this);
479 isAbstract |= Types[i]->isAbstract();
482 // Calculate whether or not this type is abstract
483 setAbstract(isAbstract);
486 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
487 : SequentialType(ArrayTyID, ElType) {
490 // Calculate whether or not this type is abstract
491 setAbstract(ElType->isAbstract());
494 VectorType::VectorType(const Type *ElType, unsigned NumEl)
495 : SequentialType(VectorTyID, ElType) {
497 setAbstract(ElType->isAbstract());
498 assert(NumEl > 0 && "NumEl of a VectorType must be greater than 0");
499 assert(isValidElementType(ElType) &&
500 "Elements of a VectorType must be a primitive type");
505 PointerType::PointerType(const Type *E, unsigned AddrSpace)
506 : SequentialType(PointerTyID, E) {
507 setSubclassData(AddrSpace);
508 // Calculate whether or not this type is abstract
509 setAbstract(E->isAbstract());
512 OpaqueType::OpaqueType(LLVMContext &C) : DerivedType(C, OpaqueTyID) {
514 #ifdef DEBUG_MERGE_TYPES
515 DEBUG(dbgs() << "Derived new type: " << *this << "\n");
519 void PATypeHolder::destroy() {
523 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
524 // another (more concrete) type, we must eliminate all references to other
525 // types, to avoid some circular reference problems.
526 void DerivedType::dropAllTypeUses() {
527 if (NumContainedTys != 0) {
528 // The type must stay abstract. To do this, we insert a pointer to a type
529 // that will never get resolved, thus will always be abstract.
530 ContainedTys[0] = getContext().pImpl->AlwaysOpaqueTy;
532 // Change the rest of the types to be Int32Ty's. It doesn't matter what we
533 // pick so long as it doesn't point back to this type. We choose something
534 // concrete to avoid overhead for adding to AbstractTypeUser lists and
536 const Type *ConcreteTy = Type::getInt32Ty(getContext());
537 for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
538 ContainedTys[i] = ConcreteTy;
545 /// TypePromotionGraph and graph traits - this is designed to allow us to do
546 /// efficient SCC processing of type graphs. This is the exact same as
547 /// GraphTraits<Type*>, except that we pretend that concrete types have no
548 /// children to avoid processing them.
549 struct TypePromotionGraph {
551 TypePromotionGraph(Type *T) : Ty(T) {}
557 template <> struct GraphTraits<TypePromotionGraph> {
558 typedef Type NodeType;
559 typedef Type::subtype_iterator ChildIteratorType;
561 static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
562 static inline ChildIteratorType child_begin(NodeType *N) {
564 return N->subtype_begin();
565 // No need to process children of concrete types.
566 return N->subtype_end();
568 static inline ChildIteratorType child_end(NodeType *N) {
569 return N->subtype_end();
575 // PromoteAbstractToConcrete - This is a recursive function that walks a type
576 // graph calculating whether or not a type is abstract.
578 void Type::PromoteAbstractToConcrete() {
579 if (!isAbstract()) return;
581 scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
582 scc_iterator<TypePromotionGraph> SE = scc_end (TypePromotionGraph(this));
584 for (; SI != SE; ++SI) {
585 std::vector<Type*> &SCC = *SI;
587 // Concrete types are leaves in the tree. Since an SCC will either be all
588 // abstract or all concrete, we only need to check one type.
589 if (!SCC[0]->isAbstract()) continue;
591 if (SCC[0]->isOpaqueTy())
592 return; // Not going to be concrete, sorry.
594 // If all of the children of all of the types in this SCC are concrete,
595 // then this SCC is now concrete as well. If not, neither this SCC, nor
596 // any parent SCCs will be concrete, so we might as well just exit.
597 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
598 for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
599 E = SCC[i]->subtype_end(); CI != E; ++CI)
600 if ((*CI)->isAbstract())
601 // If the child type is in our SCC, it doesn't make the entire SCC
602 // abstract unless there is a non-SCC abstract type.
603 if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
604 return; // Not going to be concrete, sorry.
606 // Okay, we just discovered this whole SCC is now concrete, mark it as
608 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
609 assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
611 SCC[i]->setAbstract(false);
614 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
615 assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
616 // The type just became concrete, notify all users!
617 cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
623 //===----------------------------------------------------------------------===//
624 // Type Structural Equality Testing
625 //===----------------------------------------------------------------------===//
627 // TypesEqual - Two types are considered structurally equal if they have the
628 // same "shape": Every level and element of the types have identical primitive
629 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
630 // be pointer equals to be equivalent though. This uses an optimistic algorithm
631 // that assumes that two graphs are the same until proven otherwise.
633 static bool TypesEqual(const Type *Ty, const Type *Ty2,
634 std::map<const Type *, const Type *> &EqTypes) {
635 if (Ty == Ty2) return true;
636 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
637 if (Ty->isOpaqueTy())
638 return false; // Two unequal opaque types are never equal
640 std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
641 if (It != EqTypes.end())
642 return It->second == Ty2; // Looping back on a type, check for equality
644 // Otherwise, add the mapping to the table to make sure we don't get
645 // recursion on the types...
646 EqTypes.insert(It, std::make_pair(Ty, Ty2));
648 // Two really annoying special cases that breaks an otherwise nice simple
649 // algorithm is the fact that arraytypes have sizes that differentiates types,
650 // and that function types can be varargs or not. Consider this now.
652 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
653 const IntegerType *ITy2 = cast<IntegerType>(Ty2);
654 return ITy->getBitWidth() == ITy2->getBitWidth();
657 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
658 const PointerType *PTy2 = cast<PointerType>(Ty2);
659 return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
660 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
663 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
664 const StructType *STy2 = cast<StructType>(Ty2);
665 if (STy->getNumElements() != STy2->getNumElements()) return false;
666 if (STy->isPacked() != STy2->isPacked()) return false;
667 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
668 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
673 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);
679 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
680 const VectorType *PTy2 = cast<VectorType>(Ty2);
681 return PTy->getNumElements() == PTy2->getNumElements() &&
682 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
685 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
686 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
687 if (FTy->isVarArg() != FTy2->isVarArg() ||
688 FTy->getNumParams() != FTy2->getNumParams() ||
689 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
691 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
692 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
698 llvm_unreachable("Unknown derived type!");
702 namespace llvm { // in namespace llvm so findable by ADL
703 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
704 std::map<const Type *, const Type *> EqTypes;
705 return ::TypesEqual(Ty, Ty2, EqTypes);
709 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
710 // TargetTy in the type graph. We know that Ty is an abstract type, so if we
711 // ever reach a non-abstract type, we know that we don't need to search the
713 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
714 SmallPtrSet<const Type*, 128> &VisitedTypes) {
715 if (TargetTy == CurTy) return true;
716 if (!CurTy->isAbstract()) return false;
718 if (!VisitedTypes.insert(CurTy))
719 return false; // Already been here.
721 for (Type::subtype_iterator I = CurTy->subtype_begin(),
722 E = CurTy->subtype_end(); I != E; ++I)
723 if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
728 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
729 SmallPtrSet<const Type*, 128> &VisitedTypes) {
730 if (TargetTy == CurTy) return true;
732 if (!VisitedTypes.insert(CurTy))
733 return false; // Already been here.
735 for (Type::subtype_iterator I = CurTy->subtype_begin(),
736 E = CurTy->subtype_end(); I != E; ++I)
737 if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
742 /// TypeHasCycleThroughItself - Return true if the specified type has
743 /// a cycle back to itself.
745 namespace llvm { // in namespace llvm so it's findable by ADL
746 static bool TypeHasCycleThroughItself(const Type *Ty) {
747 SmallPtrSet<const Type*, 128> VisitedTypes;
749 if (Ty->isAbstract()) { // Optimized case for abstract types.
750 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
752 if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
755 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
757 if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
764 //===----------------------------------------------------------------------===//
765 // Function Type Factory and Value Class...
767 const IntegerType *IntegerType::get(LLVMContext &C, unsigned NumBits) {
768 assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
769 assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
771 // Check for the built-in integer types
773 case 1: return cast<IntegerType>(Type::getInt1Ty(C));
774 case 8: return cast<IntegerType>(Type::getInt8Ty(C));
775 case 16: return cast<IntegerType>(Type::getInt16Ty(C));
776 case 32: return cast<IntegerType>(Type::getInt32Ty(C));
777 case 64: return cast<IntegerType>(Type::getInt64Ty(C));
782 LLVMContextImpl *pImpl = C.pImpl;
784 IntegerValType IVT(NumBits);
785 IntegerType *ITy = 0;
787 // First, see if the type is already in the table, for which
788 // a reader lock suffices.
789 ITy = pImpl->IntegerTypes.get(IVT);
792 // Value not found. Derive a new type!
793 ITy = new IntegerType(C, NumBits);
794 pImpl->IntegerTypes.add(IVT, ITy);
796 #ifdef DEBUG_MERGE_TYPES
797 DEBUG(dbgs() << "Derived new type: " << *ITy << "\n");
802 bool IntegerType::isPowerOf2ByteWidth() const {
803 unsigned BitWidth = getBitWidth();
804 return (BitWidth > 7) && isPowerOf2_32(BitWidth);
807 APInt IntegerType::getMask() const {
808 return APInt::getAllOnesValue(getBitWidth());
811 FunctionValType FunctionValType::get(const FunctionType *FT) {
812 // Build up a FunctionValType
813 std::vector<const Type *> ParamTypes;
814 ParamTypes.reserve(FT->getNumParams());
815 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
816 ParamTypes.push_back(FT->getParamType(i));
817 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
820 FunctionType *FunctionType::get(const Type *Result, bool isVarArg) {
821 return get(Result, ArrayRef<const Type *>(), isVarArg);
824 // FunctionType::get - The factory function for the FunctionType class...
825 FunctionType *FunctionType::get(const Type *ReturnType,
826 ArrayRef<const Type*> Params,
828 FunctionValType VT(ReturnType, Params, isVarArg);
829 FunctionType *FT = 0;
831 LLVMContextImpl *pImpl = ReturnType->getContext().pImpl;
833 FT = pImpl->FunctionTypes.get(VT);
836 FT = (FunctionType*) operator new(sizeof(FunctionType) +
837 sizeof(PATypeHandle)*(Params.size()+1));
838 new (FT) FunctionType(ReturnType, Params, isVarArg);
839 pImpl->FunctionTypes.add(VT, FT);
842 #ifdef DEBUG_MERGE_TYPES
843 DEBUG(dbgs() << "Derived new type: " << FT << "\n");
848 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
849 assert(ElementType && "Can't get array of <null> types!");
850 assert(isValidElementType(ElementType) && "Invalid type for array element!");
852 ArrayValType AVT(ElementType, NumElements);
855 LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
857 AT = pImpl->ArrayTypes.get(AVT);
860 // Value not found. Derive a new type!
861 pImpl->ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
863 #ifdef DEBUG_MERGE_TYPES
864 DEBUG(dbgs() << "Derived new type: " << *AT << "\n");
869 bool ArrayType::isValidElementType(const Type *ElemTy) {
870 return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
871 !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
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 PT = pImpl->VectorTypes.get(PVT);
885 pImpl->VectorTypes.add(PVT, PT = new VectorType(ElementType, NumElements));
887 #ifdef DEBUG_MERGE_TYPES
888 DEBUG(dbgs() << "Derived new type: " << *PT << "\n");
893 bool VectorType::isValidElementType(const Type *ElemTy) {
894 return ElemTy->isIntegerTy() || ElemTy->isFloatingPointTy() ||
895 ElemTy->isOpaqueTy();
898 //===----------------------------------------------------------------------===//
899 // Struct Type Factory.
902 StructType *StructType::get(LLVMContext &Context, bool isPacked) {
903 return get(Context, llvm::ArrayRef<const Type*>(), isPacked);
907 StructType *StructType::get(LLVMContext &Context,
908 ArrayRef<const Type*> ETypes,
910 StructValType STV(ETypes, isPacked);
913 LLVMContextImpl *pImpl = Context.pImpl;
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(Context, ETypes, isPacked);
922 pImpl->StructTypes.add(STV, ST);
924 #ifdef DEBUG_MERGE_TYPES
925 DEBUG(dbgs() << "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 return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
943 !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
947 //===----------------------------------------------------------------------===//
948 // Pointer Type Factory...
951 PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) {
952 assert(ValueType && "Can't get a pointer to <null> type!");
953 assert(ValueType->getTypeID() != VoidTyID &&
954 "Pointer to void is not valid, use i8* instead!");
955 assert(isValidElementType(ValueType) && "Invalid type for pointer element!");
956 PointerValType PVT(ValueType, AddressSpace);
960 LLVMContextImpl *pImpl = ValueType->getContext().pImpl;
962 PT = pImpl->PointerTypes.get(PVT);
965 // Value not found. Derive a new type!
966 pImpl->PointerTypes.add(PVT, PT = new PointerType(ValueType, AddressSpace));
968 #ifdef DEBUG_MERGE_TYPES
969 DEBUG(dbgs() << "Derived new type: " << *PT << "\n");
974 const PointerType *Type::getPointerTo(unsigned addrs) const {
975 return PointerType::get(this, addrs);
978 bool PointerType::isValidElementType(const Type *ElemTy) {
979 return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
980 !ElemTy->isMetadataTy();
984 //===----------------------------------------------------------------------===//
985 // Opaque Type Factory...
988 OpaqueType *OpaqueType::get(LLVMContext &C) {
989 OpaqueType *OT = new OpaqueType(C); // All opaque types are distinct.
990 LLVMContextImpl *pImpl = C.pImpl;
991 pImpl->OpaqueTypes.insert(OT);
997 //===----------------------------------------------------------------------===//
998 // Derived Type Refinement Functions
999 //===----------------------------------------------------------------------===//
1001 // addAbstractTypeUser - Notify an abstract type that there is a new user of
1002 // it. This function is called primarily by the PATypeHandle class.
1003 void Type::addAbstractTypeUser(AbstractTypeUser *U) const {
1004 assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
1005 AbstractTypeUsers.push_back(U);
1009 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1010 // no longer has a handle to the type. This function is called primarily by
1011 // the PATypeHandle class. When there are no users of the abstract type, it
1012 // is annihilated, because there is no way to get a reference to it ever again.
1014 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
1016 // Search from back to front because we will notify users from back to
1017 // front. Also, it is likely that there will be a stack like behavior to
1018 // users that register and unregister users.
1021 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1022 assert(i != 0 && "AbstractTypeUser not in user list!");
1024 --i; // Convert to be in range 0 <= i < size()
1025 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1027 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1029 #ifdef DEBUG_MERGE_TYPES
1030 DEBUG(dbgs() << " remAbstractTypeUser[" << (void*)this << ", "
1031 << *this << "][" << i << "] User = " << U << "\n");
1034 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1035 #ifdef DEBUG_MERGE_TYPES
1036 DEBUG(dbgs() << "DELETEing unused abstract type: <" << *this
1037 << ">[" << (void*)this << "]" << "\n");
1044 // refineAbstractTypeTo - This function is used when it is discovered
1045 // that the 'this' abstract type is actually equivalent to the NewType
1046 // specified. This causes all users of 'this' to switch to reference the more
1047 // concrete type NewType and for 'this' to be deleted. Only used for internal
1050 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1051 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1052 assert(this != NewType && "Can't refine to myself!");
1053 assert(ForwardType == 0 && "This type has already been refined!");
1055 #ifdef DEBUG_MERGE_TYPES
1056 DEBUG(dbgs() << "REFINING abstract type [" << (void*)this << " "
1057 << *this << "] to [" << (void*)NewType << " "
1058 << *NewType << "]!\n");
1061 // Make sure to put the type to be refined to into a holder so that if IT gets
1062 // refined, that we will not continue using a dead reference...
1064 PATypeHolder NewTy(NewType);
1065 // Any PATypeHolders referring to this type will now automatically forward to
1066 // the type we are resolved to.
1067 ForwardType = NewType;
1068 if (ForwardType->isAbstract())
1069 ForwardType->addRef();
1071 // Add a self use of the current type so that we don't delete ourself until
1072 // after the function exits.
1074 PATypeHolder CurrentTy(this);
1076 // To make the situation simpler, we ask the subclass to remove this type from
1077 // the type map, and to replace any type uses with uses of non-abstract types.
1078 // This dramatically limits the amount of recursive type trouble we can find
1082 // Iterate over all of the uses of this type, invoking callback. Each user
1083 // should remove itself from our use list automatically. We have to check to
1084 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1085 // will not cause users to drop off of the use list. If we resolve to ourself
1088 while (!AbstractTypeUsers.empty() && NewTy != this) {
1089 AbstractTypeUser *User = AbstractTypeUsers.back();
1091 unsigned OldSize = AbstractTypeUsers.size(); (void)OldSize;
1092 #ifdef DEBUG_MERGE_TYPES
1093 DEBUG(dbgs() << " REFINING user " << OldSize-1 << "[" << (void*)User
1094 << "] of abstract type [" << (void*)this << " "
1095 << *this << "] to [" << (void*)NewTy.get() << " "
1096 << *NewTy << "]!\n");
1098 User->refineAbstractType(this, NewTy);
1100 assert(AbstractTypeUsers.size() != OldSize &&
1101 "AbsTyUser did not remove self from user list!");
1104 // If we were successful removing all users from the type, 'this' will be
1105 // deleted when the last PATypeHolder is destroyed or updated from this type.
1106 // This may occur on exit of this function, as the CurrentTy object is
1110 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1111 // the current type has transitioned from being abstract to being concrete.
1113 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1114 #ifdef DEBUG_MERGE_TYPES
1115 DEBUG(dbgs() << "typeIsREFINED type: " << (void*)this << " " << *this <<"\n");
1118 unsigned OldSize = AbstractTypeUsers.size(); (void)OldSize;
1119 while (!AbstractTypeUsers.empty()) {
1120 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1121 ATU->typeBecameConcrete(this);
1123 assert(AbstractTypeUsers.size() < OldSize-- &&
1124 "AbstractTypeUser did not remove itself from the use list!");
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 (V->getType()->isIntegerTy())
1211 raw_ostream &operator<<(raw_ostream &OS, const Type &T) {