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 "llvm/DerivedTypes.h"
15 #include "llvm/Constants.h"
16 #include "llvm/Assembly/Writer.h"
17 #include "llvm/ADT/DepthFirstIterator.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/SCCIterator.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Support/Threading.h"
27 #include "llvm/System/Mutex.h"
28 #include "llvm/System/RWMutex.h"
33 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
34 // created and later destroyed, all in an effort to make sure that there is only
35 // a single canonical version of a type.
37 // #define DEBUG_MERGE_TYPES 1
39 AbstractTypeUser::~AbstractTypeUser() {}
42 //===----------------------------------------------------------------------===//
43 // Type Class Implementation
44 //===----------------------------------------------------------------------===//
46 // Reader/writer lock used for guarding access to the type maps.
47 static ManagedStatic<sys::RWMutex> TypeMapLock;
49 // Lock used for guarding access to AbstractTypeUsers.
50 static ManagedStatic<sys::Mutex> AbstractTypeUsersLock;
52 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
53 // for types as they are needed. Because resolution of types must invalidate
54 // all of the abstract type descriptions, we keep them in a seperate map to make
56 static ManagedStatic<TypePrinting> ConcreteTypeDescriptions;
57 static ManagedStatic<TypePrinting> AbstractTypeDescriptions;
59 /// Because of the way Type subclasses are allocated, this function is necessary
60 /// to use the correct kind of "delete" operator to deallocate the Type object.
61 /// Some type objects (FunctionTy, StructTy) allocate additional space after
62 /// the space for their derived type to hold the contained types array of
63 /// PATypeHandles. Using this allocation scheme means all the PATypeHandles are
64 /// allocated with the type object, decreasing allocations and eliminating the
65 /// need for a std::vector to be used in the Type class itself.
66 /// @brief Type destruction function
67 void Type::destroy() const {
69 // Structures and Functions allocate their contained types past the end of
70 // the type object itself. These need to be destroyed differently than the
72 if (isa<FunctionType>(this) || isa<StructType>(this)) {
73 // First, make sure we destruct any PATypeHandles allocated by these
74 // subclasses. They must be manually destructed.
75 for (unsigned i = 0; i < NumContainedTys; ++i)
76 ContainedTys[i].PATypeHandle::~PATypeHandle();
78 // Now call the destructor for the subclass directly because we're going
79 // to delete this as an array of char.
80 if (isa<FunctionType>(this))
81 static_cast<const FunctionType*>(this)->FunctionType::~FunctionType();
83 static_cast<const StructType*>(this)->StructType::~StructType();
85 // Finally, remove the memory as an array deallocation of the chars it was
87 operator delete(const_cast<Type *>(this));
92 // For all the other type subclasses, there is either no contained types or
93 // just one (all Sequentials). For Sequentials, the PATypeHandle is not
94 // allocated past the type object, its included directly in the SequentialType
95 // class. This means we can safely just do "normal" delete of this object and
96 // all the destructors that need to run will be run.
100 const Type *Type::getPrimitiveType(TypeID IDNumber) {
102 case VoidTyID : return VoidTy;
103 case FloatTyID : return FloatTy;
104 case DoubleTyID : return DoubleTy;
105 case X86_FP80TyID : return X86_FP80Ty;
106 case FP128TyID : return FP128Ty;
107 case PPC_FP128TyID : return PPC_FP128Ty;
108 case LabelTyID : return LabelTy;
109 case MetadataTyID : return MetadataTy;
115 const Type *Type::getVAArgsPromotedType() const {
116 if (ID == IntegerTyID && getSubclassData() < 32)
117 return Type::Int32Ty;
118 else if (ID == FloatTyID)
119 return Type::DoubleTy;
124 /// getScalarType - If this is a vector type, return the element type,
125 /// otherwise return this.
126 const Type *Type::getScalarType() const {
127 if (const VectorType *VTy = dyn_cast<VectorType>(this))
128 return VTy->getElementType();
132 /// isIntOrIntVector - Return true if this is an integer type or a vector of
135 bool Type::isIntOrIntVector() const {
138 if (ID != Type::VectorTyID) return false;
140 return cast<VectorType>(this)->getElementType()->isInteger();
143 /// isFPOrFPVector - Return true if this is a FP type or a vector of FP types.
145 bool Type::isFPOrFPVector() const {
146 if (ID == Type::FloatTyID || ID == Type::DoubleTyID ||
147 ID == Type::FP128TyID || ID == Type::X86_FP80TyID ||
148 ID == Type::PPC_FP128TyID)
150 if (ID != Type::VectorTyID) return false;
152 return cast<VectorType>(this)->getElementType()->isFloatingPoint();
155 // canLosslesslyBitCastTo - Return true if this type can be converted to
156 // 'Ty' without any reinterpretation of bits. For example, i8* to i32*.
158 bool Type::canLosslesslyBitCastTo(const Type *Ty) const {
159 // Identity cast means no change so return true
163 // They are not convertible unless they are at least first class types
164 if (!this->isFirstClassType() || !Ty->isFirstClassType())
167 // Vector -> Vector conversions are always lossless if the two vector types
168 // have the same size, otherwise not.
169 if (const VectorType *thisPTy = dyn_cast<VectorType>(this))
170 if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
171 return thisPTy->getBitWidth() == thatPTy->getBitWidth();
173 // At this point we have only various mismatches of the first class types
174 // remaining and ptr->ptr. Just select the lossless conversions. Everything
175 // else is not lossless.
176 if (isa<PointerType>(this))
177 return isa<PointerType>(Ty);
178 return false; // Other types have no identity values
181 unsigned Type::getPrimitiveSizeInBits() const {
182 switch (getTypeID()) {
183 case Type::FloatTyID: return 32;
184 case Type::DoubleTyID: return 64;
185 case Type::X86_FP80TyID: return 80;
186 case Type::FP128TyID: return 128;
187 case Type::PPC_FP128TyID: return 128;
188 case Type::IntegerTyID: return cast<IntegerType>(this)->getBitWidth();
189 case Type::VectorTyID: return cast<VectorType>(this)->getBitWidth();
194 /// getScalarSizeInBits - If this is a vector type, return the
195 /// getPrimitiveSizeInBits value for the element type. Otherwise return the
196 /// getPrimitiveSizeInBits value for this type.
197 unsigned Type::getScalarSizeInBits() const {
198 return getScalarType()->getPrimitiveSizeInBits();
201 /// getFPMantissaWidth - Return the width of the mantissa of this type. This
202 /// is only valid on floating point types. If the FP type does not
203 /// have a stable mantissa (e.g. ppc long double), this method returns -1.
204 int Type::getFPMantissaWidth() const {
205 if (const VectorType *VTy = dyn_cast<VectorType>(this))
206 return VTy->getElementType()->getFPMantissaWidth();
207 assert(isFloatingPoint() && "Not a floating point type!");
208 if (ID == FloatTyID) return 24;
209 if (ID == DoubleTyID) return 53;
210 if (ID == X86_FP80TyID) return 64;
211 if (ID == FP128TyID) return 113;
212 assert(ID == PPC_FP128TyID && "unknown fp type");
216 /// isSizedDerivedType - Derived types like structures and arrays are sized
217 /// iff all of the members of the type are sized as well. Since asking for
218 /// their size is relatively uncommon, move this operation out of line.
219 bool Type::isSizedDerivedType() const {
220 if (isa<IntegerType>(this))
223 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
224 return ATy->getElementType()->isSized();
226 if (const VectorType *PTy = dyn_cast<VectorType>(this))
227 return PTy->getElementType()->isSized();
229 if (!isa<StructType>(this))
232 // Okay, our struct is sized if all of the elements are...
233 for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
234 if (!(*I)->isSized())
240 /// getForwardedTypeInternal - This method is used to implement the union-find
241 /// algorithm for when a type is being forwarded to another type.
242 const Type *Type::getForwardedTypeInternal() const {
243 assert(ForwardType && "This type is not being forwarded to another type!");
245 // Check to see if the forwarded type has been forwarded on. If so, collapse
246 // the forwarding links.
247 const Type *RealForwardedType = ForwardType->getForwardedType();
248 if (!RealForwardedType)
249 return ForwardType; // No it's not forwarded again
251 // Yes, it is forwarded again. First thing, add the reference to the new
253 if (RealForwardedType->isAbstract())
254 cast<DerivedType>(RealForwardedType)->addRef();
256 // Now drop the old reference. This could cause ForwardType to get deleted.
257 cast<DerivedType>(ForwardType)->dropRef();
259 // Return the updated type.
260 ForwardType = RealForwardedType;
264 void Type::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
267 void Type::typeBecameConcrete(const DerivedType *AbsTy) {
272 std::string Type::getDescription() const {
274 isAbstract() ? *AbstractTypeDescriptions : *ConcreteTypeDescriptions;
277 raw_string_ostream DescOS(DescStr);
278 Map.print(this, DescOS);
283 bool StructType::indexValid(const Value *V) const {
284 // Structure indexes require 32-bit integer constants.
285 if (V->getType() == Type::Int32Ty)
286 if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
287 return indexValid(CU->getZExtValue());
291 bool StructType::indexValid(unsigned V) const {
292 return V < NumContainedTys;
295 // getTypeAtIndex - Given an index value into the type, return the type of the
296 // element. For a structure type, this must be a constant value...
298 const Type *StructType::getTypeAtIndex(const Value *V) const {
299 unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
300 return getTypeAtIndex(Idx);
303 const Type *StructType::getTypeAtIndex(unsigned Idx) const {
304 assert(indexValid(Idx) && "Invalid structure index!");
305 return ContainedTys[Idx];
308 //===----------------------------------------------------------------------===//
309 // Primitive 'Type' data
310 //===----------------------------------------------------------------------===//
312 const Type *Type::VoidTy = new Type(Type::VoidTyID);
313 const Type *Type::FloatTy = new Type(Type::FloatTyID);
314 const Type *Type::DoubleTy = new Type(Type::DoubleTyID);
315 const Type *Type::X86_FP80Ty = new Type(Type::X86_FP80TyID);
316 const Type *Type::FP128Ty = new Type(Type::FP128TyID);
317 const Type *Type::PPC_FP128Ty = new Type(Type::PPC_FP128TyID);
318 const Type *Type::LabelTy = new Type(Type::LabelTyID);
319 const Type *Type::MetadataTy = new Type(Type::MetadataTyID);
322 struct BuiltinIntegerType : public IntegerType {
323 explicit BuiltinIntegerType(unsigned W) : IntegerType(W) {}
326 const IntegerType *Type::Int1Ty = new BuiltinIntegerType(1);
327 const IntegerType *Type::Int8Ty = new BuiltinIntegerType(8);
328 const IntegerType *Type::Int16Ty = new BuiltinIntegerType(16);
329 const IntegerType *Type::Int32Ty = new BuiltinIntegerType(32);
330 const IntegerType *Type::Int64Ty = new BuiltinIntegerType(64);
332 //===----------------------------------------------------------------------===//
333 // Derived Type Constructors
334 //===----------------------------------------------------------------------===//
336 /// isValidReturnType - Return true if the specified type is valid as a return
338 bool FunctionType::isValidReturnType(const Type *RetTy) {
339 if (RetTy->isFirstClassType()) {
340 if (const PointerType *PTy = dyn_cast<PointerType>(RetTy))
341 return PTy->getElementType() != Type::MetadataTy;
344 if (RetTy == Type::VoidTy || RetTy == Type::MetadataTy ||
345 isa<OpaqueType>(RetTy))
348 // If this is a multiple return case, verify that each return is a first class
349 // value and that there is at least one value.
350 const StructType *SRetTy = dyn_cast<StructType>(RetTy);
351 if (SRetTy == 0 || SRetTy->getNumElements() == 0)
354 for (unsigned i = 0, e = SRetTy->getNumElements(); i != e; ++i)
355 if (!SRetTy->getElementType(i)->isFirstClassType())
360 /// isValidArgumentType - Return true if the specified type is valid as an
362 bool FunctionType::isValidArgumentType(const Type *ArgTy) {
363 if ((!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy)) ||
364 (isa<PointerType>(ArgTy) &&
365 cast<PointerType>(ArgTy)->getElementType() == Type::MetadataTy))
371 FunctionType::FunctionType(const Type *Result,
372 const std::vector<const Type*> &Params,
374 : DerivedType(FunctionTyID), isVarArgs(IsVarArgs) {
375 ContainedTys = reinterpret_cast<PATypeHandle*>(this+1);
376 NumContainedTys = Params.size() + 1; // + 1 for result type
377 assert(isValidReturnType(Result) && "invalid return type for function");
380 bool isAbstract = Result->isAbstract();
381 new (&ContainedTys[0]) PATypeHandle(Result, this);
383 for (unsigned i = 0; i != Params.size(); ++i) {
384 assert(isValidArgumentType(Params[i]) &&
385 "Not a valid type for function argument!");
386 new (&ContainedTys[i+1]) PATypeHandle(Params[i], this);
387 isAbstract |= Params[i]->isAbstract();
390 // Calculate whether or not this type is abstract
391 setAbstract(isAbstract);
394 StructType::StructType(const std::vector<const Type*> &Types, bool isPacked)
395 : CompositeType(StructTyID) {
396 ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
397 NumContainedTys = Types.size();
398 setSubclassData(isPacked);
399 bool isAbstract = false;
400 for (unsigned i = 0; i < Types.size(); ++i) {
401 assert(Types[i] && "<null> type for structure field!");
402 assert(isValidElementType(Types[i]) &&
403 "Invalid type for structure element!");
404 new (&ContainedTys[i]) PATypeHandle(Types[i], this);
405 isAbstract |= Types[i]->isAbstract();
408 // Calculate whether or not this type is abstract
409 setAbstract(isAbstract);
412 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
413 : SequentialType(ArrayTyID, ElType) {
416 // Calculate whether or not this type is abstract
417 setAbstract(ElType->isAbstract());
420 VectorType::VectorType(const Type *ElType, unsigned NumEl)
421 : SequentialType(VectorTyID, ElType) {
423 setAbstract(ElType->isAbstract());
424 assert(NumEl > 0 && "NumEl of a VectorType must be greater than 0");
425 assert(isValidElementType(ElType) &&
426 "Elements of a VectorType must be a primitive type");
431 PointerType::PointerType(const Type *E, unsigned AddrSpace)
432 : SequentialType(PointerTyID, E) {
433 AddressSpace = AddrSpace;
434 // Calculate whether or not this type is abstract
435 setAbstract(E->isAbstract());
438 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
440 #ifdef DEBUG_MERGE_TYPES
441 DOUT << "Derived new type: " << *this << "\n";
445 void PATypeHolder::destroy() {
449 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
450 // another (more concrete) type, we must eliminate all references to other
451 // types, to avoid some circular reference problems.
452 void DerivedType::dropAllTypeUses() {
453 if (NumContainedTys != 0) {
454 // The type must stay abstract. To do this, we insert a pointer to a type
455 // that will never get resolved, thus will always be abstract.
456 static Type *AlwaysOpaqueTy = OpaqueType::get();
457 static PATypeHolder Holder(AlwaysOpaqueTy);
458 ContainedTys[0] = AlwaysOpaqueTy;
460 // Change the rest of the types to be Int32Ty's. It doesn't matter what we
461 // pick so long as it doesn't point back to this type. We choose something
462 // concrete to avoid overhead for adding to AbstracTypeUser lists and stuff.
463 for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
464 ContainedTys[i] = Type::Int32Ty;
471 /// TypePromotionGraph and graph traits - this is designed to allow us to do
472 /// efficient SCC processing of type graphs. This is the exact same as
473 /// GraphTraits<Type*>, except that we pretend that concrete types have no
474 /// children to avoid processing them.
475 struct TypePromotionGraph {
477 TypePromotionGraph(Type *T) : Ty(T) {}
483 template <> struct GraphTraits<TypePromotionGraph> {
484 typedef Type NodeType;
485 typedef Type::subtype_iterator ChildIteratorType;
487 static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
488 static inline ChildIteratorType child_begin(NodeType *N) {
490 return N->subtype_begin();
491 else // No need to process children of concrete types.
492 return N->subtype_end();
494 static inline ChildIteratorType child_end(NodeType *N) {
495 return N->subtype_end();
501 // PromoteAbstractToConcrete - This is a recursive function that walks a type
502 // graph calculating whether or not a type is abstract.
504 void Type::PromoteAbstractToConcrete() {
505 if (!isAbstract()) return;
507 scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
508 scc_iterator<TypePromotionGraph> SE = scc_end (TypePromotionGraph(this));
510 for (; SI != SE; ++SI) {
511 std::vector<Type*> &SCC = *SI;
513 // Concrete types are leaves in the tree. Since an SCC will either be all
514 // abstract or all concrete, we only need to check one type.
515 if (SCC[0]->isAbstract()) {
516 if (isa<OpaqueType>(SCC[0]))
517 return; // Not going to be concrete, sorry.
519 // If all of the children of all of the types in this SCC are concrete,
520 // then this SCC is now concrete as well. If not, neither this SCC, nor
521 // any parent SCCs will be concrete, so we might as well just exit.
522 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
523 for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
524 E = SCC[i]->subtype_end(); CI != E; ++CI)
525 if ((*CI)->isAbstract())
526 // If the child type is in our SCC, it doesn't make the entire SCC
527 // abstract unless there is a non-SCC abstract type.
528 if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
529 return; // Not going to be concrete, sorry.
531 // Okay, we just discovered this whole SCC is now concrete, mark it as
533 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
534 assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
536 SCC[i]->setAbstract(false);
539 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
540 assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
541 // The type just became concrete, notify all users!
542 cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
549 //===----------------------------------------------------------------------===//
550 // Type Structural Equality Testing
551 //===----------------------------------------------------------------------===//
553 // TypesEqual - Two types are considered structurally equal if they have the
554 // same "shape": Every level and element of the types have identical primitive
555 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
556 // be pointer equals to be equivalent though. This uses an optimistic algorithm
557 // that assumes that two graphs are the same until proven otherwise.
559 static bool TypesEqual(const Type *Ty, const Type *Ty2,
560 std::map<const Type *, const Type *> &EqTypes) {
561 if (Ty == Ty2) return true;
562 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
563 if (isa<OpaqueType>(Ty))
564 return false; // Two unequal opaque types are never equal
566 std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
567 if (It != EqTypes.end())
568 return It->second == Ty2; // Looping back on a type, check for equality
570 // Otherwise, add the mapping to the table to make sure we don't get
571 // recursion on the types...
572 EqTypes.insert(It, std::make_pair(Ty, Ty2));
574 // Two really annoying special cases that breaks an otherwise nice simple
575 // algorithm is the fact that arraytypes have sizes that differentiates types,
576 // and that function types can be varargs or not. Consider this now.
578 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
579 const IntegerType *ITy2 = cast<IntegerType>(Ty2);
580 return ITy->getBitWidth() == ITy2->getBitWidth();
581 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
582 const PointerType *PTy2 = cast<PointerType>(Ty2);
583 return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
584 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
585 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
586 const StructType *STy2 = cast<StructType>(Ty2);
587 if (STy->getNumElements() != STy2->getNumElements()) return false;
588 if (STy->isPacked() != STy2->isPacked()) return false;
589 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
590 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
593 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
594 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
595 return ATy->getNumElements() == ATy2->getNumElements() &&
596 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
597 } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
598 const VectorType *PTy2 = cast<VectorType>(Ty2);
599 return PTy->getNumElements() == PTy2->getNumElements() &&
600 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
601 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
602 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
603 if (FTy->isVarArg() != FTy2->isVarArg() ||
604 FTy->getNumParams() != FTy2->getNumParams() ||
605 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
607 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
608 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
613 assert(0 && "Unknown derived type!");
618 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
619 std::map<const Type *, const Type *> EqTypes;
620 return TypesEqual(Ty, Ty2, EqTypes);
623 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
624 // TargetTy in the type graph. We know that Ty is an abstract type, so if we
625 // ever reach a non-abstract type, we know that we don't need to search the
627 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
628 SmallPtrSet<const Type*, 128> &VisitedTypes) {
629 if (TargetTy == CurTy) return true;
630 if (!CurTy->isAbstract()) return false;
632 if (!VisitedTypes.insert(CurTy))
633 return false; // Already been here.
635 for (Type::subtype_iterator I = CurTy->subtype_begin(),
636 E = CurTy->subtype_end(); I != E; ++I)
637 if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
642 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
643 SmallPtrSet<const Type*, 128> &VisitedTypes) {
644 if (TargetTy == CurTy) return true;
646 if (!VisitedTypes.insert(CurTy))
647 return false; // Already been here.
649 for (Type::subtype_iterator I = CurTy->subtype_begin(),
650 E = CurTy->subtype_end(); I != E; ++I)
651 if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
656 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
658 static bool TypeHasCycleThroughItself(const Type *Ty) {
659 SmallPtrSet<const Type*, 128> VisitedTypes;
661 if (Ty->isAbstract()) { // Optimized case for abstract types.
662 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
664 if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
667 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
669 if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
675 /// getSubElementHash - Generate a hash value for all of the SubType's of this
676 /// type. The hash value is guaranteed to be zero if any of the subtypes are
677 /// an opaque type. Otherwise we try to mix them in as well as possible, but do
678 /// not look at the subtype's subtype's.
679 static unsigned getSubElementHash(const Type *Ty) {
680 unsigned HashVal = 0;
681 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
684 const Type *SubTy = I->get();
685 HashVal += SubTy->getTypeID();
686 switch (SubTy->getTypeID()) {
688 case Type::OpaqueTyID: return 0; // Opaque -> hash = 0 no matter what.
689 case Type::IntegerTyID:
690 HashVal ^= (cast<IntegerType>(SubTy)->getBitWidth() << 3);
692 case Type::FunctionTyID:
693 HashVal ^= cast<FunctionType>(SubTy)->getNumParams()*2 +
694 cast<FunctionType>(SubTy)->isVarArg();
696 case Type::ArrayTyID:
697 HashVal ^= cast<ArrayType>(SubTy)->getNumElements();
699 case Type::VectorTyID:
700 HashVal ^= cast<VectorType>(SubTy)->getNumElements();
702 case Type::StructTyID:
703 HashVal ^= cast<StructType>(SubTy)->getNumElements();
705 case Type::PointerTyID:
706 HashVal ^= cast<PointerType>(SubTy)->getAddressSpace();
710 return HashVal ? HashVal : 1; // Do not return zero unless opaque subty.
713 //===----------------------------------------------------------------------===//
714 // Derived Type Factory Functions
715 //===----------------------------------------------------------------------===//
720 /// TypesByHash - Keep track of types by their structure hash value. Note
721 /// that we only keep track of types that have cycles through themselves in
724 std::multimap<unsigned, PATypeHolder> TypesByHash;
728 // PATypeHolder won't destroy non-abstract types.
729 // We can't destroy them by simply iterating, because
730 // they may contain references to each-other.
732 for (std::multimap<unsigned, PATypeHolder>::iterator I
733 = TypesByHash.begin(), E = TypesByHash.end(); I != E; ++I) {
734 Type *Ty = const_cast<Type*>(I->second.Ty);
736 // We can't invoke destroy or delete, because the type may
737 // contain references to already freed types.
738 // So we have to destruct the object the ugly way.
740 Ty->AbstractTypeUsers.clear();
741 static_cast<const Type*>(Ty)->Type::~Type();
748 void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
749 std::multimap<unsigned, PATypeHolder>::iterator I =
750 TypesByHash.lower_bound(Hash);
751 for (; I != TypesByHash.end() && I->first == Hash; ++I) {
752 if (I->second == Ty) {
753 TypesByHash.erase(I);
758 // This must be do to an opaque type that was resolved. Switch down to hash
760 assert(Hash && "Didn't find type entry!");
761 RemoveFromTypesByHash(0, Ty);
764 /// TypeBecameConcrete - When Ty gets a notification that TheType just became
765 /// concrete, drop uses and make Ty non-abstract if we should.
766 void TypeBecameConcrete(DerivedType *Ty, const DerivedType *TheType) {
767 // If the element just became concrete, remove 'ty' from the abstract
768 // type user list for the type. Do this for as many times as Ty uses
770 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
772 if (I->get() == TheType)
773 TheType->removeAbstractTypeUser(Ty);
775 // If the type is currently thought to be abstract, rescan all of our
776 // subtypes to see if the type has just become concrete! Note that this
777 // may send out notifications to AbstractTypeUsers that types become
779 if (Ty->isAbstract())
780 Ty->PromoteAbstractToConcrete();
786 // TypeMap - Make sure that only one instance of a particular type may be
787 // created on any given run of the compiler... note that this involves updating
788 // our map if an abstract type gets refined somehow.
791 template<class ValType, class TypeClass>
792 class TypeMap : public TypeMapBase {
793 std::map<ValType, PATypeHolder> Map;
795 typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
796 ~TypeMap() { print("ON EXIT"); }
798 inline TypeClass *get(const ValType &V) {
799 iterator I = Map.find(V);
800 return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
803 inline void add(const ValType &V, TypeClass *Ty) {
804 Map.insert(std::make_pair(V, Ty));
806 // If this type has a cycle, remember it.
807 TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
811 /// RefineAbstractType - This method is called after we have merged a type
812 /// with another one. We must now either merge the type away with
813 /// some other type or reinstall it in the map with it's new configuration.
814 void RefineAbstractType(TypeClass *Ty, const DerivedType *OldType,
815 const Type *NewType) {
816 #ifdef DEBUG_MERGE_TYPES
817 DOUT << "RefineAbstractType(" << (void*)OldType << "[" << *OldType
818 << "], " << (void*)NewType << " [" << *NewType << "])\n";
821 // Otherwise, we are changing one subelement type into another. Clearly the
822 // OldType must have been abstract, making us abstract.
823 assert(Ty->isAbstract() && "Refining a non-abstract type!");
824 assert(OldType != NewType);
826 // Make a temporary type holder for the type so that it doesn't disappear on
827 // us when we erase the entry from the map.
828 PATypeHolder TyHolder = Ty;
830 // The old record is now out-of-date, because one of the children has been
831 // updated. Remove the obsolete entry from the map.
832 unsigned NumErased = Map.erase(ValType::get(Ty));
833 assert(NumErased && "Element not found!"); NumErased = NumErased;
835 // Remember the structural hash for the type before we start hacking on it,
836 // in case we need it later.
837 unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
839 // Find the type element we are refining... and change it now!
840 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i)
841 if (Ty->ContainedTys[i] == OldType)
842 Ty->ContainedTys[i] = NewType;
843 unsigned NewTypeHash = ValType::hashTypeStructure(Ty);
845 // If there are no cycles going through this node, we can do a simple,
846 // efficient lookup in the map, instead of an inefficient nasty linear
848 if (!TypeHasCycleThroughItself(Ty)) {
849 typename std::map<ValType, PATypeHolder>::iterator I;
852 tie(I, Inserted) = Map.insert(std::make_pair(ValType::get(Ty), Ty));
854 // Refined to a different type altogether?
855 RemoveFromTypesByHash(OldTypeHash, Ty);
857 // We already have this type in the table. Get rid of the newly refined
859 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
860 Ty->unlockedRefineAbstractTypeTo(NewTy);
864 // Now we check to see if there is an existing entry in the table which is
865 // structurally identical to the newly refined type. If so, this type
866 // gets refined to the pre-existing type.
868 std::multimap<unsigned, PATypeHolder>::iterator I, E, Entry;
869 tie(I, E) = TypesByHash.equal_range(NewTypeHash);
871 for (; I != E; ++I) {
872 if (I->second == Ty) {
873 // Remember the position of the old type if we see it in our scan.
876 if (TypesEqual(Ty, I->second)) {
877 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
879 // Remove the old entry form TypesByHash. If the hash values differ
880 // now, remove it from the old place. Otherwise, continue scanning
881 // withing this hashcode to reduce work.
882 if (NewTypeHash != OldTypeHash) {
883 RemoveFromTypesByHash(OldTypeHash, Ty);
886 // Find the location of Ty in the TypesByHash structure if we
887 // haven't seen it already.
888 while (I->second != Ty) {
890 assert(I != E && "Structure doesn't contain type??");
894 TypesByHash.erase(Entry);
896 Ty->unlockedRefineAbstractTypeTo(NewTy);
902 // If there is no existing type of the same structure, we reinsert an
903 // updated record into the map.
904 Map.insert(std::make_pair(ValType::get(Ty), Ty));
907 // If the hash codes differ, update TypesByHash
908 if (NewTypeHash != OldTypeHash) {
909 RemoveFromTypesByHash(OldTypeHash, Ty);
910 TypesByHash.insert(std::make_pair(NewTypeHash, Ty));
913 // If the type is currently thought to be abstract, rescan all of our
914 // subtypes to see if the type has just become concrete! Note that this
915 // may send out notifications to AbstractTypeUsers that types become
917 if (Ty->isAbstract())
918 Ty->PromoteAbstractToConcrete();
921 void print(const char *Arg) const {
922 #ifdef DEBUG_MERGE_TYPES
923 DOUT << "TypeMap<>::" << Arg << " table contents:\n";
925 for (typename std::map<ValType, PATypeHolder>::const_iterator I
926 = Map.begin(), E = Map.end(); I != E; ++I)
927 DOUT << " " << (++i) << ". " << (void*)I->second.get() << " "
928 << *I->second.get() << "\n";
932 void dump() const { print("dump output"); }
937 //===----------------------------------------------------------------------===//
938 // Function Type Factory and Value Class...
941 //===----------------------------------------------------------------------===//
942 // Integer Type Factory...
945 class IntegerValType {
948 IntegerValType(uint16_t numbits) : bits(numbits) {}
950 static IntegerValType get(const IntegerType *Ty) {
951 return IntegerValType(Ty->getBitWidth());
954 static unsigned hashTypeStructure(const IntegerType *Ty) {
955 return (unsigned)Ty->getBitWidth();
958 inline bool operator<(const IntegerValType &IVT) const {
959 return bits < IVT.bits;
964 static ManagedStatic<TypeMap<IntegerValType, IntegerType> > IntegerTypes;
966 const IntegerType *IntegerType::get(unsigned NumBits) {
967 assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
968 assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
970 // Check for the built-in integer types
972 case 1: return cast<IntegerType>(Type::Int1Ty);
973 case 8: return cast<IntegerType>(Type::Int8Ty);
974 case 16: return cast<IntegerType>(Type::Int16Ty);
975 case 32: return cast<IntegerType>(Type::Int32Ty);
976 case 64: return cast<IntegerType>(Type::Int64Ty);
981 IntegerValType IVT(NumBits);
982 IntegerType *ITy = 0;
983 if (llvm_is_multithreaded()) {
984 // First, see if the type is already in the table, for which
985 // a reader lock suffices.
986 TypeMapLock->reader_acquire();
987 ITy = IntegerTypes->get(IVT);
988 TypeMapLock->reader_release();
991 // OK, not in the table, get a writer lock.
992 TypeMapLock->writer_acquire();
993 ITy = IntegerTypes->get(IVT);
995 // We need to _recheck_ the table in case someone
996 // put it in between when we released the reader lock
997 // and when we gained the writer lock!
999 // Value not found. Derive a new type!
1000 ITy = new IntegerType(NumBits);
1001 IntegerTypes->add(IVT, ITy);
1004 TypeMapLock->writer_release();
1007 ITy = IntegerTypes->get(IVT);
1008 if (ITy) return ITy; // Found a match, return it!
1010 // Value not found. Derive a new type!
1011 ITy = new IntegerType(NumBits);
1012 IntegerTypes->add(IVT, ITy);
1014 #ifdef DEBUG_MERGE_TYPES
1015 DOUT << "Derived new type: " << *ITy << "\n";
1020 bool IntegerType::isPowerOf2ByteWidth() const {
1021 unsigned BitWidth = getBitWidth();
1022 return (BitWidth > 7) && isPowerOf2_32(BitWidth);
1025 APInt IntegerType::getMask() const {
1026 return APInt::getAllOnesValue(getBitWidth());
1029 // FunctionValType - Define a class to hold the key that goes into the TypeMap
1032 class FunctionValType {
1034 std::vector<const Type*> ArgTypes;
1037 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
1038 bool isVA) : RetTy(ret), ArgTypes(args), isVarArg(isVA) {}
1040 static FunctionValType get(const FunctionType *FT);
1042 static unsigned hashTypeStructure(const FunctionType *FT) {
1043 unsigned Result = FT->getNumParams()*2 + FT->isVarArg();
1047 inline bool operator<(const FunctionValType &MTV) const {
1048 if (RetTy < MTV.RetTy) return true;
1049 if (RetTy > MTV.RetTy) return false;
1050 if (isVarArg < MTV.isVarArg) return true;
1051 if (isVarArg > MTV.isVarArg) return false;
1052 if (ArgTypes < MTV.ArgTypes) return true;
1053 if (ArgTypes > MTV.ArgTypes) return false;
1059 // Define the actual map itself now...
1060 static ManagedStatic<TypeMap<FunctionValType, FunctionType> > FunctionTypes;
1062 FunctionValType FunctionValType::get(const FunctionType *FT) {
1063 // Build up a FunctionValType
1064 std::vector<const Type *> ParamTypes;
1065 ParamTypes.reserve(FT->getNumParams());
1066 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1067 ParamTypes.push_back(FT->getParamType(i));
1068 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
1072 // FunctionType::get - The factory function for the FunctionType class...
1073 FunctionType *FunctionType::get(const Type *ReturnType,
1074 const std::vector<const Type*> &Params,
1076 FunctionValType VT(ReturnType, Params, isVarArg);
1077 FunctionType *FT = 0;
1079 if (llvm_is_multithreaded()) {
1080 TypeMapLock->reader_acquire();
1081 FT = FunctionTypes->get(VT);
1082 TypeMapLock->reader_release();
1085 TypeMapLock->writer_acquire();
1087 // Have to check again here, because it might have
1088 // been inserted between when we release the reader
1089 // lock and when we acquired the writer lock.
1090 FT = FunctionTypes->get(VT);
1092 FT = (FunctionType*) operator new(sizeof(FunctionType) +
1093 sizeof(PATypeHandle)*(Params.size()+1));
1094 new (FT) FunctionType(ReturnType, Params, isVarArg);
1095 FunctionTypes->add(VT, FT);
1097 TypeMapLock->writer_release();
1100 FT = FunctionTypes->get(VT);
1104 FT = (FunctionType*) operator new(sizeof(FunctionType) +
1105 sizeof(PATypeHandle)*(Params.size()+1));
1106 new (FT) FunctionType(ReturnType, Params, isVarArg);
1107 FunctionTypes->add(VT, FT);
1110 #ifdef DEBUG_MERGE_TYPES
1111 DOUT << "Derived new type: " << FT << "\n";
1116 //===----------------------------------------------------------------------===//
1117 // Array Type Factory...
1120 class ArrayValType {
1124 ArrayValType(const Type *val, uint64_t sz) : ValTy(val), Size(sz) {}
1126 static ArrayValType get(const ArrayType *AT) {
1127 return ArrayValType(AT->getElementType(), AT->getNumElements());
1130 static unsigned hashTypeStructure(const ArrayType *AT) {
1131 return (unsigned)AT->getNumElements();
1134 inline bool operator<(const ArrayValType &MTV) const {
1135 if (Size < MTV.Size) return true;
1136 return Size == MTV.Size && ValTy < MTV.ValTy;
1141 static ManagedStatic<TypeMap<ArrayValType, ArrayType> > ArrayTypes;
1143 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
1144 assert(ElementType && "Can't get array of <null> types!");
1145 assert(isValidElementType(ElementType) && "Invalid type for array element!");
1147 ArrayValType AVT(ElementType, NumElements);
1150 if (llvm_is_multithreaded()) {
1151 TypeMapLock->reader_acquire();
1152 AT = ArrayTypes->get(AVT);
1153 TypeMapLock->reader_release();
1156 TypeMapLock->writer_acquire();
1158 // Recheck. Might have changed between release and acquire.
1159 AT = ArrayTypes->get(AVT);
1161 // Value not found. Derive a new type!
1162 ArrayTypes->add(AVT, AT = new ArrayType(ElementType, NumElements));
1164 TypeMapLock->writer_release();
1167 AT = ArrayTypes->get(AVT);
1168 if (AT) return AT; // Found a match, return it!
1170 // Value not found. Derive a new type!
1171 ArrayTypes->add(AVT, AT = new ArrayType(ElementType, NumElements));
1173 #ifdef DEBUG_MERGE_TYPES
1174 DOUT << "Derived new type: " << *AT << "\n";
1179 bool ArrayType::isValidElementType(const Type *ElemTy) {
1180 if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy ||
1181 ElemTy == Type::MetadataTy)
1184 if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
1185 if (PTy->getElementType() == Type::MetadataTy)
1192 //===----------------------------------------------------------------------===//
1193 // Vector Type Factory...
1196 class VectorValType {
1200 VectorValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
1202 static VectorValType get(const VectorType *PT) {
1203 return VectorValType(PT->getElementType(), PT->getNumElements());
1206 static unsigned hashTypeStructure(const VectorType *PT) {
1207 return PT->getNumElements();
1210 inline bool operator<(const VectorValType &MTV) const {
1211 if (Size < MTV.Size) return true;
1212 return Size == MTV.Size && ValTy < MTV.ValTy;
1217 static ManagedStatic<TypeMap<VectorValType, VectorType> > VectorTypes;
1219 VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) {
1220 assert(ElementType && "Can't get vector of <null> types!");
1222 VectorValType PVT(ElementType, NumElements);
1225 if (llvm_is_multithreaded()) {
1226 TypeMapLock->reader_acquire();
1227 PT = VectorTypes->get(PVT);
1228 TypeMapLock->reader_release();
1231 TypeMapLock->writer_acquire();
1232 PT = VectorTypes->get(PVT);
1233 // Recheck. Might have changed between release and acquire.
1235 VectorTypes->add(PVT, PT = new VectorType(ElementType, NumElements));
1237 TypeMapLock->writer_acquire();
1240 PT = VectorTypes->get(PVT);
1241 if (PT) return PT; // Found a match, return it!
1243 // Value not found. Derive a new type!
1244 VectorTypes->add(PVT, PT = new VectorType(ElementType, NumElements));
1246 #ifdef DEBUG_MERGE_TYPES
1247 DOUT << "Derived new type: " << *PT << "\n";
1252 bool VectorType::isValidElementType(const Type *ElemTy) {
1253 if (ElemTy->isInteger() || ElemTy->isFloatingPoint() ||
1254 isa<OpaqueType>(ElemTy))
1260 //===----------------------------------------------------------------------===//
1261 // Struct Type Factory...
1265 // StructValType - Define a class to hold the key that goes into the TypeMap
1267 class StructValType {
1268 std::vector<const Type*> ElTypes;
1271 StructValType(const std::vector<const Type*> &args, bool isPacked)
1272 : ElTypes(args), packed(isPacked) {}
1274 static StructValType get(const StructType *ST) {
1275 std::vector<const Type *> ElTypes;
1276 ElTypes.reserve(ST->getNumElements());
1277 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
1278 ElTypes.push_back(ST->getElementType(i));
1280 return StructValType(ElTypes, ST->isPacked());
1283 static unsigned hashTypeStructure(const StructType *ST) {
1284 return ST->getNumElements();
1287 inline bool operator<(const StructValType &STV) const {
1288 if (ElTypes < STV.ElTypes) return true;
1289 else if (ElTypes > STV.ElTypes) return false;
1290 else return (int)packed < (int)STV.packed;
1295 static ManagedStatic<TypeMap<StructValType, StructType> > StructTypes;
1297 StructType *StructType::get(const std::vector<const Type*> &ETypes,
1299 StructValType STV(ETypes, isPacked);
1302 if (llvm_is_multithreaded()) {
1303 TypeMapLock->reader_acquire();
1304 ST = StructTypes->get(STV);
1305 TypeMapLock->reader_release();
1308 TypeMapLock->writer_acquire();
1309 ST = StructTypes->get(STV);
1310 // Recheck. Might have changed between release and acquire.
1312 // Value not found. Derive a new type!
1313 ST = (StructType*) operator new(sizeof(StructType) +
1314 sizeof(PATypeHandle) * ETypes.size());
1315 new (ST) StructType(ETypes, isPacked);
1316 StructTypes->add(STV, ST);
1318 TypeMapLock->writer_release();
1321 ST = StructTypes->get(STV);
1324 // Value not found. Derive a new type!
1325 ST = (StructType*) operator new(sizeof(StructType) +
1326 sizeof(PATypeHandle) * ETypes.size());
1327 new (ST) StructType(ETypes, isPacked);
1328 StructTypes->add(STV, ST);
1330 #ifdef DEBUG_MERGE_TYPES
1331 DOUT << "Derived new type: " << *ST << "\n";
1336 StructType *StructType::get(const Type *type, ...) {
1338 std::vector<const llvm::Type*> StructFields;
1341 StructFields.push_back(type);
1342 type = va_arg(ap, llvm::Type*);
1344 return llvm::StructType::get(StructFields);
1347 bool StructType::isValidElementType(const Type *ElemTy) {
1348 if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy ||
1349 ElemTy == Type::MetadataTy)
1352 if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
1353 if (PTy->getElementType() == Type::MetadataTy)
1360 //===----------------------------------------------------------------------===//
1361 // Pointer Type Factory...
1364 // PointerValType - Define a class to hold the key that goes into the TypeMap
1367 class PointerValType {
1369 unsigned AddressSpace;
1371 PointerValType(const Type *val, unsigned as) : ValTy(val), AddressSpace(as) {}
1373 static PointerValType get(const PointerType *PT) {
1374 return PointerValType(PT->getElementType(), PT->getAddressSpace());
1377 static unsigned hashTypeStructure(const PointerType *PT) {
1378 return getSubElementHash(PT);
1381 bool operator<(const PointerValType &MTV) const {
1382 if (AddressSpace < MTV.AddressSpace) return true;
1383 return AddressSpace == MTV.AddressSpace && ValTy < MTV.ValTy;
1388 static ManagedStatic<TypeMap<PointerValType, PointerType> > PointerTypes;
1390 PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) {
1391 assert(ValueType && "Can't get a pointer to <null> type!");
1392 assert(ValueType != Type::VoidTy &&
1393 "Pointer to void is not valid, use i8* instead!");
1394 assert(isValidElementType(ValueType) && "Invalid type for pointer element!");
1395 PointerValType PVT(ValueType, AddressSpace);
1397 PointerType *PT = 0;
1399 if (llvm_is_multithreaded()) {
1400 TypeMapLock->reader_acquire();
1401 PT = PointerTypes->get(PVT);
1402 TypeMapLock->reader_release();
1405 TypeMapLock->writer_acquire();
1406 PT = PointerTypes->get(PVT);
1407 // Recheck. Might have changed between release and acquire.
1409 // Value not found. Derive a new type!
1410 PointerTypes->add(PVT, PT = new PointerType(ValueType, AddressSpace));
1412 TypeMapLock->writer_release();
1415 PT = PointerTypes->get(PVT);
1418 // Value not found. Derive a new type!
1419 PointerTypes->add(PVT, PT = new PointerType(ValueType, AddressSpace));
1421 #ifdef DEBUG_MERGE_TYPES
1422 DOUT << "Derived new type: " << *PT << "\n";
1427 PointerType *Type::getPointerTo(unsigned addrs) const {
1428 return PointerType::get(this, addrs);
1431 bool PointerType::isValidElementType(const Type *ElemTy) {
1432 if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy)
1435 if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
1436 if (PTy->getElementType() == Type::MetadataTy)
1443 //===----------------------------------------------------------------------===//
1444 // Derived Type Refinement Functions
1445 //===----------------------------------------------------------------------===//
1447 // addAbstractTypeUser - Notify an abstract type that there is a new user of
1448 // it. This function is called primarily by the PATypeHandle class.
1449 void Type::addAbstractTypeUser(AbstractTypeUser *U) const {
1450 assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
1451 if (llvm_is_multithreaded()) {
1452 AbstractTypeUsersLock->acquire();
1453 AbstractTypeUsers.push_back(U);
1454 AbstractTypeUsersLock->release();
1456 AbstractTypeUsers.push_back(U);
1461 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1462 // no longer has a handle to the type. This function is called primarily by
1463 // the PATypeHandle class. When there are no users of the abstract type, it
1464 // is annihilated, because there is no way to get a reference to it ever again.
1466 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
1467 if (llvm_is_multithreaded()) AbstractTypeUsersLock->acquire();
1469 // Search from back to front because we will notify users from back to
1470 // front. Also, it is likely that there will be a stack like behavior to
1471 // users that register and unregister users.
1474 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1475 assert(i != 0 && "AbstractTypeUser not in user list!");
1477 --i; // Convert to be in range 0 <= i < size()
1478 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1480 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1482 #ifdef DEBUG_MERGE_TYPES
1483 DOUT << " remAbstractTypeUser[" << (void*)this << ", "
1484 << *this << "][" << i << "] User = " << U << "\n";
1487 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1488 #ifdef DEBUG_MERGE_TYPES
1489 DOUT << "DELETEing unused abstract type: <" << *this
1490 << ">[" << (void*)this << "]" << "\n";
1496 if (llvm_is_multithreaded()) AbstractTypeUsersLock->release();
1499 // unlockedRefineAbstractTypeTo - This function is used when it is discovered
1500 // that the 'this' abstract type is actually equivalent to the NewType
1501 // specified. This causes all users of 'this' to switch to reference the more
1502 // concrete type NewType and for 'this' to be deleted. Only used for internal
1505 void DerivedType::unlockedRefineAbstractTypeTo(const Type *NewType) {
1506 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1507 assert(this != NewType && "Can't refine to myself!");
1508 assert(ForwardType == 0 && "This type has already been refined!");
1510 // The descriptions may be out of date. Conservatively clear them all!
1511 if (AbstractTypeDescriptions.isConstructed())
1512 AbstractTypeDescriptions->clear();
1514 #ifdef DEBUG_MERGE_TYPES
1515 DOUT << "REFINING abstract type [" << (void*)this << " "
1516 << *this << "] to [" << (void*)NewType << " "
1517 << *NewType << "]!\n";
1520 // Make sure to put the type to be refined to into a holder so that if IT gets
1521 // refined, that we will not continue using a dead reference...
1523 PATypeHolder NewTy(NewType);
1524 // Any PATypeHolders referring to this type will now automatically forward o
1525 // the type we are resolved to.
1526 ForwardType = NewType;
1527 if (NewType->isAbstract())
1528 cast<DerivedType>(NewType)->addRef();
1530 // Add a self use of the current type so that we don't delete ourself until
1531 // after the function exits.
1533 PATypeHolder CurrentTy(this);
1535 // To make the situation simpler, we ask the subclass to remove this type from
1536 // the type map, and to replace any type uses with uses of non-abstract types.
1537 // This dramatically limits the amount of recursive type trouble we can find
1541 // Iterate over all of the uses of this type, invoking callback. Each user
1542 // should remove itself from our use list automatically. We have to check to
1543 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1544 // will not cause users to drop off of the use list. If we resolve to ourself
1547 while (!AbstractTypeUsers.empty() && NewTy != this) {
1548 AbstractTypeUser *User = AbstractTypeUsers.back();
1550 unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1551 #ifdef DEBUG_MERGE_TYPES
1552 DOUT << " REFINING user " << OldSize-1 << "[" << (void*)User
1553 << "] of abstract type [" << (void*)this << " "
1554 << *this << "] to [" << (void*)NewTy.get() << " "
1555 << *NewTy << "]!\n";
1557 User->refineAbstractType(this, NewTy);
1559 assert(AbstractTypeUsers.size() != OldSize &&
1560 "AbsTyUser did not remove self from user list!");
1563 // If we were successful removing all users from the type, 'this' will be
1564 // deleted when the last PATypeHolder is destroyed or updated from this type.
1565 // This may occur on exit of this function, as the CurrentTy object is
1569 // refineAbstractTypeTo - This function is used by external callers to notify
1570 // us that this abstract type is equivalent to another type.
1572 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1573 if (llvm_is_multithreaded()) {
1574 // All recursive calls will go through unlockedRefineAbstractTypeTo,
1575 // to avoid deadlock problems.
1576 TypeMapLock->writer_acquire();
1577 unlockedRefineAbstractTypeTo(NewType);
1578 TypeMapLock->writer_release();
1580 unlockedRefineAbstractTypeTo(NewType);
1584 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1585 // the current type has transitioned from being abstract to being concrete.
1587 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1588 #ifdef DEBUG_MERGE_TYPES
1589 DOUT << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1592 unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1593 while (!AbstractTypeUsers.empty()) {
1594 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1595 ATU->typeBecameConcrete(this);
1597 assert(AbstractTypeUsers.size() < OldSize-- &&
1598 "AbstractTypeUser did not remove itself from the use list!");
1602 // refineAbstractType - Called when a contained type is found to be more
1603 // concrete - this could potentially change us from an abstract type to a
1606 void FunctionType::refineAbstractType(const DerivedType *OldType,
1607 const Type *NewType) {
1608 FunctionTypes->RefineAbstractType(this, OldType, NewType);
1611 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1612 FunctionTypes->TypeBecameConcrete(this, AbsTy);
1616 // refineAbstractType - Called when a contained type is found to be more
1617 // concrete - this could potentially change us from an abstract type to a
1620 void ArrayType::refineAbstractType(const DerivedType *OldType,
1621 const Type *NewType) {
1622 ArrayTypes->RefineAbstractType(this, OldType, NewType);
1625 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1626 ArrayTypes->TypeBecameConcrete(this, AbsTy);
1629 // refineAbstractType - Called when a contained type is found to be more
1630 // concrete - this could potentially change us from an abstract type to a
1633 void VectorType::refineAbstractType(const DerivedType *OldType,
1634 const Type *NewType) {
1635 VectorTypes->RefineAbstractType(this, OldType, NewType);
1638 void VectorType::typeBecameConcrete(const DerivedType *AbsTy) {
1639 VectorTypes->TypeBecameConcrete(this, AbsTy);
1642 // refineAbstractType - Called when a contained type is found to be more
1643 // concrete - this could potentially change us from an abstract type to a
1646 void StructType::refineAbstractType(const DerivedType *OldType,
1647 const Type *NewType) {
1648 StructTypes->RefineAbstractType(this, OldType, NewType);
1651 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1652 StructTypes->TypeBecameConcrete(this, AbsTy);
1655 // refineAbstractType - Called when a contained type is found to be more
1656 // concrete - this could potentially change us from an abstract type to a
1659 void PointerType::refineAbstractType(const DerivedType *OldType,
1660 const Type *NewType) {
1661 PointerTypes->RefineAbstractType(this, OldType, NewType);
1664 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1665 PointerTypes->TypeBecameConcrete(this, AbsTy);
1668 bool SequentialType::indexValid(const Value *V) const {
1669 if (isa<IntegerType>(V->getType()))
1675 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1677 OS << "<null> value!\n";
1683 std::ostream &operator<<(std::ostream &OS, const Type &T) {
1688 raw_ostream &operator<<(raw_ostream &OS, const Type &T) {