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 // Recursive 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 = 0;
457 static PATypeHolder* Holder = 0;
458 if (!AlwaysOpaqueTy) {
459 if (llvm_is_multithreaded()) {
460 llvm_acquire_global_lock();
462 if (!AlwaysOpaqueTy) {
463 Type *tmp = OpaqueType::get();
464 PATypeHolder* tmp2 = new PATypeHolder(AlwaysOpaqueTy);
466 AlwaysOpaqueTy = tmp;
470 llvm_release_global_lock();
472 AlwaysOpaqueTy = OpaqueType::get();
473 Holder = new PATypeHolder(AlwaysOpaqueTy);
477 ContainedTys[0] = AlwaysOpaqueTy;
479 // Change the rest of the types to be Int32Ty's. It doesn't matter what we
480 // pick so long as it doesn't point back to this type. We choose something
481 // concrete to avoid overhead for adding to AbstracTypeUser lists and stuff.
482 for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
483 ContainedTys[i] = Type::Int32Ty;
490 /// TypePromotionGraph and graph traits - this is designed to allow us to do
491 /// efficient SCC processing of type graphs. This is the exact same as
492 /// GraphTraits<Type*>, except that we pretend that concrete types have no
493 /// children to avoid processing them.
494 struct TypePromotionGraph {
496 TypePromotionGraph(Type *T) : Ty(T) {}
502 template <> struct GraphTraits<TypePromotionGraph> {
503 typedef Type NodeType;
504 typedef Type::subtype_iterator ChildIteratorType;
506 static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
507 static inline ChildIteratorType child_begin(NodeType *N) {
509 return N->subtype_begin();
510 else // No need to process children of concrete types.
511 return N->subtype_end();
513 static inline ChildIteratorType child_end(NodeType *N) {
514 return N->subtype_end();
520 // PromoteAbstractToConcrete - This is a recursive function that walks a type
521 // graph calculating whether or not a type is abstract.
523 void Type::PromoteAbstractToConcrete() {
524 if (!isAbstract()) return;
526 scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
527 scc_iterator<TypePromotionGraph> SE = scc_end (TypePromotionGraph(this));
529 for (; SI != SE; ++SI) {
530 std::vector<Type*> &SCC = *SI;
532 // Concrete types are leaves in the tree. Since an SCC will either be all
533 // abstract or all concrete, we only need to check one type.
534 if (SCC[0]->isAbstract()) {
535 if (isa<OpaqueType>(SCC[0]))
536 return; // Not going to be concrete, sorry.
538 // If all of the children of all of the types in this SCC are concrete,
539 // then this SCC is now concrete as well. If not, neither this SCC, nor
540 // any parent SCCs will be concrete, so we might as well just exit.
541 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
542 for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
543 E = SCC[i]->subtype_end(); CI != E; ++CI)
544 if ((*CI)->isAbstract())
545 // If the child type is in our SCC, it doesn't make the entire SCC
546 // abstract unless there is a non-SCC abstract type.
547 if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
548 return; // Not going to be concrete, sorry.
550 // Okay, we just discovered this whole SCC is now concrete, mark it as
552 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
553 assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
555 SCC[i]->setAbstract(false);
558 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
559 assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
560 // The type just became concrete, notify all users!
561 cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
568 //===----------------------------------------------------------------------===//
569 // Type Structural Equality Testing
570 //===----------------------------------------------------------------------===//
572 // TypesEqual - Two types are considered structurally equal if they have the
573 // same "shape": Every level and element of the types have identical primitive
574 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
575 // be pointer equals to be equivalent though. This uses an optimistic algorithm
576 // that assumes that two graphs are the same until proven otherwise.
578 static bool TypesEqual(const Type *Ty, const Type *Ty2,
579 std::map<const Type *, const Type *> &EqTypes) {
580 if (Ty == Ty2) return true;
581 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
582 if (isa<OpaqueType>(Ty))
583 return false; // Two unequal opaque types are never equal
585 std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
586 if (It != EqTypes.end())
587 return It->second == Ty2; // Looping back on a type, check for equality
589 // Otherwise, add the mapping to the table to make sure we don't get
590 // recursion on the types...
591 EqTypes.insert(It, std::make_pair(Ty, Ty2));
593 // Two really annoying special cases that breaks an otherwise nice simple
594 // algorithm is the fact that arraytypes have sizes that differentiates types,
595 // and that function types can be varargs or not. Consider this now.
597 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
598 const IntegerType *ITy2 = cast<IntegerType>(Ty2);
599 return ITy->getBitWidth() == ITy2->getBitWidth();
600 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
601 const PointerType *PTy2 = cast<PointerType>(Ty2);
602 return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
603 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
604 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
605 const StructType *STy2 = cast<StructType>(Ty2);
606 if (STy->getNumElements() != STy2->getNumElements()) return false;
607 if (STy->isPacked() != STy2->isPacked()) return false;
608 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
609 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
612 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
613 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
614 return ATy->getNumElements() == ATy2->getNumElements() &&
615 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
616 } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
617 const VectorType *PTy2 = cast<VectorType>(Ty2);
618 return PTy->getNumElements() == PTy2->getNumElements() &&
619 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
620 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
621 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
622 if (FTy->isVarArg() != FTy2->isVarArg() ||
623 FTy->getNumParams() != FTy2->getNumParams() ||
624 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
626 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
627 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
632 assert(0 && "Unknown derived type!");
637 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
638 std::map<const Type *, const Type *> EqTypes;
639 return TypesEqual(Ty, Ty2, EqTypes);
642 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
643 // TargetTy in the type graph. We know that Ty is an abstract type, so if we
644 // ever reach a non-abstract type, we know that we don't need to search the
646 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
647 SmallPtrSet<const Type*, 128> &VisitedTypes) {
648 if (TargetTy == CurTy) return true;
649 if (!CurTy->isAbstract()) return false;
651 if (!VisitedTypes.insert(CurTy))
652 return false; // Already been here.
654 for (Type::subtype_iterator I = CurTy->subtype_begin(),
655 E = CurTy->subtype_end(); I != E; ++I)
656 if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
661 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
662 SmallPtrSet<const Type*, 128> &VisitedTypes) {
663 if (TargetTy == CurTy) return true;
665 if (!VisitedTypes.insert(CurTy))
666 return false; // Already been here.
668 for (Type::subtype_iterator I = CurTy->subtype_begin(),
669 E = CurTy->subtype_end(); I != E; ++I)
670 if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
675 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
677 static bool TypeHasCycleThroughItself(const Type *Ty) {
678 SmallPtrSet<const Type*, 128> VisitedTypes;
680 if (Ty->isAbstract()) { // Optimized case for abstract types.
681 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
683 if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
686 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
688 if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
694 /// getSubElementHash - Generate a hash value for all of the SubType's of this
695 /// type. The hash value is guaranteed to be zero if any of the subtypes are
696 /// an opaque type. Otherwise we try to mix them in as well as possible, but do
697 /// not look at the subtype's subtype's.
698 static unsigned getSubElementHash(const Type *Ty) {
699 unsigned HashVal = 0;
700 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
703 const Type *SubTy = I->get();
704 HashVal += SubTy->getTypeID();
705 switch (SubTy->getTypeID()) {
707 case Type::OpaqueTyID: return 0; // Opaque -> hash = 0 no matter what.
708 case Type::IntegerTyID:
709 HashVal ^= (cast<IntegerType>(SubTy)->getBitWidth() << 3);
711 case Type::FunctionTyID:
712 HashVal ^= cast<FunctionType>(SubTy)->getNumParams()*2 +
713 cast<FunctionType>(SubTy)->isVarArg();
715 case Type::ArrayTyID:
716 HashVal ^= cast<ArrayType>(SubTy)->getNumElements();
718 case Type::VectorTyID:
719 HashVal ^= cast<VectorType>(SubTy)->getNumElements();
721 case Type::StructTyID:
722 HashVal ^= cast<StructType>(SubTy)->getNumElements();
724 case Type::PointerTyID:
725 HashVal ^= cast<PointerType>(SubTy)->getAddressSpace();
729 return HashVal ? HashVal : 1; // Do not return zero unless opaque subty.
732 //===----------------------------------------------------------------------===//
733 // Derived Type Factory Functions
734 //===----------------------------------------------------------------------===//
739 /// TypesByHash - Keep track of types by their structure hash value. Note
740 /// that we only keep track of types that have cycles through themselves in
743 std::multimap<unsigned, PATypeHolder> TypesByHash;
747 // PATypeHolder won't destroy non-abstract types.
748 // We can't destroy them by simply iterating, because
749 // they may contain references to each-other.
751 for (std::multimap<unsigned, PATypeHolder>::iterator I
752 = TypesByHash.begin(), E = TypesByHash.end(); I != E; ++I) {
753 Type *Ty = const_cast<Type*>(I->second.Ty);
755 // We can't invoke destroy or delete, because the type may
756 // contain references to already freed types.
757 // So we have to destruct the object the ugly way.
759 Ty->AbstractTypeUsers.clear();
760 static_cast<const Type*>(Ty)->Type::~Type();
767 void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
768 std::multimap<unsigned, PATypeHolder>::iterator I =
769 TypesByHash.lower_bound(Hash);
770 for (; I != TypesByHash.end() && I->first == Hash; ++I) {
771 if (I->second == Ty) {
772 TypesByHash.erase(I);
777 // This must be do to an opaque type that was resolved. Switch down to hash
779 assert(Hash && "Didn't find type entry!");
780 RemoveFromTypesByHash(0, Ty);
783 /// TypeBecameConcrete - When Ty gets a notification that TheType just became
784 /// concrete, drop uses and make Ty non-abstract if we should.
785 void TypeBecameConcrete(DerivedType *Ty, const DerivedType *TheType) {
786 // If the element just became concrete, remove 'ty' from the abstract
787 // type user list for the type. Do this for as many times as Ty uses
789 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
791 if (I->get() == TheType)
792 TheType->removeAbstractTypeUser(Ty);
794 // If the type is currently thought to be abstract, rescan all of our
795 // subtypes to see if the type has just become concrete! Note that this
796 // may send out notifications to AbstractTypeUsers that types become
798 if (Ty->isAbstract())
799 Ty->PromoteAbstractToConcrete();
805 // TypeMap - Make sure that only one instance of a particular type may be
806 // created on any given run of the compiler... note that this involves updating
807 // our map if an abstract type gets refined somehow.
810 template<class ValType, class TypeClass>
811 class TypeMap : public TypeMapBase {
812 std::map<ValType, PATypeHolder> Map;
814 typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
815 ~TypeMap() { print("ON EXIT"); }
817 inline TypeClass *get(const ValType &V) {
818 iterator I = Map.find(V);
819 return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
822 inline void add(const ValType &V, TypeClass *Ty) {
823 Map.insert(std::make_pair(V, Ty));
825 // If this type has a cycle, remember it.
826 TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
830 /// RefineAbstractType - This method is called after we have merged a type
831 /// with another one. We must now either merge the type away with
832 /// some other type or reinstall it in the map with it's new configuration.
833 void RefineAbstractType(TypeClass *Ty, const DerivedType *OldType,
834 const Type *NewType) {
835 #ifdef DEBUG_MERGE_TYPES
836 DOUT << "RefineAbstractType(" << (void*)OldType << "[" << *OldType
837 << "], " << (void*)NewType << " [" << *NewType << "])\n";
840 // Otherwise, we are changing one subelement type into another. Clearly the
841 // OldType must have been abstract, making us abstract.
842 assert(Ty->isAbstract() && "Refining a non-abstract type!");
843 assert(OldType != NewType);
845 // Make a temporary type holder for the type so that it doesn't disappear on
846 // us when we erase the entry from the map.
847 PATypeHolder TyHolder = Ty;
849 // The old record is now out-of-date, because one of the children has been
850 // updated. Remove the obsolete entry from the map.
851 unsigned NumErased = Map.erase(ValType::get(Ty));
852 assert(NumErased && "Element not found!"); NumErased = NumErased;
854 // Remember the structural hash for the type before we start hacking on it,
855 // in case we need it later.
856 unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
858 // Find the type element we are refining... and change it now!
859 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i)
860 if (Ty->ContainedTys[i] == OldType)
861 Ty->ContainedTys[i] = NewType;
862 unsigned NewTypeHash = ValType::hashTypeStructure(Ty);
864 // If there are no cycles going through this node, we can do a simple,
865 // efficient lookup in the map, instead of an inefficient nasty linear
867 if (!TypeHasCycleThroughItself(Ty)) {
868 typename std::map<ValType, PATypeHolder>::iterator I;
871 tie(I, Inserted) = Map.insert(std::make_pair(ValType::get(Ty), Ty));
873 // Refined to a different type altogether?
874 RemoveFromTypesByHash(OldTypeHash, Ty);
876 // We already have this type in the table. Get rid of the newly refined
878 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
879 Ty->unlockedRefineAbstractTypeTo(NewTy);
883 // Now we check to see if there is an existing entry in the table which is
884 // structurally identical to the newly refined type. If so, this type
885 // gets refined to the pre-existing type.
887 std::multimap<unsigned, PATypeHolder>::iterator I, E, Entry;
888 tie(I, E) = TypesByHash.equal_range(NewTypeHash);
890 for (; I != E; ++I) {
891 if (I->second == Ty) {
892 // Remember the position of the old type if we see it in our scan.
895 if (TypesEqual(Ty, I->second)) {
896 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
898 // Remove the old entry form TypesByHash. If the hash values differ
899 // now, remove it from the old place. Otherwise, continue scanning
900 // withing this hashcode to reduce work.
901 if (NewTypeHash != OldTypeHash) {
902 RemoveFromTypesByHash(OldTypeHash, Ty);
905 // Find the location of Ty in the TypesByHash structure if we
906 // haven't seen it already.
907 while (I->second != Ty) {
909 assert(I != E && "Structure doesn't contain type??");
913 TypesByHash.erase(Entry);
915 Ty->unlockedRefineAbstractTypeTo(NewTy);
921 // If there is no existing type of the same structure, we reinsert an
922 // updated record into the map.
923 Map.insert(std::make_pair(ValType::get(Ty), Ty));
926 // If the hash codes differ, update TypesByHash
927 if (NewTypeHash != OldTypeHash) {
928 RemoveFromTypesByHash(OldTypeHash, Ty);
929 TypesByHash.insert(std::make_pair(NewTypeHash, Ty));
932 // If the type is currently thought to be abstract, rescan all of our
933 // subtypes to see if the type has just become concrete! Note that this
934 // may send out notifications to AbstractTypeUsers that types become
936 if (Ty->isAbstract())
937 Ty->PromoteAbstractToConcrete();
940 void print(const char *Arg) const {
941 #ifdef DEBUG_MERGE_TYPES
942 DOUT << "TypeMap<>::" << Arg << " table contents:\n";
944 for (typename std::map<ValType, PATypeHolder>::const_iterator I
945 = Map.begin(), E = Map.end(); I != E; ++I)
946 DOUT << " " << (++i) << ". " << (void*)I->second.get() << " "
947 << *I->second.get() << "\n";
951 void dump() const { print("dump output"); }
956 //===----------------------------------------------------------------------===//
957 // Function Type Factory and Value Class...
960 //===----------------------------------------------------------------------===//
961 // Integer Type Factory...
964 class IntegerValType {
967 IntegerValType(uint16_t numbits) : bits(numbits) {}
969 static IntegerValType get(const IntegerType *Ty) {
970 return IntegerValType(Ty->getBitWidth());
973 static unsigned hashTypeStructure(const IntegerType *Ty) {
974 return (unsigned)Ty->getBitWidth();
977 inline bool operator<(const IntegerValType &IVT) const {
978 return bits < IVT.bits;
983 static ManagedStatic<TypeMap<IntegerValType, IntegerType> > IntegerTypes;
985 const IntegerType *IntegerType::get(unsigned NumBits) {
986 assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
987 assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
989 // Check for the built-in integer types
991 case 1: return cast<IntegerType>(Type::Int1Ty);
992 case 8: return cast<IntegerType>(Type::Int8Ty);
993 case 16: return cast<IntegerType>(Type::Int16Ty);
994 case 32: return cast<IntegerType>(Type::Int32Ty);
995 case 64: return cast<IntegerType>(Type::Int64Ty);
1000 IntegerValType IVT(NumBits);
1001 IntegerType *ITy = 0;
1002 if (llvm_is_multithreaded()) {
1003 // First, see if the type is already in the table, for which
1004 // a reader lock suffices.
1005 TypeMapLock->reader_acquire();
1006 ITy = IntegerTypes->get(IVT);
1007 TypeMapLock->reader_release();
1010 // OK, not in the table, get a writer lock.
1011 TypeMapLock->writer_acquire();
1012 ITy = IntegerTypes->get(IVT);
1014 // We need to _recheck_ the table in case someone
1015 // put it in between when we released the reader lock
1016 // and when we gained the writer lock!
1018 // Value not found. Derive a new type!
1019 ITy = new IntegerType(NumBits);
1020 IntegerTypes->add(IVT, ITy);
1023 TypeMapLock->writer_release();
1026 ITy = IntegerTypes->get(IVT);
1027 if (ITy) return ITy; // Found a match, return it!
1029 // Value not found. Derive a new type!
1030 ITy = new IntegerType(NumBits);
1031 IntegerTypes->add(IVT, ITy);
1033 #ifdef DEBUG_MERGE_TYPES
1034 DOUT << "Derived new type: " << *ITy << "\n";
1039 bool IntegerType::isPowerOf2ByteWidth() const {
1040 unsigned BitWidth = getBitWidth();
1041 return (BitWidth > 7) && isPowerOf2_32(BitWidth);
1044 APInt IntegerType::getMask() const {
1045 return APInt::getAllOnesValue(getBitWidth());
1048 // FunctionValType - Define a class to hold the key that goes into the TypeMap
1051 class FunctionValType {
1053 std::vector<const Type*> ArgTypes;
1056 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
1057 bool isVA) : RetTy(ret), ArgTypes(args), isVarArg(isVA) {}
1059 static FunctionValType get(const FunctionType *FT);
1061 static unsigned hashTypeStructure(const FunctionType *FT) {
1062 unsigned Result = FT->getNumParams()*2 + FT->isVarArg();
1066 inline bool operator<(const FunctionValType &MTV) const {
1067 if (RetTy < MTV.RetTy) return true;
1068 if (RetTy > MTV.RetTy) return false;
1069 if (isVarArg < MTV.isVarArg) return true;
1070 if (isVarArg > MTV.isVarArg) return false;
1071 if (ArgTypes < MTV.ArgTypes) return true;
1072 if (ArgTypes > MTV.ArgTypes) return false;
1078 // Define the actual map itself now...
1079 static ManagedStatic<TypeMap<FunctionValType, FunctionType> > FunctionTypes;
1081 FunctionValType FunctionValType::get(const FunctionType *FT) {
1082 // Build up a FunctionValType
1083 std::vector<const Type *> ParamTypes;
1084 ParamTypes.reserve(FT->getNumParams());
1085 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1086 ParamTypes.push_back(FT->getParamType(i));
1087 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
1091 // FunctionType::get - The factory function for the FunctionType class...
1092 FunctionType *FunctionType::get(const Type *ReturnType,
1093 const std::vector<const Type*> &Params,
1095 FunctionValType VT(ReturnType, Params, isVarArg);
1096 FunctionType *FT = 0;
1098 if (llvm_is_multithreaded()) {
1099 TypeMapLock->reader_acquire();
1100 FT = FunctionTypes->get(VT);
1101 TypeMapLock->reader_release();
1104 TypeMapLock->writer_acquire();
1106 // Have to check again here, because it might have
1107 // been inserted between when we release the reader
1108 // lock and when we acquired the writer lock.
1109 FT = FunctionTypes->get(VT);
1111 FT = (FunctionType*) operator new(sizeof(FunctionType) +
1112 sizeof(PATypeHandle)*(Params.size()+1));
1113 new (FT) FunctionType(ReturnType, Params, isVarArg);
1114 FunctionTypes->add(VT, FT);
1116 TypeMapLock->writer_release();
1119 FT = FunctionTypes->get(VT);
1123 FT = (FunctionType*) operator new(sizeof(FunctionType) +
1124 sizeof(PATypeHandle)*(Params.size()+1));
1125 new (FT) FunctionType(ReturnType, Params, isVarArg);
1126 FunctionTypes->add(VT, FT);
1129 #ifdef DEBUG_MERGE_TYPES
1130 DOUT << "Derived new type: " << FT << "\n";
1135 //===----------------------------------------------------------------------===//
1136 // Array Type Factory...
1139 class ArrayValType {
1143 ArrayValType(const Type *val, uint64_t sz) : ValTy(val), Size(sz) {}
1145 static ArrayValType get(const ArrayType *AT) {
1146 return ArrayValType(AT->getElementType(), AT->getNumElements());
1149 static unsigned hashTypeStructure(const ArrayType *AT) {
1150 return (unsigned)AT->getNumElements();
1153 inline bool operator<(const ArrayValType &MTV) const {
1154 if (Size < MTV.Size) return true;
1155 return Size == MTV.Size && ValTy < MTV.ValTy;
1160 static ManagedStatic<TypeMap<ArrayValType, ArrayType> > ArrayTypes;
1162 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
1163 assert(ElementType && "Can't get array of <null> types!");
1164 assert(isValidElementType(ElementType) && "Invalid type for array element!");
1166 ArrayValType AVT(ElementType, NumElements);
1169 if (llvm_is_multithreaded()) {
1170 TypeMapLock->reader_acquire();
1171 AT = ArrayTypes->get(AVT);
1172 TypeMapLock->reader_release();
1175 TypeMapLock->writer_acquire();
1177 // Recheck. Might have changed between release and acquire.
1178 AT = ArrayTypes->get(AVT);
1180 // Value not found. Derive a new type!
1181 ArrayTypes->add(AVT, AT = new ArrayType(ElementType, NumElements));
1183 TypeMapLock->writer_release();
1186 AT = ArrayTypes->get(AVT);
1187 if (AT) return AT; // Found a match, return it!
1189 // Value not found. Derive a new type!
1190 ArrayTypes->add(AVT, AT = new ArrayType(ElementType, NumElements));
1192 #ifdef DEBUG_MERGE_TYPES
1193 DOUT << "Derived new type: " << *AT << "\n";
1198 bool ArrayType::isValidElementType(const Type *ElemTy) {
1199 if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy ||
1200 ElemTy == Type::MetadataTy)
1203 if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
1204 if (PTy->getElementType() == Type::MetadataTy)
1211 //===----------------------------------------------------------------------===//
1212 // Vector Type Factory...
1215 class VectorValType {
1219 VectorValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
1221 static VectorValType get(const VectorType *PT) {
1222 return VectorValType(PT->getElementType(), PT->getNumElements());
1225 static unsigned hashTypeStructure(const VectorType *PT) {
1226 return PT->getNumElements();
1229 inline bool operator<(const VectorValType &MTV) const {
1230 if (Size < MTV.Size) return true;
1231 return Size == MTV.Size && ValTy < MTV.ValTy;
1236 static ManagedStatic<TypeMap<VectorValType, VectorType> > VectorTypes;
1238 VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) {
1239 assert(ElementType && "Can't get vector of <null> types!");
1241 VectorValType PVT(ElementType, NumElements);
1244 if (llvm_is_multithreaded()) {
1245 TypeMapLock->reader_acquire();
1246 PT = VectorTypes->get(PVT);
1247 TypeMapLock->reader_release();
1250 TypeMapLock->writer_acquire();
1251 PT = VectorTypes->get(PVT);
1252 // Recheck. Might have changed between release and acquire.
1254 VectorTypes->add(PVT, PT = new VectorType(ElementType, NumElements));
1256 TypeMapLock->writer_acquire();
1259 PT = VectorTypes->get(PVT);
1260 if (PT) return PT; // Found a match, return it!
1262 // Value not found. Derive a new type!
1263 VectorTypes->add(PVT, PT = new VectorType(ElementType, NumElements));
1265 #ifdef DEBUG_MERGE_TYPES
1266 DOUT << "Derived new type: " << *PT << "\n";
1271 bool VectorType::isValidElementType(const Type *ElemTy) {
1272 if (ElemTy->isInteger() || ElemTy->isFloatingPoint() ||
1273 isa<OpaqueType>(ElemTy))
1279 //===----------------------------------------------------------------------===//
1280 // Struct Type Factory...
1284 // StructValType - Define a class to hold the key that goes into the TypeMap
1286 class StructValType {
1287 std::vector<const Type*> ElTypes;
1290 StructValType(const std::vector<const Type*> &args, bool isPacked)
1291 : ElTypes(args), packed(isPacked) {}
1293 static StructValType get(const StructType *ST) {
1294 std::vector<const Type *> ElTypes;
1295 ElTypes.reserve(ST->getNumElements());
1296 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
1297 ElTypes.push_back(ST->getElementType(i));
1299 return StructValType(ElTypes, ST->isPacked());
1302 static unsigned hashTypeStructure(const StructType *ST) {
1303 return ST->getNumElements();
1306 inline bool operator<(const StructValType &STV) const {
1307 if (ElTypes < STV.ElTypes) return true;
1308 else if (ElTypes > STV.ElTypes) return false;
1309 else return (int)packed < (int)STV.packed;
1314 static ManagedStatic<TypeMap<StructValType, StructType> > StructTypes;
1316 StructType *StructType::get(const std::vector<const Type*> &ETypes,
1318 StructValType STV(ETypes, isPacked);
1321 if (llvm_is_multithreaded()) {
1322 TypeMapLock->reader_acquire();
1323 ST = StructTypes->get(STV);
1324 TypeMapLock->reader_release();
1327 TypeMapLock->writer_acquire();
1328 ST = StructTypes->get(STV);
1329 // Recheck. Might have changed between release and acquire.
1331 // Value not found. Derive a new type!
1332 ST = (StructType*) operator new(sizeof(StructType) +
1333 sizeof(PATypeHandle) * ETypes.size());
1334 new (ST) StructType(ETypes, isPacked);
1335 StructTypes->add(STV, ST);
1337 TypeMapLock->writer_release();
1340 ST = StructTypes->get(STV);
1343 // Value not found. Derive a new type!
1344 ST = (StructType*) operator new(sizeof(StructType) +
1345 sizeof(PATypeHandle) * ETypes.size());
1346 new (ST) StructType(ETypes, isPacked);
1347 StructTypes->add(STV, ST);
1349 #ifdef DEBUG_MERGE_TYPES
1350 DOUT << "Derived new type: " << *ST << "\n";
1355 StructType *StructType::get(const Type *type, ...) {
1357 std::vector<const llvm::Type*> StructFields;
1360 StructFields.push_back(type);
1361 type = va_arg(ap, llvm::Type*);
1363 return llvm::StructType::get(StructFields);
1366 bool StructType::isValidElementType(const Type *ElemTy) {
1367 if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy ||
1368 ElemTy == Type::MetadataTy)
1371 if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
1372 if (PTy->getElementType() == Type::MetadataTy)
1379 //===----------------------------------------------------------------------===//
1380 // Pointer Type Factory...
1383 // PointerValType - Define a class to hold the key that goes into the TypeMap
1386 class PointerValType {
1388 unsigned AddressSpace;
1390 PointerValType(const Type *val, unsigned as) : ValTy(val), AddressSpace(as) {}
1392 static PointerValType get(const PointerType *PT) {
1393 return PointerValType(PT->getElementType(), PT->getAddressSpace());
1396 static unsigned hashTypeStructure(const PointerType *PT) {
1397 return getSubElementHash(PT);
1400 bool operator<(const PointerValType &MTV) const {
1401 if (AddressSpace < MTV.AddressSpace) return true;
1402 return AddressSpace == MTV.AddressSpace && ValTy < MTV.ValTy;
1407 static ManagedStatic<TypeMap<PointerValType, PointerType> > PointerTypes;
1409 PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) {
1410 assert(ValueType && "Can't get a pointer to <null> type!");
1411 assert(ValueType != Type::VoidTy &&
1412 "Pointer to void is not valid, use i8* instead!");
1413 assert(isValidElementType(ValueType) && "Invalid type for pointer element!");
1414 PointerValType PVT(ValueType, AddressSpace);
1416 PointerType *PT = 0;
1418 if (llvm_is_multithreaded()) {
1419 TypeMapLock->reader_acquire();
1420 PT = PointerTypes->get(PVT);
1421 TypeMapLock->reader_release();
1424 TypeMapLock->writer_acquire();
1425 PT = PointerTypes->get(PVT);
1426 // Recheck. Might have changed between release and acquire.
1428 // Value not found. Derive a new type!
1429 PointerTypes->add(PVT, PT = new PointerType(ValueType, AddressSpace));
1431 TypeMapLock->writer_release();
1434 PT = PointerTypes->get(PVT);
1437 // Value not found. Derive a new type!
1438 PointerTypes->add(PVT, PT = new PointerType(ValueType, AddressSpace));
1440 #ifdef DEBUG_MERGE_TYPES
1441 DOUT << "Derived new type: " << *PT << "\n";
1446 PointerType *Type::getPointerTo(unsigned addrs) const {
1447 return PointerType::get(this, addrs);
1450 bool PointerType::isValidElementType(const Type *ElemTy) {
1451 if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy)
1454 if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
1455 if (PTy->getElementType() == Type::MetadataTy)
1462 //===----------------------------------------------------------------------===//
1463 // Derived Type Refinement Functions
1464 //===----------------------------------------------------------------------===//
1466 // addAbstractTypeUser - Notify an abstract type that there is a new user of
1467 // it. This function is called primarily by the PATypeHandle class.
1468 void Type::addAbstractTypeUser(AbstractTypeUser *U) const {
1469 assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
1470 if (llvm_is_multithreaded()) {
1471 AbstractTypeUsersLock->acquire();
1472 AbstractTypeUsers.push_back(U);
1473 AbstractTypeUsersLock->release();
1475 AbstractTypeUsers.push_back(U);
1480 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1481 // no longer has a handle to the type. This function is called primarily by
1482 // the PATypeHandle class. When there are no users of the abstract type, it
1483 // is annihilated, because there is no way to get a reference to it ever again.
1485 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
1486 if (llvm_is_multithreaded()) AbstractTypeUsersLock->acquire();
1488 // Search from back to front because we will notify users from back to
1489 // front. Also, it is likely that there will be a stack like behavior to
1490 // users that register and unregister users.
1493 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1494 assert(i != 0 && "AbstractTypeUser not in user list!");
1496 --i; // Convert to be in range 0 <= i < size()
1497 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1499 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1501 #ifdef DEBUG_MERGE_TYPES
1502 DOUT << " remAbstractTypeUser[" << (void*)this << ", "
1503 << *this << "][" << i << "] User = " << U << "\n";
1506 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1507 #ifdef DEBUG_MERGE_TYPES
1508 DOUT << "DELETEing unused abstract type: <" << *this
1509 << ">[" << (void*)this << "]" << "\n";
1515 if (llvm_is_multithreaded()) AbstractTypeUsersLock->release();
1518 // unlockedRefineAbstractTypeTo - This function is used when it is discovered
1519 // that the 'this' abstract type is actually equivalent to the NewType
1520 // specified. This causes all users of 'this' to switch to reference the more
1521 // concrete type NewType and for 'this' to be deleted. Only used for internal
1524 void DerivedType::unlockedRefineAbstractTypeTo(const Type *NewType) {
1525 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1526 assert(this != NewType && "Can't refine to myself!");
1527 assert(ForwardType == 0 && "This type has already been refined!");
1529 // The descriptions may be out of date. Conservatively clear them all!
1530 if (AbstractTypeDescriptions.isConstructed())
1531 AbstractTypeDescriptions->clear();
1533 #ifdef DEBUG_MERGE_TYPES
1534 DOUT << "REFINING abstract type [" << (void*)this << " "
1535 << *this << "] to [" << (void*)NewType << " "
1536 << *NewType << "]!\n";
1539 // Make sure to put the type to be refined to into a holder so that if IT gets
1540 // refined, that we will not continue using a dead reference...
1542 PATypeHolder NewTy(NewType);
1543 // Any PATypeHolders referring to this type will now automatically forward o
1544 // the type we are resolved to.
1545 ForwardType = NewType;
1546 if (NewType->isAbstract())
1547 cast<DerivedType>(NewType)->addRef();
1549 // Add a self use of the current type so that we don't delete ourself until
1550 // after the function exits.
1552 PATypeHolder CurrentTy(this);
1554 // To make the situation simpler, we ask the subclass to remove this type from
1555 // the type map, and to replace any type uses with uses of non-abstract types.
1556 // This dramatically limits the amount of recursive type trouble we can find
1560 // Iterate over all of the uses of this type, invoking callback. Each user
1561 // should remove itself from our use list automatically. We have to check to
1562 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1563 // will not cause users to drop off of the use list. If we resolve to ourself
1566 if (llvm_is_multithreaded()) AbstractTypeUsersLock->acquire();
1567 while (!AbstractTypeUsers.empty() && NewTy != this) {
1568 AbstractTypeUser *User = AbstractTypeUsers.back();
1570 unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1571 #ifdef DEBUG_MERGE_TYPES
1572 DOUT << " REFINING user " << OldSize-1 << "[" << (void*)User
1573 << "] of abstract type [" << (void*)this << " "
1574 << *this << "] to [" << (void*)NewTy.get() << " "
1575 << *NewTy << "]!\n";
1577 User->refineAbstractType(this, NewTy);
1579 assert(AbstractTypeUsers.size() != OldSize &&
1580 "AbsTyUser did not remove self from user list!");
1582 if (llvm_is_multithreaded()) AbstractTypeUsersLock->release();
1584 // If we were successful removing all users from the type, 'this' will be
1585 // deleted when the last PATypeHolder is destroyed or updated from this type.
1586 // This may occur on exit of this function, as the CurrentTy object is
1590 // refineAbstractTypeTo - This function is used by external callers to notify
1591 // us that this abstract type is equivalent to another type.
1593 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1594 if (llvm_is_multithreaded()) {
1595 // All recursive calls will go through unlockedRefineAbstractTypeTo,
1596 // to avoid deadlock problems.
1597 TypeMapLock->writer_acquire();
1598 unlockedRefineAbstractTypeTo(NewType);
1599 TypeMapLock->writer_release();
1601 unlockedRefineAbstractTypeTo(NewType);
1605 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1606 // the current type has transitioned from being abstract to being concrete.
1608 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1609 #ifdef DEBUG_MERGE_TYPES
1610 DOUT << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1613 if (llvm_is_multithreaded()) AbstractTypeUsersLock->acquire();
1614 unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1615 while (!AbstractTypeUsers.empty()) {
1616 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1617 ATU->typeBecameConcrete(this);
1619 assert(AbstractTypeUsers.size() < OldSize-- &&
1620 "AbstractTypeUser did not remove itself from the use list!");
1622 if (llvm_is_multithreaded()) AbstractTypeUsersLock->release();
1625 // refineAbstractType - Called when a contained type is found to be more
1626 // concrete - this could potentially change us from an abstract type to a
1629 void FunctionType::refineAbstractType(const DerivedType *OldType,
1630 const Type *NewType) {
1631 FunctionTypes->RefineAbstractType(this, OldType, NewType);
1634 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1635 FunctionTypes->TypeBecameConcrete(this, AbsTy);
1639 // refineAbstractType - Called when a contained type is found to be more
1640 // concrete - this could potentially change us from an abstract type to a
1643 void ArrayType::refineAbstractType(const DerivedType *OldType,
1644 const Type *NewType) {
1645 ArrayTypes->RefineAbstractType(this, OldType, NewType);
1648 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1649 ArrayTypes->TypeBecameConcrete(this, AbsTy);
1652 // refineAbstractType - Called when a contained type is found to be more
1653 // concrete - this could potentially change us from an abstract type to a
1656 void VectorType::refineAbstractType(const DerivedType *OldType,
1657 const Type *NewType) {
1658 VectorTypes->RefineAbstractType(this, OldType, NewType);
1661 void VectorType::typeBecameConcrete(const DerivedType *AbsTy) {
1662 VectorTypes->TypeBecameConcrete(this, AbsTy);
1665 // refineAbstractType - Called when a contained type is found to be more
1666 // concrete - this could potentially change us from an abstract type to a
1669 void StructType::refineAbstractType(const DerivedType *OldType,
1670 const Type *NewType) {
1671 StructTypes->RefineAbstractType(this, OldType, NewType);
1674 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1675 StructTypes->TypeBecameConcrete(this, AbsTy);
1678 // refineAbstractType - Called when a contained type is found to be more
1679 // concrete - this could potentially change us from an abstract type to a
1682 void PointerType::refineAbstractType(const DerivedType *OldType,
1683 const Type *NewType) {
1684 PointerTypes->RefineAbstractType(this, OldType, NewType);
1687 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1688 PointerTypes->TypeBecameConcrete(this, AbsTy);
1691 bool SequentialType::indexValid(const Value *V) const {
1692 if (isa<IntegerType>(V->getType()))
1698 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1700 OS << "<null> value!\n";
1706 std::ostream &operator<<(std::ostream &OS, const Type &T) {
1711 raw_ostream &operator<<(raw_ostream &OS, const Type &T) {