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 const Type *CompositeType::getTypeAtIndex(const Value *V) const {
290 if (const StructType *STy = dyn_cast<StructType>(this)) {
291 unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
292 assert(indexValid(Idx) && "Invalid structure index!");
293 return STy->getElementType(Idx);
296 return cast<SequentialType>(this)->getElementType();
298 const Type *CompositeType::getTypeAtIndex(unsigned Idx) const {
299 if (const StructType *STy = dyn_cast<StructType>(this)) {
300 assert(indexValid(Idx) && "Invalid structure index!");
301 return STy->getElementType(Idx);
304 return cast<SequentialType>(this)->getElementType();
306 bool CompositeType::indexValid(const Value *V) const {
307 if (const StructType *STy = dyn_cast<StructType>(this)) {
308 // Structure indexes require 32-bit integer constants.
309 if (V->getType()->isIntegerTy(32))
310 if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
311 return CU->getZExtValue() < STy->getNumElements();
315 // Sequential types can be indexed by any integer.
316 return V->getType()->isIntegerTy();
319 bool CompositeType::indexValid(unsigned Idx) const {
320 if (const StructType *STy = dyn_cast<StructType>(this))
321 return Idx < STy->getNumElements();
322 // Sequential types can be indexed by any integer.
327 //===----------------------------------------------------------------------===//
328 // Primitive 'Type' data
329 //===----------------------------------------------------------------------===//
331 const Type *Type::getVoidTy(LLVMContext &C) {
332 return &C.pImpl->VoidTy;
335 const Type *Type::getLabelTy(LLVMContext &C) {
336 return &C.pImpl->LabelTy;
339 const Type *Type::getFloatTy(LLVMContext &C) {
340 return &C.pImpl->FloatTy;
343 const Type *Type::getDoubleTy(LLVMContext &C) {
344 return &C.pImpl->DoubleTy;
347 const Type *Type::getMetadataTy(LLVMContext &C) {
348 return &C.pImpl->MetadataTy;
351 const Type *Type::getX86_FP80Ty(LLVMContext &C) {
352 return &C.pImpl->X86_FP80Ty;
355 const Type *Type::getFP128Ty(LLVMContext &C) {
356 return &C.pImpl->FP128Ty;
359 const Type *Type::getPPC_FP128Ty(LLVMContext &C) {
360 return &C.pImpl->PPC_FP128Ty;
363 const Type *Type::getX86_MMXTy(LLVMContext &C) {
364 return &C.pImpl->X86_MMXTy;
367 const IntegerType *Type::getIntNTy(LLVMContext &C, unsigned N) {
368 return IntegerType::get(C, N);
371 const IntegerType *Type::getInt1Ty(LLVMContext &C) {
372 return &C.pImpl->Int1Ty;
375 const IntegerType *Type::getInt8Ty(LLVMContext &C) {
376 return &C.pImpl->Int8Ty;
379 const IntegerType *Type::getInt16Ty(LLVMContext &C) {
380 return &C.pImpl->Int16Ty;
383 const IntegerType *Type::getInt32Ty(LLVMContext &C) {
384 return &C.pImpl->Int32Ty;
387 const IntegerType *Type::getInt64Ty(LLVMContext &C) {
388 return &C.pImpl->Int64Ty;
391 const PointerType *Type::getFloatPtrTy(LLVMContext &C, unsigned AS) {
392 return getFloatTy(C)->getPointerTo(AS);
395 const PointerType *Type::getDoublePtrTy(LLVMContext &C, unsigned AS) {
396 return getDoubleTy(C)->getPointerTo(AS);
399 const PointerType *Type::getX86_FP80PtrTy(LLVMContext &C, unsigned AS) {
400 return getX86_FP80Ty(C)->getPointerTo(AS);
403 const PointerType *Type::getFP128PtrTy(LLVMContext &C, unsigned AS) {
404 return getFP128Ty(C)->getPointerTo(AS);
407 const PointerType *Type::getPPC_FP128PtrTy(LLVMContext &C, unsigned AS) {
408 return getPPC_FP128Ty(C)->getPointerTo(AS);
411 const PointerType *Type::getX86_MMXPtrTy(LLVMContext &C, unsigned AS) {
412 return getX86_MMXTy(C)->getPointerTo(AS);
415 const PointerType *Type::getIntNPtrTy(LLVMContext &C, unsigned N, unsigned AS) {
416 return getIntNTy(C, N)->getPointerTo(AS);
419 const PointerType *Type::getInt1PtrTy(LLVMContext &C, unsigned AS) {
420 return getInt1Ty(C)->getPointerTo(AS);
423 const PointerType *Type::getInt8PtrTy(LLVMContext &C, unsigned AS) {
424 return getInt8Ty(C)->getPointerTo(AS);
427 const PointerType *Type::getInt16PtrTy(LLVMContext &C, unsigned AS) {
428 return getInt16Ty(C)->getPointerTo(AS);
431 const PointerType *Type::getInt32PtrTy(LLVMContext &C, unsigned AS) {
432 return getInt32Ty(C)->getPointerTo(AS);
435 const PointerType *Type::getInt64PtrTy(LLVMContext &C, unsigned AS) {
436 return getInt64Ty(C)->getPointerTo(AS);
439 //===----------------------------------------------------------------------===//
440 // Derived Type Constructors
441 //===----------------------------------------------------------------------===//
443 /// isValidReturnType - Return true if the specified type is valid as a return
445 bool FunctionType::isValidReturnType(const Type *RetTy) {
446 return !RetTy->isFunctionTy() && !RetTy->isLabelTy() &&
447 !RetTy->isMetadataTy();
450 /// isValidArgumentType - Return true if the specified type is valid as an
452 bool FunctionType::isValidArgumentType(const Type *ArgTy) {
453 return ArgTy->isFirstClassType() || ArgTy->isOpaqueTy();
456 FunctionType::FunctionType(const Type *Result,
457 ArrayRef<const Type*> Params,
459 : DerivedType(Result->getContext(), FunctionTyID) {
460 ContainedTys = reinterpret_cast<PATypeHandle*>(this+1);
461 NumContainedTys = Params.size() + 1; // + 1 for result type
462 assert(isValidReturnType(Result) && "invalid return type for function");
463 setSubclassData(IsVarArgs);
465 bool isAbstract = Result->isAbstract();
466 new (&ContainedTys[0]) PATypeHandle(Result, this);
468 for (unsigned i = 0; i != Params.size(); ++i) {
469 assert(isValidArgumentType(Params[i]) &&
470 "Not a valid type for function argument!");
471 new (&ContainedTys[i+1]) PATypeHandle(Params[i], this);
472 isAbstract |= Params[i]->isAbstract();
475 // Calculate whether or not this type is abstract
476 setAbstract(isAbstract);
479 StructType::StructType(LLVMContext &C,
480 ArrayRef<const Type*> Types, bool isPacked)
481 : CompositeType(C, StructTyID) {
482 ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
483 NumContainedTys = Types.size();
484 setSubclassData(isPacked);
485 bool isAbstract = false;
486 for (unsigned i = 0; i < Types.size(); ++i) {
487 assert(Types[i] && "<null> type for structure field!");
488 assert(isValidElementType(Types[i]) &&
489 "Invalid type for structure element!");
490 new (&ContainedTys[i]) PATypeHandle(Types[i], this);
491 isAbstract |= Types[i]->isAbstract();
494 // Calculate whether or not this type is abstract
495 setAbstract(isAbstract);
498 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
499 : SequentialType(ArrayTyID, ElType) {
502 // Calculate whether or not this type is abstract
503 setAbstract(ElType->isAbstract());
506 VectorType::VectorType(const Type *ElType, unsigned NumEl)
507 : SequentialType(VectorTyID, ElType) {
509 setAbstract(ElType->isAbstract());
510 assert(NumEl > 0 && "NumEl of a VectorType must be greater than 0");
511 assert(isValidElementType(ElType) &&
512 "Elements of a VectorType must be a primitive type");
517 PointerType::PointerType(const Type *E, unsigned AddrSpace)
518 : SequentialType(PointerTyID, E) {
519 setSubclassData(AddrSpace);
520 // Calculate whether or not this type is abstract
521 setAbstract(E->isAbstract());
524 OpaqueType::OpaqueType(LLVMContext &C) : DerivedType(C, OpaqueTyID) {
526 #ifdef DEBUG_MERGE_TYPES
527 DEBUG(dbgs() << "Derived new type: " << *this << "\n");
531 void PATypeHolder::destroy() {
535 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
536 // another (more concrete) type, we must eliminate all references to other
537 // types, to avoid some circular reference problems.
538 void DerivedType::dropAllTypeUses() {
539 if (NumContainedTys != 0) {
540 // The type must stay abstract. To do this, we insert a pointer to a type
541 // that will never get resolved, thus will always be abstract.
542 ContainedTys[0] = getContext().pImpl->AlwaysOpaqueTy;
544 // Change the rest of the types to be Int32Ty's. It doesn't matter what we
545 // pick so long as it doesn't point back to this type. We choose something
546 // concrete to avoid overhead for adding to AbstractTypeUser lists and
548 const Type *ConcreteTy = Type::getInt32Ty(getContext());
549 for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
550 ContainedTys[i] = ConcreteTy;
557 /// TypePromotionGraph and graph traits - this is designed to allow us to do
558 /// efficient SCC processing of type graphs. This is the exact same as
559 /// GraphTraits<Type*>, except that we pretend that concrete types have no
560 /// children to avoid processing them.
561 struct TypePromotionGraph {
563 TypePromotionGraph(Type *T) : Ty(T) {}
569 template <> struct GraphTraits<TypePromotionGraph> {
570 typedef Type NodeType;
571 typedef Type::subtype_iterator ChildIteratorType;
573 static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
574 static inline ChildIteratorType child_begin(NodeType *N) {
576 return N->subtype_begin();
577 // No need to process children of concrete types.
578 return N->subtype_end();
580 static inline ChildIteratorType child_end(NodeType *N) {
581 return N->subtype_end();
587 // PromoteAbstractToConcrete - This is a recursive function that walks a type
588 // graph calculating whether or not a type is abstract.
590 void Type::PromoteAbstractToConcrete() {
591 if (!isAbstract()) return;
593 scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
594 scc_iterator<TypePromotionGraph> SE = scc_end (TypePromotionGraph(this));
596 for (; SI != SE; ++SI) {
597 std::vector<Type*> &SCC = *SI;
599 // Concrete types are leaves in the tree. Since an SCC will either be all
600 // abstract or all concrete, we only need to check one type.
601 if (!SCC[0]->isAbstract()) continue;
603 if (SCC[0]->isOpaqueTy())
604 return; // Not going to be concrete, sorry.
606 // If all of the children of all of the types in this SCC are concrete,
607 // then this SCC is now concrete as well. If not, neither this SCC, nor
608 // any parent SCCs will be concrete, so we might as well just exit.
609 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
610 for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
611 E = SCC[i]->subtype_end(); CI != E; ++CI)
612 if ((*CI)->isAbstract())
613 // If the child type is in our SCC, it doesn't make the entire SCC
614 // abstract unless there is a non-SCC abstract type.
615 if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
616 return; // Not going to be concrete, sorry.
618 // Okay, we just discovered this whole SCC is now concrete, mark it as
620 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
621 assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
623 SCC[i]->setAbstract(false);
626 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
627 assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
628 // The type just became concrete, notify all users!
629 cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
635 //===----------------------------------------------------------------------===//
636 // Type Structural Equality Testing
637 //===----------------------------------------------------------------------===//
639 // TypesEqual - Two types are considered structurally equal if they have the
640 // same "shape": Every level and element of the types have identical primitive
641 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
642 // be pointer equals to be equivalent though. This uses an optimistic algorithm
643 // that assumes that two graphs are the same until proven otherwise.
645 static bool TypesEqual(const Type *Ty, const Type *Ty2,
646 std::map<const Type *, const Type *> &EqTypes) {
647 if (Ty == Ty2) return true;
648 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
649 if (Ty->isOpaqueTy())
650 return false; // Two unequal opaque types are never equal
652 std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
653 if (It != EqTypes.end())
654 return It->second == Ty2; // Looping back on a type, check for equality
656 // Otherwise, add the mapping to the table to make sure we don't get
657 // recursion on the types...
658 EqTypes.insert(It, std::make_pair(Ty, Ty2));
660 // Two really annoying special cases that breaks an otherwise nice simple
661 // algorithm is the fact that arraytypes have sizes that differentiates types,
662 // and that function types can be varargs or not. Consider this now.
664 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
665 const IntegerType *ITy2 = cast<IntegerType>(Ty2);
666 return ITy->getBitWidth() == ITy2->getBitWidth();
669 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
670 const PointerType *PTy2 = cast<PointerType>(Ty2);
671 return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
672 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
675 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
676 const StructType *STy2 = cast<StructType>(Ty2);
677 if (STy->getNumElements() != STy2->getNumElements()) return false;
678 if (STy->isPacked() != STy2->isPacked()) return false;
679 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
680 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
685 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
686 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
687 return ATy->getNumElements() == ATy2->getNumElements() &&
688 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
691 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
692 const VectorType *PTy2 = cast<VectorType>(Ty2);
693 return PTy->getNumElements() == PTy2->getNumElements() &&
694 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
697 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
698 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
699 if (FTy->isVarArg() != FTy2->isVarArg() ||
700 FTy->getNumParams() != FTy2->getNumParams() ||
701 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
703 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
704 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
710 llvm_unreachable("Unknown derived type!");
714 namespace llvm { // in namespace llvm so findable by ADL
715 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
716 std::map<const Type *, const Type *> EqTypes;
717 return ::TypesEqual(Ty, Ty2, EqTypes);
721 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
722 // TargetTy in the type graph. We know that Ty is an abstract type, so if we
723 // ever reach a non-abstract type, we know that we don't need to search the
725 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
726 SmallPtrSet<const Type*, 128> &VisitedTypes) {
727 if (TargetTy == CurTy) return true;
728 if (!CurTy->isAbstract()) return false;
730 if (!VisitedTypes.insert(CurTy))
731 return false; // Already been here.
733 for (Type::subtype_iterator I = CurTy->subtype_begin(),
734 E = CurTy->subtype_end(); I != E; ++I)
735 if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
740 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
741 SmallPtrSet<const Type*, 128> &VisitedTypes) {
742 if (TargetTy == CurTy) return true;
744 if (!VisitedTypes.insert(CurTy))
745 return false; // Already been here.
747 for (Type::subtype_iterator I = CurTy->subtype_begin(),
748 E = CurTy->subtype_end(); I != E; ++I)
749 if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
754 /// TypeHasCycleThroughItself - Return true if the specified type has
755 /// a cycle back to itself.
757 namespace llvm { // in namespace llvm so it's findable by ADL
758 static bool TypeHasCycleThroughItself(const Type *Ty) {
759 SmallPtrSet<const Type*, 128> VisitedTypes;
761 if (Ty->isAbstract()) { // Optimized case for abstract types.
762 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
764 if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
767 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
769 if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
776 //===----------------------------------------------------------------------===//
777 // Function Type Factory and Value Class...
779 const IntegerType *IntegerType::get(LLVMContext &C, unsigned NumBits) {
780 assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
781 assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
783 // Check for the built-in integer types
785 case 1: return cast<IntegerType>(Type::getInt1Ty(C));
786 case 8: return cast<IntegerType>(Type::getInt8Ty(C));
787 case 16: return cast<IntegerType>(Type::getInt16Ty(C));
788 case 32: return cast<IntegerType>(Type::getInt32Ty(C));
789 case 64: return cast<IntegerType>(Type::getInt64Ty(C));
794 LLVMContextImpl *pImpl = C.pImpl;
796 IntegerValType IVT(NumBits);
797 IntegerType *ITy = 0;
799 // First, see if the type is already in the table, for which
800 // a reader lock suffices.
801 ITy = pImpl->IntegerTypes.get(IVT);
804 // Value not found. Derive a new type!
805 ITy = new IntegerType(C, NumBits);
806 pImpl->IntegerTypes.add(IVT, ITy);
808 #ifdef DEBUG_MERGE_TYPES
809 DEBUG(dbgs() << "Derived new type: " << *ITy << "\n");
814 bool IntegerType::isPowerOf2ByteWidth() const {
815 unsigned BitWidth = getBitWidth();
816 return (BitWidth > 7) && isPowerOf2_32(BitWidth);
819 APInt IntegerType::getMask() const {
820 return APInt::getAllOnesValue(getBitWidth());
823 FunctionValType FunctionValType::get(const FunctionType *FT) {
824 // Build up a FunctionValType
825 std::vector<const Type *> ParamTypes;
826 ParamTypes.reserve(FT->getNumParams());
827 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
828 ParamTypes.push_back(FT->getParamType(i));
829 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
832 FunctionType *FunctionType::get(const Type *Result, bool isVarArg) {
833 return get(Result, ArrayRef<const Type *>(), isVarArg);
836 // FunctionType::get - The factory function for the FunctionType class...
837 FunctionType *FunctionType::get(const Type *ReturnType,
838 ArrayRef<const Type*> Params,
840 FunctionValType VT(ReturnType, Params, isVarArg);
841 FunctionType *FT = 0;
843 LLVMContextImpl *pImpl = ReturnType->getContext().pImpl;
845 FT = pImpl->FunctionTypes.get(VT);
848 FT = (FunctionType*) operator new(sizeof(FunctionType) +
849 sizeof(PATypeHandle)*(Params.size()+1));
850 new (FT) FunctionType(ReturnType, Params, isVarArg);
851 pImpl->FunctionTypes.add(VT, FT);
854 #ifdef DEBUG_MERGE_TYPES
855 DEBUG(dbgs() << "Derived new type: " << FT << "\n");
860 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
861 assert(ElementType && "Can't get array of <null> types!");
862 assert(isValidElementType(ElementType) && "Invalid type for array element!");
864 ArrayValType AVT(ElementType, NumElements);
867 LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
869 AT = pImpl->ArrayTypes.get(AVT);
872 // Value not found. Derive a new type!
873 pImpl->ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
875 #ifdef DEBUG_MERGE_TYPES
876 DEBUG(dbgs() << "Derived new type: " << *AT << "\n");
881 bool ArrayType::isValidElementType(const Type *ElemTy) {
882 return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
883 !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
886 VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) {
887 assert(ElementType && "Can't get vector of <null> types!");
889 VectorValType PVT(ElementType, NumElements);
892 LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
894 PT = pImpl->VectorTypes.get(PVT);
897 pImpl->VectorTypes.add(PVT, PT = new VectorType(ElementType, NumElements));
899 #ifdef DEBUG_MERGE_TYPES
900 DEBUG(dbgs() << "Derived new type: " << *PT << "\n");
905 bool VectorType::isValidElementType(const Type *ElemTy) {
906 return ElemTy->isIntegerTy() || ElemTy->isFloatingPointTy() ||
907 ElemTy->isOpaqueTy();
910 //===----------------------------------------------------------------------===//
911 // Struct Type Factory.
914 StructType *StructType::get(LLVMContext &Context, bool isPacked) {
915 return get(Context, llvm::ArrayRef<const Type*>(), isPacked);
919 StructType *StructType::get(LLVMContext &Context,
920 ArrayRef<const Type*> ETypes,
922 StructValType STV(ETypes, isPacked);
925 LLVMContextImpl *pImpl = Context.pImpl;
927 ST = pImpl->StructTypes.get(STV);
930 // Value not found. Derive a new type!
931 ST = (StructType*) operator new(sizeof(StructType) +
932 sizeof(PATypeHandle) * ETypes.size());
933 new (ST) StructType(Context, ETypes, isPacked);
934 pImpl->StructTypes.add(STV, ST);
936 #ifdef DEBUG_MERGE_TYPES
937 DEBUG(dbgs() << "Derived new type: " << *ST << "\n");
942 StructType *StructType::get(const Type *type, ...) {
943 assert(type != 0 && "Cannot create a struct type with no elements with this");
944 LLVMContext &Ctx = type->getContext();
946 SmallVector<const llvm::Type*, 8> StructFields;
949 StructFields.push_back(type);
950 type = va_arg(ap, llvm::Type*);
952 return llvm::StructType::get(Ctx, StructFields);
955 bool StructType::isValidElementType(const Type *ElemTy) {
956 return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
957 !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
961 //===----------------------------------------------------------------------===//
962 // Pointer Type Factory...
965 PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) {
966 assert(ValueType && "Can't get a pointer to <null> type!");
967 assert(ValueType->getTypeID() != VoidTyID &&
968 "Pointer to void is not valid, use i8* instead!");
969 assert(isValidElementType(ValueType) && "Invalid type for pointer element!");
970 PointerValType PVT(ValueType, AddressSpace);
974 LLVMContextImpl *pImpl = ValueType->getContext().pImpl;
976 PT = pImpl->PointerTypes.get(PVT);
979 // Value not found. Derive a new type!
980 pImpl->PointerTypes.add(PVT, PT = new PointerType(ValueType, AddressSpace));
982 #ifdef DEBUG_MERGE_TYPES
983 DEBUG(dbgs() << "Derived new type: " << *PT << "\n");
988 const PointerType *Type::getPointerTo(unsigned addrs) const {
989 return PointerType::get(this, addrs);
992 bool PointerType::isValidElementType(const Type *ElemTy) {
993 return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
994 !ElemTy->isMetadataTy();
998 //===----------------------------------------------------------------------===//
999 // Opaque Type Factory...
1002 OpaqueType *OpaqueType::get(LLVMContext &C) {
1003 OpaqueType *OT = new OpaqueType(C); // All opaque types are distinct.
1004 LLVMContextImpl *pImpl = C.pImpl;
1005 pImpl->OpaqueTypes.insert(OT);
1011 //===----------------------------------------------------------------------===//
1012 // Derived Type Refinement Functions
1013 //===----------------------------------------------------------------------===//
1015 // addAbstractTypeUser - Notify an abstract type that there is a new user of
1016 // it. This function is called primarily by the PATypeHandle class.
1017 void Type::addAbstractTypeUser(AbstractTypeUser *U) const {
1018 assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
1019 AbstractTypeUsers.push_back(U);
1023 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1024 // no longer has a handle to the type. This function is called primarily by
1025 // the PATypeHandle class. When there are no users of the abstract type, it
1026 // is annihilated, because there is no way to get a reference to it ever again.
1028 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
1030 // Search from back to front because we will notify users from back to
1031 // front. Also, it is likely that there will be a stack like behavior to
1032 // users that register and unregister users.
1035 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1036 assert(i != 0 && "AbstractTypeUser not in user list!");
1038 --i; // Convert to be in range 0 <= i < size()
1039 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1041 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1043 #ifdef DEBUG_MERGE_TYPES
1044 DEBUG(dbgs() << " remAbstractTypeUser[" << (void*)this << ", "
1045 << *this << "][" << i << "] User = " << U << "\n");
1048 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1049 #ifdef DEBUG_MERGE_TYPES
1050 DEBUG(dbgs() << "DELETEing unused abstract type: <" << *this
1051 << ">[" << (void*)this << "]" << "\n");
1058 // refineAbstractTypeTo - This function is used when it is discovered
1059 // that the 'this' abstract type is actually equivalent to the NewType
1060 // specified. This causes all users of 'this' to switch to reference the more
1061 // concrete type NewType and for 'this' to be deleted. Only used for internal
1064 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1065 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1066 assert(this != NewType && "Can't refine to myself!");
1067 assert(ForwardType == 0 && "This type has already been refined!");
1069 #ifdef DEBUG_MERGE_TYPES
1070 DEBUG(dbgs() << "REFINING abstract type [" << (void*)this << " "
1071 << *this << "] to [" << (void*)NewType << " "
1072 << *NewType << "]!\n");
1075 // Make sure to put the type to be refined to into a holder so that if IT gets
1076 // refined, that we will not continue using a dead reference...
1078 PATypeHolder NewTy(NewType);
1079 // Any PATypeHolders referring to this type will now automatically forward to
1080 // the type we are resolved to.
1081 ForwardType = NewType;
1082 if (ForwardType->isAbstract())
1083 ForwardType->addRef();
1085 // Add a self use of the current type so that we don't delete ourself until
1086 // after the function exits.
1088 PATypeHolder CurrentTy(this);
1090 // To make the situation simpler, we ask the subclass to remove this type from
1091 // the type map, and to replace any type uses with uses of non-abstract types.
1092 // This dramatically limits the amount of recursive type trouble we can find
1096 // Iterate over all of the uses of this type, invoking callback. Each user
1097 // should remove itself from our use list automatically. We have to check to
1098 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1099 // will not cause users to drop off of the use list. If we resolve to ourself
1102 while (!AbstractTypeUsers.empty() && NewTy != this) {
1103 AbstractTypeUser *User = AbstractTypeUsers.back();
1105 unsigned OldSize = AbstractTypeUsers.size(); (void)OldSize;
1106 #ifdef DEBUG_MERGE_TYPES
1107 DEBUG(dbgs() << " REFINING user " << OldSize-1 << "[" << (void*)User
1108 << "] of abstract type [" << (void*)this << " "
1109 << *this << "] to [" << (void*)NewTy.get() << " "
1110 << *NewTy << "]!\n");
1112 User->refineAbstractType(this, NewTy);
1114 assert(AbstractTypeUsers.size() != OldSize &&
1115 "AbsTyUser did not remove self from user list!");
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 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1125 // the current type has transitioned from being abstract to being concrete.
1127 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1128 #ifdef DEBUG_MERGE_TYPES
1129 DEBUG(dbgs() << "typeIsREFINED type: " << (void*)this << " " << *this <<"\n");
1132 unsigned OldSize = AbstractTypeUsers.size(); (void)OldSize;
1133 while (!AbstractTypeUsers.empty()) {
1134 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1135 ATU->typeBecameConcrete(this);
1137 assert(AbstractTypeUsers.size() < OldSize-- &&
1138 "AbstractTypeUser did not remove itself from the use list!");
1142 // refineAbstractType - Called when a contained type is found to be more
1143 // concrete - this could potentially change us from an abstract type to a
1146 void FunctionType::refineAbstractType(const DerivedType *OldType,
1147 const Type *NewType) {
1148 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1149 pImpl->FunctionTypes.RefineAbstractType(this, OldType, NewType);
1152 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1153 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1154 pImpl->FunctionTypes.TypeBecameConcrete(this, AbsTy);
1158 // refineAbstractType - Called when a contained type is found to be more
1159 // concrete - this could potentially change us from an abstract type to a
1162 void ArrayType::refineAbstractType(const DerivedType *OldType,
1163 const Type *NewType) {
1164 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1165 pImpl->ArrayTypes.RefineAbstractType(this, OldType, NewType);
1168 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1169 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1170 pImpl->ArrayTypes.TypeBecameConcrete(this, AbsTy);
1173 // refineAbstractType - Called when a contained type is found to be more
1174 // concrete - this could potentially change us from an abstract type to a
1177 void VectorType::refineAbstractType(const DerivedType *OldType,
1178 const Type *NewType) {
1179 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1180 pImpl->VectorTypes.RefineAbstractType(this, OldType, NewType);
1183 void VectorType::typeBecameConcrete(const DerivedType *AbsTy) {
1184 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1185 pImpl->VectorTypes.TypeBecameConcrete(this, AbsTy);
1188 // refineAbstractType - Called when a contained type is found to be more
1189 // concrete - this could potentially change us from an abstract type to a
1192 void StructType::refineAbstractType(const DerivedType *OldType,
1193 const Type *NewType) {
1194 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1195 pImpl->StructTypes.RefineAbstractType(this, OldType, NewType);
1198 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1199 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1200 pImpl->StructTypes.TypeBecameConcrete(this, AbsTy);
1203 // refineAbstractType - Called when a contained type is found to be more
1204 // concrete - this could potentially change us from an abstract type to a
1207 void PointerType::refineAbstractType(const DerivedType *OldType,
1208 const Type *NewType) {
1209 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1210 pImpl->PointerTypes.RefineAbstractType(this, OldType, NewType);
1213 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1214 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1215 pImpl->PointerTypes.TypeBecameConcrete(this, AbsTy);
1219 raw_ostream &operator<<(raw_ostream &OS, const Type &T) {