1 //===-- Type.cpp - Implement the Type class -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Type class for the VMCore library.
12 //===----------------------------------------------------------------------===//
14 #include "LLVMContextImpl.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Metadata.h"
20 #include "llvm/ADT/DepthFirstIterator.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/SCCIterator.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/System/Threading.h"
35 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
36 // created and later destroyed, all in an effort to make sure that there is only
37 // a single canonical version of a type.
39 // #define DEBUG_MERGE_TYPES 1
41 AbstractTypeUser::~AbstractTypeUser() {}
43 void AbstractTypeUser::setType(Value *V, const Type *NewTy) {
47 //===----------------------------------------------------------------------===//
48 // Type Class Implementation
49 //===----------------------------------------------------------------------===//
51 /// Because of the way Type subclasses are allocated, this function is necessary
52 /// to use the correct kind of "delete" operator to deallocate the Type object.
53 /// Some type objects (FunctionTy, StructTy, UnionTy) allocate additional space
54 /// after the space for their derived type to hold the contained types array of
55 /// PATypeHandles. Using this allocation scheme means all the PATypeHandles are
56 /// allocated with the type object, decreasing allocations and eliminating the
57 /// need for a std::vector to be used in the Type class itself.
58 /// @brief Type destruction function
59 void Type::destroy() const {
60 // Nothing calls getForwardedType from here on.
61 if (ForwardType && ForwardType->isAbstract()) {
62 ForwardType->dropRef();
66 // Structures and Functions allocate their contained types past the end of
67 // the type object itself. These need to be destroyed differently than the
69 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();
80 else if (this->isStructTy())
81 static_cast<const StructType*>(this)->StructType::~StructType();
83 static_cast<const UnionType*>(this)->UnionType::~UnionType();
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);
118 const Type *Type::getVAArgsPromotedType(LLVMContext &C) const {
119 if (ID == IntegerTyID && getSubclassData() < 32)
120 return Type::getInt32Ty(C);
121 else if (ID == FloatTyID)
122 return Type::getDoubleTy(C);
127 /// getScalarType - If this is a vector type, return the element type,
128 /// otherwise return this.
129 const Type *Type::getScalarType() const {
130 if (const VectorType *VTy = dyn_cast<VectorType>(this))
131 return VTy->getElementType();
135 /// isIntegerTy - Return true if this is an IntegerType of the specified width.
136 bool Type::isIntegerTy(unsigned Bitwidth) const {
137 return isIntegerTy() && cast<IntegerType>(this)->getBitWidth() == Bitwidth;
140 /// isIntOrIntVectorTy - Return true if this is an integer type or a vector of
143 bool Type::isIntOrIntVectorTy() const {
146 if (ID != Type::VectorTyID) return false;
148 return cast<VectorType>(this)->getElementType()->isIntegerTy();
151 /// isFPOrFPVectorTy - Return true if this is a FP type or a vector of FP types.
153 bool Type::isFPOrFPVectorTy() const {
154 if (ID == Type::FloatTyID || ID == Type::DoubleTyID ||
155 ID == Type::FP128TyID || ID == Type::X86_FP80TyID ||
156 ID == Type::PPC_FP128TyID)
158 if (ID != Type::VectorTyID) return false;
160 return cast<VectorType>(this)->getElementType()->isFloatingPointTy();
163 // canLosslesslyBitCastTo - Return true if this type can be converted to
164 // 'Ty' without any reinterpretation of bits. For example, i8* to i32*.
166 bool Type::canLosslesslyBitCastTo(const Type *Ty) const {
167 // Identity cast means no change so return true
171 // They are not convertible unless they are at least first class types
172 if (!this->isFirstClassType() || !Ty->isFirstClassType())
175 // Vector -> Vector conversions are always lossless if the two vector types
176 // have the same size, otherwise not.
177 if (const VectorType *thisPTy = dyn_cast<VectorType>(this))
178 if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
179 return thisPTy->getBitWidth() == thatPTy->getBitWidth();
181 // At this point we have only various mismatches of the first class types
182 // remaining and ptr->ptr. Just select the lossless conversions. Everything
183 // else is not lossless.
184 if (this->isPointerTy())
185 return Ty->isPointerTy();
186 return false; // Other types have no identity values
189 unsigned Type::getPrimitiveSizeInBits() const {
190 switch (getTypeID()) {
191 case Type::FloatTyID: return 32;
192 case Type::DoubleTyID: return 64;
193 case Type::X86_FP80TyID: return 80;
194 case Type::FP128TyID: return 128;
195 case Type::PPC_FP128TyID: return 128;
196 case Type::IntegerTyID: return cast<IntegerType>(this)->getBitWidth();
197 case Type::VectorTyID: return cast<VectorType>(this)->getBitWidth();
202 /// getScalarSizeInBits - If this is a vector type, return the
203 /// getPrimitiveSizeInBits value for the element type. Otherwise return the
204 /// getPrimitiveSizeInBits value for this type.
205 unsigned Type::getScalarSizeInBits() const {
206 return getScalarType()->getPrimitiveSizeInBits();
209 /// getFPMantissaWidth - Return the width of the mantissa of this type. This
210 /// is only valid on floating point types. If the FP type does not
211 /// have a stable mantissa (e.g. ppc long double), this method returns -1.
212 int Type::getFPMantissaWidth() const {
213 if (const VectorType *VTy = dyn_cast<VectorType>(this))
214 return VTy->getElementType()->getFPMantissaWidth();
215 assert(isFloatingPointTy() && "Not a floating point type!");
216 if (ID == FloatTyID) return 24;
217 if (ID == DoubleTyID) return 53;
218 if (ID == X86_FP80TyID) return 64;
219 if (ID == FP128TyID) return 113;
220 assert(ID == PPC_FP128TyID && "unknown fp type");
224 /// isSizedDerivedType - Derived types like structures and arrays are sized
225 /// iff all of the members of the type are sized as well. Since asking for
226 /// their size is relatively uncommon, move this operation out of line.
227 bool Type::isSizedDerivedType() const {
228 if (this->isIntegerTy())
231 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
232 return ATy->getElementType()->isSized();
234 if (const VectorType *PTy = dyn_cast<VectorType>(this))
235 return PTy->getElementType()->isSized();
237 if (!this->isStructTy() && !this->isUnionTy())
240 // Okay, our struct is sized if all of the elements are...
241 for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
242 if (!(*I)->isSized())
248 /// getForwardedTypeInternal - This method is used to implement the union-find
249 /// algorithm for when a type is being forwarded to another type.
250 const Type *Type::getForwardedTypeInternal() const {
251 assert(ForwardType && "This type is not being forwarded to another type!");
253 // Check to see if the forwarded type has been forwarded on. If so, collapse
254 // the forwarding links.
255 const Type *RealForwardedType = ForwardType->getForwardedType();
256 if (!RealForwardedType)
257 return ForwardType; // No it's not forwarded again
259 // Yes, it is forwarded again. First thing, add the reference to the new
261 if (RealForwardedType->isAbstract())
262 RealForwardedType->addRef();
264 // Now drop the old reference. This could cause ForwardType to get deleted.
265 // ForwardType must be abstract because only abstract types can have their own
267 ForwardType->dropRef();
269 // Return the updated type.
270 ForwardType = RealForwardedType;
274 void Type::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
275 llvm_unreachable("Attempting to refine a derived type!");
277 void Type::typeBecameConcrete(const DerivedType *AbsTy) {
278 llvm_unreachable("DerivedType is already a concrete type!");
282 std::string Type::getDescription() const {
283 LLVMContextImpl *pImpl = getContext().pImpl;
286 pImpl->AbstractTypeDescriptions :
287 pImpl->ConcreteTypeDescriptions;
290 raw_string_ostream DescOS(DescStr);
291 Map.print(this, DescOS);
296 bool StructType::indexValid(const Value *V) const {
297 // Structure indexes require 32-bit integer constants.
298 if (V->getType()->isIntegerTy(32))
299 if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
300 return indexValid(CU->getZExtValue());
304 bool StructType::indexValid(unsigned V) const {
305 return V < NumContainedTys;
308 // getTypeAtIndex - Given an index value into the type, return the type of the
309 // element. For a structure type, this must be a constant value...
311 const Type *StructType::getTypeAtIndex(const Value *V) const {
312 unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
313 return getTypeAtIndex(Idx);
316 const Type *StructType::getTypeAtIndex(unsigned Idx) const {
317 assert(indexValid(Idx) && "Invalid structure index!");
318 return ContainedTys[Idx];
322 bool UnionType::indexValid(const Value *V) const {
323 // Union indexes require 32-bit integer constants.
324 if (V->getType()->isIntegerTy(32))
325 if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
326 return indexValid(CU->getZExtValue());
330 bool UnionType::indexValid(unsigned V) const {
331 return V < NumContainedTys;
334 // getTypeAtIndex - Given an index value into the type, return the type of the
335 // element. For a structure type, this must be a constant value...
337 const Type *UnionType::getTypeAtIndex(const Value *V) const {
338 unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
339 return getTypeAtIndex(Idx);
342 const Type *UnionType::getTypeAtIndex(unsigned Idx) const {
343 assert(indexValid(Idx) && "Invalid structure index!");
344 return ContainedTys[Idx];
347 //===----------------------------------------------------------------------===//
348 // Primitive 'Type' data
349 //===----------------------------------------------------------------------===//
351 const Type *Type::getVoidTy(LLVMContext &C) {
352 return &C.pImpl->VoidTy;
355 const Type *Type::getLabelTy(LLVMContext &C) {
356 return &C.pImpl->LabelTy;
359 const Type *Type::getFloatTy(LLVMContext &C) {
360 return &C.pImpl->FloatTy;
363 const Type *Type::getDoubleTy(LLVMContext &C) {
364 return &C.pImpl->DoubleTy;
367 const Type *Type::getMetadataTy(LLVMContext &C) {
368 return &C.pImpl->MetadataTy;
371 const Type *Type::getX86_FP80Ty(LLVMContext &C) {
372 return &C.pImpl->X86_FP80Ty;
375 const Type *Type::getFP128Ty(LLVMContext &C) {
376 return &C.pImpl->FP128Ty;
379 const Type *Type::getPPC_FP128Ty(LLVMContext &C) {
380 return &C.pImpl->PPC_FP128Ty;
383 const IntegerType *Type::getIntNTy(LLVMContext &C, unsigned N) {
384 return IntegerType::get(C, N);
387 const IntegerType *Type::getInt1Ty(LLVMContext &C) {
388 return &C.pImpl->Int1Ty;
391 const IntegerType *Type::getInt8Ty(LLVMContext &C) {
392 return &C.pImpl->Int8Ty;
395 const IntegerType *Type::getInt16Ty(LLVMContext &C) {
396 return &C.pImpl->Int16Ty;
399 const IntegerType *Type::getInt32Ty(LLVMContext &C) {
400 return &C.pImpl->Int32Ty;
403 const IntegerType *Type::getInt64Ty(LLVMContext &C) {
404 return &C.pImpl->Int64Ty;
407 const PointerType *Type::getFloatPtrTy(LLVMContext &C, unsigned AS) {
408 return getFloatTy(C)->getPointerTo(AS);
411 const PointerType *Type::getDoublePtrTy(LLVMContext &C, unsigned AS) {
412 return getDoubleTy(C)->getPointerTo(AS);
415 const PointerType *Type::getX86_FP80PtrTy(LLVMContext &C, unsigned AS) {
416 return getX86_FP80Ty(C)->getPointerTo(AS);
419 const PointerType *Type::getFP128PtrTy(LLVMContext &C, unsigned AS) {
420 return getFP128Ty(C)->getPointerTo(AS);
423 const PointerType *Type::getPPC_FP128PtrTy(LLVMContext &C, unsigned AS) {
424 return getPPC_FP128Ty(C)->getPointerTo(AS);
427 const PointerType *Type::getIntNPtrTy(LLVMContext &C, unsigned N, unsigned AS) {
428 return getIntNTy(C, N)->getPointerTo(AS);
431 const PointerType *Type::getInt1PtrTy(LLVMContext &C, unsigned AS) {
432 return getInt1Ty(C)->getPointerTo(AS);
435 const PointerType *Type::getInt8PtrTy(LLVMContext &C, unsigned AS) {
436 return getInt8Ty(C)->getPointerTo(AS);
439 const PointerType *Type::getInt16PtrTy(LLVMContext &C, unsigned AS) {
440 return getInt16Ty(C)->getPointerTo(AS);
443 const PointerType *Type::getInt32PtrTy(LLVMContext &C, unsigned AS) {
444 return getInt32Ty(C)->getPointerTo(AS);
447 const PointerType *Type::getInt64PtrTy(LLVMContext &C, unsigned AS) {
448 return getInt64Ty(C)->getPointerTo(AS);
451 //===----------------------------------------------------------------------===//
452 // Derived Type Constructors
453 //===----------------------------------------------------------------------===//
455 /// isValidReturnType - Return true if the specified type is valid as a return
457 bool FunctionType::isValidReturnType(const Type *RetTy) {
458 return RetTy->getTypeID() != LabelTyID &&
459 RetTy->getTypeID() != MetadataTyID;
462 /// isValidArgumentType - Return true if the specified type is valid as an
464 bool FunctionType::isValidArgumentType(const Type *ArgTy) {
465 return ArgTy->isFirstClassType() || ArgTy->isOpaqueTy();
468 FunctionType::FunctionType(const Type *Result,
469 const std::vector<const Type*> &Params,
471 : DerivedType(Result->getContext(), FunctionTyID), isVarArgs(IsVarArgs) {
472 ContainedTys = reinterpret_cast<PATypeHandle*>(this+1);
473 NumContainedTys = Params.size() + 1; // + 1 for result type
474 assert(isValidReturnType(Result) && "invalid return type for function");
477 bool isAbstract = Result->isAbstract();
478 new (&ContainedTys[0]) PATypeHandle(Result, this);
480 for (unsigned i = 0; i != Params.size(); ++i) {
481 assert(isValidArgumentType(Params[i]) &&
482 "Not a valid type for function argument!");
483 new (&ContainedTys[i+1]) PATypeHandle(Params[i], this);
484 isAbstract |= Params[i]->isAbstract();
487 // Calculate whether or not this type is abstract
488 setAbstract(isAbstract);
491 StructType::StructType(LLVMContext &C,
492 const std::vector<const Type*> &Types, bool isPacked)
493 : CompositeType(C, StructTyID) {
494 ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
495 NumContainedTys = Types.size();
496 setSubclassData(isPacked);
497 bool isAbstract = false;
498 for (unsigned i = 0; i < Types.size(); ++i) {
499 assert(Types[i] && "<null> type for structure field!");
500 assert(isValidElementType(Types[i]) &&
501 "Invalid type for structure element!");
502 new (&ContainedTys[i]) PATypeHandle(Types[i], this);
503 isAbstract |= Types[i]->isAbstract();
506 // Calculate whether or not this type is abstract
507 setAbstract(isAbstract);
510 UnionType::UnionType(LLVMContext &C,const Type* const* Types, unsigned NumTypes)
511 : CompositeType(C, UnionTyID) {
512 ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
513 NumContainedTys = NumTypes;
514 bool isAbstract = false;
515 for (unsigned i = 0; i < NumTypes; ++i) {
516 assert(Types[i] && "<null> type for union field!");
517 assert(isValidElementType(Types[i]) &&
518 "Invalid type for union element!");
519 new (&ContainedTys[i]) PATypeHandle(Types[i], this);
520 isAbstract |= Types[i]->isAbstract();
523 // Calculate whether or not this type is abstract
524 setAbstract(isAbstract);
527 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
528 : SequentialType(ArrayTyID, ElType) {
531 // Calculate whether or not this type is abstract
532 setAbstract(ElType->isAbstract());
535 VectorType::VectorType(const Type *ElType, unsigned NumEl)
536 : SequentialType(VectorTyID, ElType) {
538 setAbstract(ElType->isAbstract());
539 assert(NumEl > 0 && "NumEl of a VectorType must be greater than 0");
540 assert(isValidElementType(ElType) &&
541 "Elements of a VectorType must be a primitive type");
546 PointerType::PointerType(const Type *E, unsigned AddrSpace)
547 : SequentialType(PointerTyID, E) {
548 AddressSpace = AddrSpace;
549 // Calculate whether or not this type is abstract
550 setAbstract(E->isAbstract());
553 OpaqueType::OpaqueType(LLVMContext &C) : DerivedType(C, OpaqueTyID) {
555 #ifdef DEBUG_MERGE_TYPES
556 DEBUG(dbgs() << "Derived new type: " << *this << "\n");
560 void PATypeHolder::destroy() {
564 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
565 // another (more concrete) type, we must eliminate all references to other
566 // types, to avoid some circular reference problems.
567 void DerivedType::dropAllTypeUses() {
568 if (NumContainedTys != 0) {
569 // The type must stay abstract. To do this, we insert a pointer to a type
570 // that will never get resolved, thus will always be abstract.
571 ContainedTys[0] = getContext().pImpl->AlwaysOpaqueTy;
573 // Change the rest of the types to be Int32Ty's. It doesn't matter what we
574 // pick so long as it doesn't point back to this type. We choose something
575 // concrete to avoid overhead for adding to AbstractTypeUser lists and
577 const Type *ConcreteTy = Type::getInt32Ty(getContext());
578 for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
579 ContainedTys[i] = ConcreteTy;
586 /// TypePromotionGraph and graph traits - this is designed to allow us to do
587 /// efficient SCC processing of type graphs. This is the exact same as
588 /// GraphTraits<Type*>, except that we pretend that concrete types have no
589 /// children to avoid processing them.
590 struct TypePromotionGraph {
592 TypePromotionGraph(Type *T) : Ty(T) {}
598 template <> struct GraphTraits<TypePromotionGraph> {
599 typedef Type NodeType;
600 typedef Type::subtype_iterator ChildIteratorType;
602 static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
603 static inline ChildIteratorType child_begin(NodeType *N) {
605 return N->subtype_begin();
606 else // No need to process children of concrete types.
607 return N->subtype_end();
609 static inline ChildIteratorType child_end(NodeType *N) {
610 return N->subtype_end();
616 // PromoteAbstractToConcrete - This is a recursive function that walks a type
617 // graph calculating whether or not a type is abstract.
619 void Type::PromoteAbstractToConcrete() {
620 if (!isAbstract()) return;
622 scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
623 scc_iterator<TypePromotionGraph> SE = scc_end (TypePromotionGraph(this));
625 for (; SI != SE; ++SI) {
626 std::vector<Type*> &SCC = *SI;
628 // Concrete types are leaves in the tree. Since an SCC will either be all
629 // abstract or all concrete, we only need to check one type.
630 if (SCC[0]->isAbstract()) {
631 if (SCC[0]->isOpaqueTy())
632 return; // Not going to be concrete, sorry.
634 // If all of the children of all of the types in this SCC are concrete,
635 // then this SCC is now concrete as well. If not, neither this SCC, nor
636 // any parent SCCs will be concrete, so we might as well just exit.
637 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
638 for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
639 E = SCC[i]->subtype_end(); CI != E; ++CI)
640 if ((*CI)->isAbstract())
641 // If the child type is in our SCC, it doesn't make the entire SCC
642 // abstract unless there is a non-SCC abstract type.
643 if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
644 return; // Not going to be concrete, sorry.
646 // Okay, we just discovered this whole SCC is now concrete, mark it as
648 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
649 assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
651 SCC[i]->setAbstract(false);
654 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
655 assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
656 // The type just became concrete, notify all users!
657 cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
664 //===----------------------------------------------------------------------===//
665 // Type Structural Equality Testing
666 //===----------------------------------------------------------------------===//
668 // TypesEqual - Two types are considered structurally equal if they have the
669 // same "shape": Every level and element of the types have identical primitive
670 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
671 // be pointer equals to be equivalent though. This uses an optimistic algorithm
672 // that assumes that two graphs are the same until proven otherwise.
674 static bool TypesEqual(const Type *Ty, const Type *Ty2,
675 std::map<const Type *, const Type *> &EqTypes) {
676 if (Ty == Ty2) return true;
677 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
678 if (Ty->isOpaqueTy())
679 return false; // Two unequal opaque types are never equal
681 std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
682 if (It != EqTypes.end())
683 return It->second == Ty2; // Looping back on a type, check for equality
685 // Otherwise, add the mapping to the table to make sure we don't get
686 // recursion on the types...
687 EqTypes.insert(It, std::make_pair(Ty, Ty2));
689 // Two really annoying special cases that breaks an otherwise nice simple
690 // algorithm is the fact that arraytypes have sizes that differentiates types,
691 // and that function types can be varargs or not. Consider this now.
693 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
694 const IntegerType *ITy2 = cast<IntegerType>(Ty2);
695 return ITy->getBitWidth() == ITy2->getBitWidth();
696 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
697 const PointerType *PTy2 = cast<PointerType>(Ty2);
698 return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
699 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
700 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
701 const StructType *STy2 = cast<StructType>(Ty2);
702 if (STy->getNumElements() != STy2->getNumElements()) return false;
703 if (STy->isPacked() != STy2->isPacked()) return false;
704 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
705 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
708 } else if (const UnionType *UTy = dyn_cast<UnionType>(Ty)) {
709 const UnionType *UTy2 = cast<UnionType>(Ty2);
710 if (UTy->getNumElements() != UTy2->getNumElements()) return false;
711 for (unsigned i = 0, e = UTy2->getNumElements(); i != e; ++i)
712 if (!TypesEqual(UTy->getElementType(i), UTy2->getElementType(i), EqTypes))
715 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
716 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
717 return ATy->getNumElements() == ATy2->getNumElements() &&
718 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
719 } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
720 const VectorType *PTy2 = cast<VectorType>(Ty2);
721 return PTy->getNumElements() == PTy2->getNumElements() &&
722 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
723 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
724 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
725 if (FTy->isVarArg() != FTy2->isVarArg() ||
726 FTy->getNumParams() != FTy2->getNumParams() ||
727 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
729 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
730 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
735 llvm_unreachable("Unknown derived type!");
740 namespace llvm { // in namespace llvm so findable by ADL
741 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
742 std::map<const Type *, const Type *> EqTypes;
743 return ::TypesEqual(Ty, Ty2, EqTypes);
747 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
748 // TargetTy in the type graph. We know that Ty is an abstract type, so if we
749 // ever reach a non-abstract type, we know that we don't need to search the
751 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
752 SmallPtrSet<const Type*, 128> &VisitedTypes) {
753 if (TargetTy == CurTy) return true;
754 if (!CurTy->isAbstract()) return false;
756 if (!VisitedTypes.insert(CurTy))
757 return false; // Already been here.
759 for (Type::subtype_iterator I = CurTy->subtype_begin(),
760 E = CurTy->subtype_end(); I != E; ++I)
761 if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
766 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
767 SmallPtrSet<const Type*, 128> &VisitedTypes) {
768 if (TargetTy == CurTy) return true;
770 if (!VisitedTypes.insert(CurTy))
771 return false; // Already been here.
773 for (Type::subtype_iterator I = CurTy->subtype_begin(),
774 E = CurTy->subtype_end(); I != E; ++I)
775 if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
780 /// TypeHasCycleThroughItself - Return true if the specified type has
781 /// a cycle back to itself.
783 namespace llvm { // in namespace llvm so it's findable by ADL
784 static bool TypeHasCycleThroughItself(const Type *Ty) {
785 SmallPtrSet<const Type*, 128> VisitedTypes;
787 if (Ty->isAbstract()) { // Optimized case for abstract types.
788 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
790 if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
793 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
795 if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
802 //===----------------------------------------------------------------------===//
803 // Function Type Factory and Value Class...
805 const IntegerType *IntegerType::get(LLVMContext &C, unsigned NumBits) {
806 assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
807 assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
809 // Check for the built-in integer types
811 case 1: return cast<IntegerType>(Type::getInt1Ty(C));
812 case 8: return cast<IntegerType>(Type::getInt8Ty(C));
813 case 16: return cast<IntegerType>(Type::getInt16Ty(C));
814 case 32: return cast<IntegerType>(Type::getInt32Ty(C));
815 case 64: return cast<IntegerType>(Type::getInt64Ty(C));
820 LLVMContextImpl *pImpl = C.pImpl;
822 IntegerValType IVT(NumBits);
823 IntegerType *ITy = 0;
825 // First, see if the type is already in the table, for which
826 // a reader lock suffices.
827 ITy = pImpl->IntegerTypes.get(IVT);
830 // Value not found. Derive a new type!
831 ITy = new IntegerType(C, NumBits);
832 pImpl->IntegerTypes.add(IVT, ITy);
834 #ifdef DEBUG_MERGE_TYPES
835 DEBUG(dbgs() << "Derived new type: " << *ITy << "\n");
840 bool IntegerType::isPowerOf2ByteWidth() const {
841 unsigned BitWidth = getBitWidth();
842 return (BitWidth > 7) && isPowerOf2_32(BitWidth);
845 APInt IntegerType::getMask() const {
846 return APInt::getAllOnesValue(getBitWidth());
849 FunctionValType FunctionValType::get(const FunctionType *FT) {
850 // Build up a FunctionValType
851 std::vector<const Type *> ParamTypes;
852 ParamTypes.reserve(FT->getNumParams());
853 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
854 ParamTypes.push_back(FT->getParamType(i));
855 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
859 // FunctionType::get - The factory function for the FunctionType class...
860 FunctionType *FunctionType::get(const Type *ReturnType,
861 const std::vector<const Type*> &Params,
863 FunctionValType VT(ReturnType, Params, isVarArg);
864 FunctionType *FT = 0;
866 LLVMContextImpl *pImpl = ReturnType->getContext().pImpl;
868 FT = pImpl->FunctionTypes.get(VT);
871 FT = (FunctionType*) operator new(sizeof(FunctionType) +
872 sizeof(PATypeHandle)*(Params.size()+1));
873 new (FT) FunctionType(ReturnType, Params, isVarArg);
874 pImpl->FunctionTypes.add(VT, FT);
877 #ifdef DEBUG_MERGE_TYPES
878 DEBUG(dbgs() << "Derived new type: " << FT << "\n");
883 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
884 assert(ElementType && "Can't get array of <null> types!");
885 assert(isValidElementType(ElementType) && "Invalid type for array element!");
887 ArrayValType AVT(ElementType, NumElements);
890 LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
892 AT = pImpl->ArrayTypes.get(AVT);
895 // Value not found. Derive a new type!
896 pImpl->ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
898 #ifdef DEBUG_MERGE_TYPES
899 DEBUG(dbgs() << "Derived new type: " << *AT << "\n");
904 bool ArrayType::isValidElementType(const Type *ElemTy) {
905 return ElemTy->getTypeID() != VoidTyID && ElemTy->getTypeID() != LabelTyID &&
906 ElemTy->getTypeID() != MetadataTyID && !ElemTy->isFunctionTy();
909 VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) {
910 assert(ElementType && "Can't get vector of <null> types!");
912 VectorValType PVT(ElementType, NumElements);
915 LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
917 PT = pImpl->VectorTypes.get(PVT);
920 pImpl->VectorTypes.add(PVT, PT = new VectorType(ElementType, NumElements));
922 #ifdef DEBUG_MERGE_TYPES
923 DEBUG(dbgs() << "Derived new type: " << *PT << "\n");
928 bool VectorType::isValidElementType(const Type *ElemTy) {
929 return ElemTy->isIntegerTy() || ElemTy->isFloatingPointTy() ||
930 ElemTy->isOpaqueTy();
933 //===----------------------------------------------------------------------===//
934 // Struct Type Factory...
937 StructType *StructType::get(LLVMContext &Context,
938 const std::vector<const Type*> &ETypes,
940 StructValType STV(ETypes, isPacked);
943 LLVMContextImpl *pImpl = Context.pImpl;
945 ST = pImpl->StructTypes.get(STV);
948 // Value not found. Derive a new type!
949 ST = (StructType*) operator new(sizeof(StructType) +
950 sizeof(PATypeHandle) * ETypes.size());
951 new (ST) StructType(Context, ETypes, isPacked);
952 pImpl->StructTypes.add(STV, ST);
954 #ifdef DEBUG_MERGE_TYPES
955 DEBUG(dbgs() << "Derived new type: " << *ST << "\n");
960 StructType *StructType::get(LLVMContext &Context, const Type *type, ...) {
962 std::vector<const llvm::Type*> StructFields;
965 StructFields.push_back(type);
966 type = va_arg(ap, llvm::Type*);
968 return llvm::StructType::get(Context, StructFields);
971 bool StructType::isValidElementType(const Type *ElemTy) {
972 return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
973 !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
977 //===----------------------------------------------------------------------===//
978 // Union Type Factory...
981 UnionType *UnionType::get(const Type* const* Types, unsigned NumTypes) {
982 assert(NumTypes > 0 && "union must have at least one member type!");
983 UnionValType UTV(Types, NumTypes);
986 LLVMContextImpl *pImpl = Types[0]->getContext().pImpl;
988 UT = pImpl->UnionTypes.get(UTV);
991 // Value not found. Derive a new type!
992 UT = (UnionType*) operator new(sizeof(UnionType) +
993 sizeof(PATypeHandle) * NumTypes);
994 new (UT) UnionType(Types[0]->getContext(), Types, NumTypes);
995 pImpl->UnionTypes.add(UTV, UT);
997 #ifdef DEBUG_MERGE_TYPES
998 DEBUG(dbgs() << "Derived new type: " << *UT << "\n");
1003 UnionType *UnionType::get(const Type *type, ...) {
1005 SmallVector<const llvm::Type*, 8> UnionFields;
1008 UnionFields.push_back(type);
1009 type = va_arg(ap, llvm::Type*);
1011 unsigned NumTypes = UnionFields.size();
1012 assert(NumTypes > 0 && "union must have at least one member type!");
1013 return llvm::UnionType::get(&UnionFields[0], NumTypes);
1016 bool UnionType::isValidElementType(const Type *ElemTy) {
1017 return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
1018 !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
1021 int UnionType::getElementTypeIndex(const Type *ElemTy) const {
1023 for (UnionType::element_iterator I = element_begin(), E = element_end();
1024 I != E; ++I, ++index) {
1025 if (ElemTy == *I) return index;
1031 //===----------------------------------------------------------------------===//
1032 // Pointer Type Factory...
1035 PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) {
1036 assert(ValueType && "Can't get a pointer to <null> type!");
1037 assert(ValueType->getTypeID() != VoidTyID &&
1038 "Pointer to void is not valid, use i8* instead!");
1039 assert(isValidElementType(ValueType) && "Invalid type for pointer element!");
1040 PointerValType PVT(ValueType, AddressSpace);
1042 PointerType *PT = 0;
1044 LLVMContextImpl *pImpl = ValueType->getContext().pImpl;
1046 PT = pImpl->PointerTypes.get(PVT);
1049 // Value not found. Derive a new type!
1050 pImpl->PointerTypes.add(PVT, PT = new PointerType(ValueType, AddressSpace));
1052 #ifdef DEBUG_MERGE_TYPES
1053 DEBUG(dbgs() << "Derived new type: " << *PT << "\n");
1058 const PointerType *Type::getPointerTo(unsigned addrs) const {
1059 return PointerType::get(this, addrs);
1062 bool PointerType::isValidElementType(const Type *ElemTy) {
1063 return ElemTy->getTypeID() != VoidTyID &&
1064 ElemTy->getTypeID() != LabelTyID &&
1065 ElemTy->getTypeID() != MetadataTyID;
1069 //===----------------------------------------------------------------------===//
1070 // Opaque Type Factory...
1073 OpaqueType *OpaqueType::get(LLVMContext &C) {
1074 OpaqueType *OT = new OpaqueType(C); // All opaque types are distinct
1076 LLVMContextImpl *pImpl = C.pImpl;
1077 pImpl->OpaqueTypes.insert(OT);
1083 //===----------------------------------------------------------------------===//
1084 // Derived Type Refinement Functions
1085 //===----------------------------------------------------------------------===//
1087 // addAbstractTypeUser - Notify an abstract type that there is a new user of
1088 // it. This function is called primarily by the PATypeHandle class.
1089 void Type::addAbstractTypeUser(AbstractTypeUser *U) const {
1090 assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
1091 AbstractTypeUsers.push_back(U);
1095 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1096 // no longer has a handle to the type. This function is called primarily by
1097 // the PATypeHandle class. When there are no users of the abstract type, it
1098 // is annihilated, because there is no way to get a reference to it ever again.
1100 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
1102 // Search from back to front because we will notify users from back to
1103 // front. Also, it is likely that there will be a stack like behavior to
1104 // users that register and unregister users.
1107 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1108 assert(i != 0 && "AbstractTypeUser not in user list!");
1110 --i; // Convert to be in range 0 <= i < size()
1111 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1113 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1115 #ifdef DEBUG_MERGE_TYPES
1116 DEBUG(dbgs() << " remAbstractTypeUser[" << (void*)this << ", "
1117 << *this << "][" << i << "] User = " << U << "\n");
1120 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1121 #ifdef DEBUG_MERGE_TYPES
1122 DEBUG(dbgs() << "DELETEing unused abstract type: <" << *this
1123 << ">[" << (void*)this << "]" << "\n");
1131 // unlockedRefineAbstractTypeTo - This function is used when it is discovered
1132 // that the 'this' abstract type is actually equivalent to the NewType
1133 // specified. This causes all users of 'this' to switch to reference the more
1134 // concrete type NewType and for 'this' to be deleted. Only used for internal
1137 void DerivedType::unlockedRefineAbstractTypeTo(const Type *NewType) {
1138 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1139 assert(this != NewType && "Can't refine to myself!");
1140 assert(ForwardType == 0 && "This type has already been refined!");
1142 LLVMContextImpl *pImpl = getContext().pImpl;
1144 // The descriptions may be out of date. Conservatively clear them all!
1145 pImpl->AbstractTypeDescriptions.clear();
1147 #ifdef DEBUG_MERGE_TYPES
1148 DEBUG(dbgs() << "REFINING abstract type [" << (void*)this << " "
1149 << *this << "] to [" << (void*)NewType << " "
1150 << *NewType << "]!\n");
1153 // Make sure to put the type to be refined to into a holder so that if IT gets
1154 // refined, that we will not continue using a dead reference...
1156 PATypeHolder NewTy(NewType);
1157 // Any PATypeHolders referring to this type will now automatically forward to
1158 // the type we are resolved to.
1159 ForwardType = NewType;
1160 if (ForwardType->isAbstract())
1161 ForwardType->addRef();
1163 // Add a self use of the current type so that we don't delete ourself until
1164 // after the function exits.
1166 PATypeHolder CurrentTy(this);
1168 // To make the situation simpler, we ask the subclass to remove this type from
1169 // the type map, and to replace any type uses with uses of non-abstract types.
1170 // This dramatically limits the amount of recursive type trouble we can find
1174 // Iterate over all of the uses of this type, invoking callback. Each user
1175 // should remove itself from our use list automatically. We have to check to
1176 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1177 // will not cause users to drop off of the use list. If we resolve to ourself
1180 while (!AbstractTypeUsers.empty() && NewTy != this) {
1181 AbstractTypeUser *User = AbstractTypeUsers.back();
1183 unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1184 #ifdef DEBUG_MERGE_TYPES
1185 DEBUG(dbgs() << " REFINING user " << OldSize-1 << "[" << (void*)User
1186 << "] of abstract type [" << (void*)this << " "
1187 << *this << "] to [" << (void*)NewTy.get() << " "
1188 << *NewTy << "]!\n");
1190 User->refineAbstractType(this, NewTy);
1192 assert(AbstractTypeUsers.size() != OldSize &&
1193 "AbsTyUser did not remove self from user list!");
1196 // If we were successful removing all users from the type, 'this' will be
1197 // deleted when the last PATypeHolder is destroyed or updated from this type.
1198 // This may occur on exit of this function, as the CurrentTy object is
1202 // refineAbstractTypeTo - This function is used by external callers to notify
1203 // us that this abstract type is equivalent to another type.
1205 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1206 // All recursive calls will go through unlockedRefineAbstractTypeTo,
1207 // to avoid deadlock problems.
1208 unlockedRefineAbstractTypeTo(NewType);
1211 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1212 // the current type has transitioned from being abstract to being concrete.
1214 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1215 #ifdef DEBUG_MERGE_TYPES
1216 DEBUG(dbgs() << "typeIsREFINED type: " << (void*)this << " " << *this <<"\n");
1219 unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1220 while (!AbstractTypeUsers.empty()) {
1221 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1222 ATU->typeBecameConcrete(this);
1224 assert(AbstractTypeUsers.size() < OldSize-- &&
1225 "AbstractTypeUser did not remove itself from the use list!");
1229 // refineAbstractType - Called when a contained type is found to be more
1230 // concrete - this could potentially change us from an abstract type to a
1233 void FunctionType::refineAbstractType(const DerivedType *OldType,
1234 const Type *NewType) {
1235 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1236 pImpl->FunctionTypes.RefineAbstractType(this, OldType, NewType);
1239 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1240 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1241 pImpl->FunctionTypes.TypeBecameConcrete(this, AbsTy);
1245 // refineAbstractType - Called when a contained type is found to be more
1246 // concrete - this could potentially change us from an abstract type to a
1249 void ArrayType::refineAbstractType(const DerivedType *OldType,
1250 const Type *NewType) {
1251 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1252 pImpl->ArrayTypes.RefineAbstractType(this, OldType, NewType);
1255 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1256 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1257 pImpl->ArrayTypes.TypeBecameConcrete(this, AbsTy);
1260 // refineAbstractType - Called when a contained type is found to be more
1261 // concrete - this could potentially change us from an abstract type to a
1264 void VectorType::refineAbstractType(const DerivedType *OldType,
1265 const Type *NewType) {
1266 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1267 pImpl->VectorTypes.RefineAbstractType(this, OldType, NewType);
1270 void VectorType::typeBecameConcrete(const DerivedType *AbsTy) {
1271 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1272 pImpl->VectorTypes.TypeBecameConcrete(this, AbsTy);
1275 // refineAbstractType - Called when a contained type is found to be more
1276 // concrete - this could potentially change us from an abstract type to a
1279 void StructType::refineAbstractType(const DerivedType *OldType,
1280 const Type *NewType) {
1281 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1282 pImpl->StructTypes.RefineAbstractType(this, OldType, NewType);
1285 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1286 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1287 pImpl->StructTypes.TypeBecameConcrete(this, AbsTy);
1290 // refineAbstractType - Called when a contained type is found to be more
1291 // concrete - this could potentially change us from an abstract type to a
1294 void UnionType::refineAbstractType(const DerivedType *OldType,
1295 const Type *NewType) {
1296 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1297 pImpl->UnionTypes.RefineAbstractType(this, OldType, NewType);
1300 void UnionType::typeBecameConcrete(const DerivedType *AbsTy) {
1301 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1302 pImpl->UnionTypes.TypeBecameConcrete(this, AbsTy);
1305 // refineAbstractType - Called when a contained type is found to be more
1306 // concrete - this could potentially change us from an abstract type to a
1309 void PointerType::refineAbstractType(const DerivedType *OldType,
1310 const Type *NewType) {
1311 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1312 pImpl->PointerTypes.RefineAbstractType(this, OldType, NewType);
1315 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1316 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1317 pImpl->PointerTypes.TypeBecameConcrete(this, AbsTy);
1320 bool SequentialType::indexValid(const Value *V) const {
1321 if (V->getType()->isIntegerTy())
1327 raw_ostream &operator<<(raw_ostream &OS, const Type &T) {