LLVM API Documentation
00001 //===-- Type.cpp - Implement the Type class -------------------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements the Type class for the VMCore library. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "llvm/DerivedTypes.h" 00015 #include "llvm/Constants.h" 00016 #include "llvm/ADT/DepthFirstIterator.h" 00017 #include "llvm/ADT/StringExtras.h" 00018 #include "llvm/ADT/SCCIterator.h" 00019 #include "llvm/ADT/STLExtras.h" 00020 #include "llvm/Support/MathExtras.h" 00021 #include "llvm/Support/Compiler.h" 00022 #include "llvm/Support/ManagedStatic.h" 00023 #include "llvm/Support/Debug.h" 00024 #include <algorithm> 00025 #include <cstdarg> 00026 using namespace llvm; 00027 00028 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are 00029 // created and later destroyed, all in an effort to make sure that there is only 00030 // a single canonical version of a type. 00031 // 00032 // #define DEBUG_MERGE_TYPES 1 00033 00034 AbstractTypeUser::~AbstractTypeUser() {} 00035 00036 00037 //===----------------------------------------------------------------------===// 00038 // Type Class Implementation 00039 //===----------------------------------------------------------------------===// 00040 00041 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions 00042 // for types as they are needed. Because resolution of types must invalidate 00043 // all of the abstract type descriptions, we keep them in a seperate map to make 00044 // this easy. 00045 static ManagedStatic<std::map<const Type*, 00046 std::string> > ConcreteTypeDescriptions; 00047 static ManagedStatic<std::map<const Type*, 00048 std::string> > AbstractTypeDescriptions; 00049 00050 /// Because of the way Type subclasses are allocated, this function is necessary 00051 /// to use the correct kind of "delete" operator to deallocate the Type object. 00052 /// Some type objects (FunctionTy, StructTy) allocate additional space after 00053 /// the space for their derived type to hold the contained types array of 00054 /// PATypeHandles. Using this allocation scheme means all the PATypeHandles are 00055 /// allocated with the type object, decreasing allocations and eliminating the 00056 /// need for a std::vector to be used in the Type class itself. 00057 /// @brief Type destruction function 00058 void Type::destroy() const { 00059 00060 // Structures and Functions allocate their contained types past the end of 00061 // the type object itself. These need to be destroyed differently than the 00062 // other types. 00063 if (isa<FunctionType>(this) || isa<StructType>(this)) { 00064 // First, make sure we destruct any PATypeHandles allocated by these 00065 // subclasses. They must be manually destructed. 00066 for (unsigned i = 0; i < NumContainedTys; ++i) 00067 ContainedTys[i].PATypeHandle::~PATypeHandle(); 00068 00069 // Now call the destructor for the subclass directly because we're going 00070 // to delete this as an array of char. 00071 if (isa<FunctionType>(this)) 00072 static_cast<const FunctionType*>(this)->FunctionType::~FunctionType(); 00073 else 00074 static_cast<const StructType*>(this)->StructType::~StructType(); 00075 00076 // Finally, remove the memory as an array deallocation of the chars it was 00077 // constructed from. 00078 operator delete(const_cast<Type *>(this)); 00079 00080 return; 00081 } 00082 00083 // For all the other type subclasses, there is either no contained types or 00084 // just one (all Sequentials). For Sequentials, the PATypeHandle is not 00085 // allocated past the type object, its included directly in the SequentialType 00086 // class. This means we can safely just do "normal" delete of this object and 00087 // all the destructors that need to run will be run. 00088 delete this; 00089 } 00090 00091 const Type *Type::getPrimitiveType(TypeID IDNumber) { 00092 switch (IDNumber) { 00093 case VoidTyID : return VoidTy; 00094 case FloatTyID : return FloatTy; 00095 case DoubleTyID : return DoubleTy; 00096 case X86_FP80TyID : return X86_FP80Ty; 00097 case FP128TyID : return FP128Ty; 00098 case PPC_FP128TyID : return PPC_FP128Ty; 00099 case LabelTyID : return LabelTy; 00100 default: 00101 return 0; 00102 } 00103 } 00104 00105 const Type *Type::getVAArgsPromotedType() const { 00106 if (ID == IntegerTyID && getSubclassData() < 32) 00107 return Type::Int32Ty; 00108 else if (ID == FloatTyID) 00109 return Type::DoubleTy; 00110 else 00111 return this; 00112 } 00113 00114 /// isIntOrIntVector - Return true if this is an integer type or a vector of 00115 /// integer types. 00116 /// 00117 bool Type::isIntOrIntVector() const { 00118 if (isInteger()) 00119 return true; 00120 if (ID != Type::VectorTyID) return false; 00121 00122 return cast<VectorType>(this)->getElementType()->isInteger(); 00123 } 00124 00125 /// isFPOrFPVector - Return true if this is a FP type or a vector of FP types. 00126 /// 00127 bool Type::isFPOrFPVector() const { 00128 if (ID == Type::FloatTyID || ID == Type::DoubleTyID || 00129 ID == Type::FP128TyID || ID == Type::X86_FP80TyID || 00130 ID == Type::PPC_FP128TyID) 00131 return true; 00132 if (ID != Type::VectorTyID) return false; 00133 00134 return cast<VectorType>(this)->getElementType()->isFloatingPoint(); 00135 } 00136 00137 // canLosslesllyBitCastTo - Return true if this type can be converted to 00138 // 'Ty' without any reinterpretation of bits. For example, uint to int. 00139 // 00140 bool Type::canLosslesslyBitCastTo(const Type *Ty) const { 00141 // Identity cast means no change so return true 00142 if (this == Ty) 00143 return true; 00144 00145 // They are not convertible unless they are at least first class types 00146 if (!this->isFirstClassType() || !Ty->isFirstClassType()) 00147 return false; 00148 00149 // Vector -> Vector conversions are always lossless if the two vector types 00150 // have the same size, otherwise not. 00151 if (const VectorType *thisPTy = dyn_cast<VectorType>(this)) 00152 if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty)) 00153 return thisPTy->getBitWidth() == thatPTy->getBitWidth(); 00154 00155 // At this point we have only various mismatches of the first class types 00156 // remaining and ptr->ptr. Just select the lossless conversions. Everything 00157 // else is not lossless. 00158 if (isa<PointerType>(this)) 00159 return isa<PointerType>(Ty); 00160 return false; // Other types have no identity values 00161 } 00162 00163 unsigned Type::getPrimitiveSizeInBits() const { 00164 switch (getTypeID()) { 00165 case Type::FloatTyID: return 32; 00166 case Type::DoubleTyID: return 64; 00167 case Type::X86_FP80TyID: return 80; 00168 case Type::FP128TyID: return 128; 00169 case Type::PPC_FP128TyID: return 128; 00170 case Type::IntegerTyID: return cast<IntegerType>(this)->getBitWidth(); 00171 case Type::VectorTyID: return cast<VectorType>(this)->getBitWidth(); 00172 default: return 0; 00173 } 00174 } 00175 00176 /// isSizedDerivedType - Derived types like structures and arrays are sized 00177 /// iff all of the members of the type are sized as well. Since asking for 00178 /// their size is relatively uncommon, move this operation out of line. 00179 bool Type::isSizedDerivedType() const { 00180 if (isa<IntegerType>(this)) 00181 return true; 00182 00183 if (const ArrayType *ATy = dyn_cast<ArrayType>(this)) 00184 return ATy->getElementType()->isSized(); 00185 00186 if (const VectorType *PTy = dyn_cast<VectorType>(this)) 00187 return PTy->getElementType()->isSized(); 00188 00189 if (!isa<StructType>(this)) 00190 return false; 00191 00192 // Okay, our struct is sized if all of the elements are... 00193 for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I) 00194 if (!(*I)->isSized()) 00195 return false; 00196 00197 return true; 00198 } 00199 00200 /// getForwardedTypeInternal - This method is used to implement the union-find 00201 /// algorithm for when a type is being forwarded to another type. 00202 const Type *Type::getForwardedTypeInternal() const { 00203 assert(ForwardType && "This type is not being forwarded to another type!"); 00204 00205 // Check to see if the forwarded type has been forwarded on. If so, collapse 00206 // the forwarding links. 00207 const Type *RealForwardedType = ForwardType->getForwardedType(); 00208 if (!RealForwardedType) 00209 return ForwardType; // No it's not forwarded again 00210 00211 // Yes, it is forwarded again. First thing, add the reference to the new 00212 // forward type. 00213 if (RealForwardedType->isAbstract()) 00214 cast<DerivedType>(RealForwardedType)->addRef(); 00215 00216 // Now drop the old reference. This could cause ForwardType to get deleted. 00217 cast<DerivedType>(ForwardType)->dropRef(); 00218 00219 // Return the updated type. 00220 ForwardType = RealForwardedType; 00221 return ForwardType; 00222 } 00223 00224 void Type::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) { 00225 abort(); 00226 } 00227 void Type::typeBecameConcrete(const DerivedType *AbsTy) { 00228 abort(); 00229 } 00230 00231 00232 // getTypeDescription - This is a recursive function that walks a type hierarchy 00233 // calculating the description for a type. 00234 // 00235 static std::string getTypeDescription(const Type *Ty, 00236 std::vector<const Type *> &TypeStack) { 00237 if (isa<OpaqueType>(Ty)) { // Base case for the recursion 00238 std::map<const Type*, std::string>::iterator I = 00239 AbstractTypeDescriptions->find(Ty); 00240 if (I != AbstractTypeDescriptions->end()) 00241 return I->second; 00242 std::string Desc = "opaque"; 00243 AbstractTypeDescriptions->insert(std::make_pair(Ty, Desc)); 00244 return Desc; 00245 } 00246 00247 if (!Ty->isAbstract()) { // Base case for the recursion 00248 std::map<const Type*, std::string>::iterator I = 00249 ConcreteTypeDescriptions->find(Ty); 00250 if (I != ConcreteTypeDescriptions->end()) 00251 return I->second; 00252 00253 if (Ty->isPrimitiveType()) { 00254 switch (Ty->getTypeID()) { 00255 default: assert(0 && "Unknown prim type!"); 00256 case Type::VoidTyID: return (*ConcreteTypeDescriptions)[Ty] = "void"; 00257 case Type::FloatTyID: return (*ConcreteTypeDescriptions)[Ty] = "float"; 00258 case Type::DoubleTyID: return (*ConcreteTypeDescriptions)[Ty] = "double"; 00259 case Type::X86_FP80TyID: 00260 return (*ConcreteTypeDescriptions)[Ty] = "x86_fp80"; 00261 case Type::FP128TyID: return (*ConcreteTypeDescriptions)[Ty] = "fp128"; 00262 case Type::PPC_FP128TyID: 00263 return (*ConcreteTypeDescriptions)[Ty] = "ppc_fp128"; 00264 case Type::LabelTyID: return (*ConcreteTypeDescriptions)[Ty] = "label"; 00265 } 00266 } 00267 } 00268 00269 // Check to see if the Type is already on the stack... 00270 unsigned Slot = 0, CurSize = TypeStack.size(); 00271 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type 00272 00273 // This is another base case for the recursion. In this case, we know 00274 // that we have looped back to a type that we have previously visited. 00275 // Generate the appropriate upreference to handle this. 00276 // 00277 if (Slot < CurSize) 00278 return "\\" + utostr(CurSize-Slot); // Here's the upreference 00279 00280 // Recursive case: derived types... 00281 std::string Result; 00282 TypeStack.push_back(Ty); // Add us to the stack.. 00283 00284 switch (Ty->getTypeID()) { 00285 case Type::IntegerTyID: { 00286 const IntegerType *ITy = cast<IntegerType>(Ty); 00287 Result = "i" + utostr(ITy->getBitWidth()); 00288 break; 00289 } 00290 case Type::FunctionTyID: { 00291 const FunctionType *FTy = cast<FunctionType>(Ty); 00292 if (!Result.empty()) 00293 Result += " "; 00294 Result += getTypeDescription(FTy->getReturnType(), TypeStack) + " ("; 00295 for (FunctionType::param_iterator I = FTy->param_begin(), 00296 E = FTy->param_end(); I != E; ++I) { 00297 if (I != FTy->param_begin()) 00298 Result += ", "; 00299 Result += getTypeDescription(*I, TypeStack); 00300 } 00301 if (FTy->isVarArg()) { 00302 if (FTy->getNumParams()) Result += ", "; 00303 Result += "..."; 00304 } 00305 Result += ")"; 00306 break; 00307 } 00308 case Type::StructTyID: { 00309 const StructType *STy = cast<StructType>(Ty); 00310 if (STy->isPacked()) 00311 Result = "<{ "; 00312 else 00313 Result = "{ "; 00314 for (StructType::element_iterator I = STy->element_begin(), 00315 E = STy->element_end(); I != E; ++I) { 00316 if (I != STy->element_begin()) 00317 Result += ", "; 00318 Result += getTypeDescription(*I, TypeStack); 00319 } 00320 Result += " }"; 00321 if (STy->isPacked()) 00322 Result += ">"; 00323 break; 00324 } 00325 case Type::PointerTyID: { 00326 const PointerType *PTy = cast<PointerType>(Ty); 00327 Result = getTypeDescription(PTy->getElementType(), TypeStack); 00328 if (unsigned AddressSpace = PTy->getAddressSpace()) 00329 Result += " addrspace(" + utostr(AddressSpace) + ")"; 00330 Result += " *"; 00331 break; 00332 } 00333 case Type::ArrayTyID: { 00334 const ArrayType *ATy = cast<ArrayType>(Ty); 00335 unsigned NumElements = ATy->getNumElements(); 00336 Result = "["; 00337 Result += utostr(NumElements) + " x "; 00338 Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]"; 00339 break; 00340 } 00341 case Type::VectorTyID: { 00342 const VectorType *PTy = cast<VectorType>(Ty); 00343 unsigned NumElements = PTy->getNumElements(); 00344 Result = "<"; 00345 Result += utostr(NumElements) + " x "; 00346 Result += getTypeDescription(PTy->getElementType(), TypeStack) + ">"; 00347 break; 00348 } 00349 default: 00350 Result = "<error>"; 00351 assert(0 && "Unhandled type in getTypeDescription!"); 00352 } 00353 00354 TypeStack.pop_back(); // Remove self from stack... 00355 00356 return Result; 00357 } 00358 00359 00360 00361 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map, 00362 const Type *Ty) { 00363 std::map<const Type*, std::string>::iterator I = Map.find(Ty); 00364 if (I != Map.end()) return I->second; 00365 00366 std::vector<const Type *> TypeStack; 00367 std::string Result = getTypeDescription(Ty, TypeStack); 00368 return Map[Ty] = Result; 00369 } 00370 00371 00372 const std::string &Type::getDescription() const { 00373 if (isAbstract()) 00374 return getOrCreateDesc(*AbstractTypeDescriptions, this); 00375 else 00376 return getOrCreateDesc(*ConcreteTypeDescriptions, this); 00377 } 00378 00379 00380 bool StructType::indexValid(const Value *V) const { 00381 // Structure indexes require 32-bit integer constants. 00382 if (V->getType() == Type::Int32Ty) 00383 if (const ConstantInt *CU = dyn_cast<ConstantInt>(V)) 00384 return indexValid(CU->getZExtValue()); 00385 return false; 00386 } 00387 00388 bool StructType::indexValid(unsigned V) const { 00389 return V < NumContainedTys; 00390 } 00391 00392 // getTypeAtIndex - Given an index value into the type, return the type of the 00393 // element. For a structure type, this must be a constant value... 00394 // 00395 const Type *StructType::getTypeAtIndex(const Value *V) const { 00396 unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue(); 00397 return getTypeAtIndex(Idx); 00398 } 00399 00400 const Type *StructType::getTypeAtIndex(unsigned Idx) const { 00401 assert(indexValid(Idx) && "Invalid structure index!"); 00402 return ContainedTys[Idx]; 00403 } 00404 00405 //===----------------------------------------------------------------------===// 00406 // Primitive 'Type' data 00407 //===----------------------------------------------------------------------===// 00408 00409 const Type *Type::VoidTy = new Type(Type::VoidTyID); 00410 const Type *Type::FloatTy = new Type(Type::FloatTyID); 00411 const Type *Type::DoubleTy = new Type(Type::DoubleTyID); 00412 const Type *Type::X86_FP80Ty = new Type(Type::X86_FP80TyID); 00413 const Type *Type::FP128Ty = new Type(Type::FP128TyID); 00414 const Type *Type::PPC_FP128Ty = new Type(Type::PPC_FP128TyID); 00415 const Type *Type::LabelTy = new Type(Type::LabelTyID); 00416 00417 namespace { 00418 struct BuiltinIntegerType : public IntegerType { 00419 explicit BuiltinIntegerType(unsigned W) : IntegerType(W) {} 00420 }; 00421 } 00422 const IntegerType *Type::Int1Ty = new BuiltinIntegerType(1); 00423 const IntegerType *Type::Int8Ty = new BuiltinIntegerType(8); 00424 const IntegerType *Type::Int16Ty = new BuiltinIntegerType(16); 00425 const IntegerType *Type::Int32Ty = new BuiltinIntegerType(32); 00426 const IntegerType *Type::Int64Ty = new BuiltinIntegerType(64); 00427 00428 00429 //===----------------------------------------------------------------------===// 00430 // Derived Type Constructors 00431 //===----------------------------------------------------------------------===// 00432 00433 /// isValidReturnType - Return true if the specified type is valid as a return 00434 /// type. 00435 bool FunctionType::isValidReturnType(const Type *RetTy) { 00436 if (RetTy->isFirstClassType()) 00437 return true; 00438 if (RetTy == Type::VoidTy || isa<OpaqueType>(RetTy)) 00439 return true; 00440 00441 // If this is a multiple return case, verify that each return is a first class 00442 // value and that there is at least one value. 00443 const StructType *SRetTy = dyn_cast<StructType>(RetTy); 00444 if (SRetTy == 0 || SRetTy->getNumElements() == 0) 00445 return false; 00446 00447 for (unsigned i = 0, e = SRetTy->getNumElements(); i != e; ++i) 00448 if (!SRetTy->getElementType(i)->isFirstClassType()) 00449 return false; 00450 return true; 00451 } 00452 00453 FunctionType::FunctionType(const Type *Result, 00454 const std::vector<const Type*> &Params, 00455 bool IsVarArgs) 00456 : DerivedType(FunctionTyID), isVarArgs(IsVarArgs) { 00457 ContainedTys = reinterpret_cast<PATypeHandle*>(this+1); 00458 NumContainedTys = Params.size() + 1; // + 1 for result type 00459 assert(isValidReturnType(Result) && "invalid return type for function"); 00460 00461 00462 bool isAbstract = Result->isAbstract(); 00463 new (&ContainedTys[0]) PATypeHandle(Result, this); 00464 00465 for (unsigned i = 0; i != Params.size(); ++i) { 00466 assert((Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])) && 00467 "Function arguments must be value types!"); 00468 new (&ContainedTys[i+1]) PATypeHandle(Params[i],this); 00469 isAbstract |= Params[i]->isAbstract(); 00470 } 00471 00472 // Calculate whether or not this type is abstract 00473 setAbstract(isAbstract); 00474 } 00475 00476 StructType::StructType(const std::vector<const Type*> &Types, bool isPacked) 00477 : CompositeType(StructTyID) { 00478 ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1); 00479 NumContainedTys = Types.size(); 00480 setSubclassData(isPacked); 00481 bool isAbstract = false; 00482 for (unsigned i = 0; i < Types.size(); ++i) { 00483 assert(Types[i] != Type::VoidTy && "Void type for structure field!!"); 00484 new (&ContainedTys[i]) PATypeHandle(Types[i], this); 00485 isAbstract |= Types[i]->isAbstract(); 00486 } 00487 00488 // Calculate whether or not this type is abstract 00489 setAbstract(isAbstract); 00490 } 00491 00492 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl) 00493 : SequentialType(ArrayTyID, ElType) { 00494 NumElements = NumEl; 00495 00496 // Calculate whether or not this type is abstract 00497 setAbstract(ElType->isAbstract()); 00498 } 00499 00500 VectorType::VectorType(const Type *ElType, unsigned NumEl) 00501 : SequentialType(VectorTyID, ElType) { 00502 NumElements = NumEl; 00503 setAbstract(ElType->isAbstract()); 00504 assert(NumEl > 0 && "NumEl of a VectorType must be greater than 0"); 00505 assert((ElType->isInteger() || ElType->isFloatingPoint() || 00506 isa<OpaqueType>(ElType)) && 00507 "Elements of a VectorType must be a primitive type"); 00508 00509 } 00510 00511 00512 PointerType::PointerType(const Type *E, unsigned AddrSpace) 00513 : SequentialType(PointerTyID, E) { 00514 AddressSpace = AddrSpace; 00515 // Calculate whether or not this type is abstract 00516 setAbstract(E->isAbstract()); 00517 } 00518 00519 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) { 00520 setAbstract(true); 00521 #ifdef DEBUG_MERGE_TYPES 00522 DOUT << "Derived new type: " << *this << "\n"; 00523 #endif 00524 } 00525 00526 // dropAllTypeUses - When this (abstract) type is resolved to be equal to 00527 // another (more concrete) type, we must eliminate all references to other 00528 // types, to avoid some circular reference problems. 00529 void DerivedType::dropAllTypeUses() { 00530 if (NumContainedTys != 0) { 00531 // The type must stay abstract. To do this, we insert a pointer to a type 00532 // that will never get resolved, thus will always be abstract. 00533 static Type *AlwaysOpaqueTy = OpaqueType::get(); 00534 static PATypeHolder Holder(AlwaysOpaqueTy); 00535 ContainedTys[0] = AlwaysOpaqueTy; 00536 00537 // Change the rest of the types to be Int32Ty's. It doesn't matter what we 00538 // pick so long as it doesn't point back to this type. We choose something 00539 // concrete to avoid overhead for adding to AbstracTypeUser lists and stuff. 00540 for (unsigned i = 1, e = NumContainedTys; i != e; ++i) 00541 ContainedTys[i] = Type::Int32Ty; 00542 } 00543 } 00544 00545 00546 namespace { 00547 00548 /// TypePromotionGraph and graph traits - this is designed to allow us to do 00549 /// efficient SCC processing of type graphs. This is the exact same as 00550 /// GraphTraits<Type*>, except that we pretend that concrete types have no 00551 /// children to avoid processing them. 00552 struct TypePromotionGraph { 00553 Type *Ty; 00554 TypePromotionGraph(Type *T) : Ty(T) {} 00555 }; 00556 00557 } 00558 00559 namespace llvm { 00560 template <> struct GraphTraits<TypePromotionGraph> { 00561 typedef Type NodeType; 00562 typedef Type::subtype_iterator ChildIteratorType; 00563 00564 static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; } 00565 static inline ChildIteratorType child_begin(NodeType *N) { 00566 if (N->isAbstract()) 00567 return N->subtype_begin(); 00568 else // No need to process children of concrete types. 00569 return N->subtype_end(); 00570 } 00571 static inline ChildIteratorType child_end(NodeType *N) { 00572 return N->subtype_end(); 00573 } 00574 }; 00575 } 00576 00577 00578 // PromoteAbstractToConcrete - This is a recursive function that walks a type 00579 // graph calculating whether or not a type is abstract. 00580 // 00581 void Type::PromoteAbstractToConcrete() { 00582 if (!isAbstract()) return; 00583 00584 scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this)); 00585 scc_iterator<TypePromotionGraph> SE = scc_end (TypePromotionGraph(this)); 00586 00587 for (; SI != SE; ++SI) { 00588 std::vector<Type*> &SCC = *SI; 00589 00590 // Concrete types are leaves in the tree. Since an SCC will either be all 00591 // abstract or all concrete, we only need to check one type. 00592 if (SCC[0]->isAbstract()) { 00593 if (isa<OpaqueType>(SCC[0])) 00594 return; // Not going to be concrete, sorry. 00595 00596 // If all of the children of all of the types in this SCC are concrete, 00597 // then this SCC is now concrete as well. If not, neither this SCC, nor 00598 // any parent SCCs will be concrete, so we might as well just exit. 00599 for (unsigned i = 0, e = SCC.size(); i != e; ++i) 00600 for (Type::subtype_iterator CI = SCC[i]->subtype_begin(), 00601 E = SCC[i]->subtype_end(); CI != E; ++CI) 00602 if ((*CI)->isAbstract()) 00603 // If the child type is in our SCC, it doesn't make the entire SCC 00604 // abstract unless there is a non-SCC abstract type. 00605 if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end()) 00606 return; // Not going to be concrete, sorry. 00607 00608 // Okay, we just discovered this whole SCC is now concrete, mark it as 00609 // such! 00610 for (unsigned i = 0, e = SCC.size(); i != e; ++i) { 00611 assert(SCC[i]->isAbstract() && "Why are we processing concrete types?"); 00612 00613 SCC[i]->setAbstract(false); 00614 } 00615 00616 for (unsigned i = 0, e = SCC.size(); i != e; ++i) { 00617 assert(!SCC[i]->isAbstract() && "Concrete type became abstract?"); 00618 // The type just became concrete, notify all users! 00619 cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete(); 00620 } 00621 } 00622 } 00623 } 00624 00625 00626 //===----------------------------------------------------------------------===// 00627 // Type Structural Equality Testing 00628 //===----------------------------------------------------------------------===// 00629 00630 // TypesEqual - Two types are considered structurally equal if they have the 00631 // same "shape": Every level and element of the types have identical primitive 00632 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to 00633 // be pointer equals to be equivalent though. This uses an optimistic algorithm 00634 // that assumes that two graphs are the same until proven otherwise. 00635 // 00636 static bool TypesEqual(const Type *Ty, const Type *Ty2, 00637 std::map<const Type *, const Type *> &EqTypes) { 00638 if (Ty == Ty2) return true; 00639 if (Ty->getTypeID() != Ty2->getTypeID()) return false; 00640 if (isa<OpaqueType>(Ty)) 00641 return false; // Two unequal opaque types are never equal 00642 00643 std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty); 00644 if (It != EqTypes.end()) 00645 return It->second == Ty2; // Looping back on a type, check for equality 00646 00647 // Otherwise, add the mapping to the table to make sure we don't get 00648 // recursion on the types... 00649 EqTypes.insert(It, std::make_pair(Ty, Ty2)); 00650 00651 // Two really annoying special cases that breaks an otherwise nice simple 00652 // algorithm is the fact that arraytypes have sizes that differentiates types, 00653 // and that function types can be varargs or not. Consider this now. 00654 // 00655 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) { 00656 const IntegerType *ITy2 = cast<IntegerType>(Ty2); 00657 return ITy->getBitWidth() == ITy2->getBitWidth(); 00658 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) { 00659 const PointerType *PTy2 = cast<PointerType>(Ty2); 00660 return PTy->getAddressSpace() == PTy2->getAddressSpace() && 00661 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes); 00662 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) { 00663 const StructType *STy2 = cast<StructType>(Ty2); 00664 if (STy->getNumElements() != STy2->getNumElements()) return false; 00665 if (STy->isPacked() != STy2->isPacked()) return false; 00666 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i) 00667 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes)) 00668 return false; 00669 return true; 00670 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 00671 const ArrayType *ATy2 = cast<ArrayType>(Ty2); 00672 return ATy->getNumElements() == ATy2->getNumElements() && 00673 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes); 00674 } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) { 00675 const VectorType *PTy2 = cast<VectorType>(Ty2); 00676 return PTy->getNumElements() == PTy2->getNumElements() && 00677 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes); 00678 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) { 00679 const FunctionType *FTy2 = cast<FunctionType>(Ty2); 00680 if (FTy->isVarArg() != FTy2->isVarArg() || 00681 FTy->getNumParams() != FTy2->getNumParams() || 00682 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes)) 00683 return false; 00684 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) { 00685 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes)) 00686 return false; 00687 } 00688 return true; 00689 } else { 00690 assert(0 && "Unknown derived type!"); 00691 return false; 00692 } 00693 } 00694 00695 static bool TypesEqual(const Type *Ty, const Type *Ty2) { 00696 std::map<const Type *, const Type *> EqTypes; 00697 return TypesEqual(Ty, Ty2, EqTypes); 00698 } 00699 00700 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to 00701 // TargetTy in the type graph. We know that Ty is an abstract type, so if we 00702 // ever reach a non-abstract type, we know that we don't need to search the 00703 // subgraph. 00704 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy, 00705 SmallPtrSet<const Type*, 128> &VisitedTypes) { 00706 if (TargetTy == CurTy) return true; 00707 if (!CurTy->isAbstract()) return false; 00708 00709 if (!VisitedTypes.insert(CurTy)) 00710 return false; // Already been here. 00711 00712 for (Type::subtype_iterator I = CurTy->subtype_begin(), 00713 E = CurTy->subtype_end(); I != E; ++I) 00714 if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes)) 00715 return true; 00716 return false; 00717 } 00718 00719 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy, 00720 SmallPtrSet<const Type*, 128> &VisitedTypes) { 00721 if (TargetTy == CurTy) return true; 00722 00723 if (!VisitedTypes.insert(CurTy)) 00724 return false; // Already been here. 00725 00726 for (Type::subtype_iterator I = CurTy->subtype_begin(), 00727 E = CurTy->subtype_end(); I != E; ++I) 00728 if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes)) 00729 return true; 00730 return false; 00731 } 00732 00733 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle 00734 /// back to itself. 00735 static bool TypeHasCycleThroughItself(const Type *Ty) { 00736 SmallPtrSet<const Type*, 128> VisitedTypes; 00737 00738 if (Ty->isAbstract()) { // Optimized case for abstract types. 00739 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end(); 00740 I != E; ++I) 00741 if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes)) 00742 return true; 00743 } else { 00744 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end(); 00745 I != E; ++I) 00746 if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes)) 00747 return true; 00748 } 00749 return false; 00750 } 00751 00752 /// getSubElementHash - Generate a hash value for all of the SubType's of this 00753 /// type. The hash value is guaranteed to be zero if any of the subtypes are 00754 /// an opaque type. Otherwise we try to mix them in as well as possible, but do 00755 /// not look at the subtype's subtype's. 00756 static unsigned getSubElementHash(const Type *Ty) { 00757 unsigned HashVal = 0; 00758 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end(); 00759 I != E; ++I) { 00760 HashVal *= 32; 00761 const Type *SubTy = I->get(); 00762 HashVal += SubTy->getTypeID(); 00763 switch (SubTy->getTypeID()) { 00764 default: break; 00765 case Type::OpaqueTyID: return 0; // Opaque -> hash = 0 no matter what. 00766 case Type::IntegerTyID: 00767 HashVal ^= (cast<IntegerType>(SubTy)->getBitWidth() << 3); 00768 break; 00769 case Type::FunctionTyID: 00770 HashVal ^= cast<FunctionType>(SubTy)->getNumParams()*2 + 00771 cast<FunctionType>(SubTy)->isVarArg(); 00772 break; 00773 case Type::ArrayTyID: 00774 HashVal ^= cast<ArrayType>(SubTy)->getNumElements(); 00775 break; 00776 case Type::VectorTyID: 00777 HashVal ^= cast<VectorType>(SubTy)->getNumElements(); 00778 break; 00779 case Type::StructTyID: 00780 HashVal ^= cast<StructType>(SubTy)->getNumElements(); 00781 break; 00782 case Type::PointerTyID: 00783 HashVal ^= cast<PointerType>(SubTy)->getAddressSpace(); 00784 break; 00785 } 00786 } 00787 return HashVal ? HashVal : 1; // Do not return zero unless opaque subty. 00788 } 00789 00790 //===----------------------------------------------------------------------===// 00791 // Derived Type Factory Functions 00792 //===----------------------------------------------------------------------===// 00793 00794 namespace llvm { 00795 class TypeMapBase { 00796 protected: 00797 /// TypesByHash - Keep track of types by their structure hash value. Note 00798 /// that we only keep track of types that have cycles through themselves in 00799 /// this map. 00800 /// 00801 std::multimap<unsigned, PATypeHolder> TypesByHash; 00802 00803 public: 00804 void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) { 00805 std::multimap<unsigned, PATypeHolder>::iterator I = 00806 TypesByHash.lower_bound(Hash); 00807 for (; I != TypesByHash.end() && I->first == Hash; ++I) { 00808 if (I->second == Ty) { 00809 TypesByHash.erase(I); 00810 return; 00811 } 00812 } 00813 00814 // This must be do to an opaque type that was resolved. Switch down to hash 00815 // code of zero. 00816 assert(Hash && "Didn't find type entry!"); 00817 RemoveFromTypesByHash(0, Ty); 00818 } 00819 00820 /// TypeBecameConcrete - When Ty gets a notification that TheType just became 00821 /// concrete, drop uses and make Ty non-abstract if we should. 00822 void TypeBecameConcrete(DerivedType *Ty, const DerivedType *TheType) { 00823 // If the element just became concrete, remove 'ty' from the abstract 00824 // type user list for the type. Do this for as many times as Ty uses 00825 // OldType. 00826 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end(); 00827 I != E; ++I) 00828 if (I->get() == TheType) 00829 TheType->removeAbstractTypeUser(Ty); 00830 00831 // If the type is currently thought to be abstract, rescan all of our 00832 // subtypes to see if the type has just become concrete! Note that this 00833 // may send out notifications to AbstractTypeUsers that types become 00834 // concrete. 00835 if (Ty->isAbstract()) 00836 Ty->PromoteAbstractToConcrete(); 00837 } 00838 }; 00839 } 00840 00841 00842 // TypeMap - Make sure that only one instance of a particular type may be 00843 // created on any given run of the compiler... note that this involves updating 00844 // our map if an abstract type gets refined somehow. 00845 // 00846 namespace llvm { 00847 template<class ValType, class TypeClass> 00848 class TypeMap : public TypeMapBase { 00849 std::map<ValType, PATypeHolder> Map; 00850 public: 00851 typedef typename std::map<ValType, PATypeHolder>::iterator iterator; 00852 ~TypeMap() { print("ON EXIT"); } 00853 00854 inline TypeClass *get(const ValType &V) { 00855 iterator I = Map.find(V); 00856 return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0; 00857 } 00858 00859 inline void add(const ValType &V, TypeClass *Ty) { 00860 Map.insert(std::make_pair(V, Ty)); 00861 00862 // If this type has a cycle, remember it. 00863 TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty)); 00864 print("add"); 00865 } 00866 00867 /// RefineAbstractType - This method is called after we have merged a type 00868 /// with another one. We must now either merge the type away with 00869 /// some other type or reinstall it in the map with it's new configuration. 00870 void RefineAbstractType(TypeClass *Ty, const DerivedType *OldType, 00871 const Type *NewType) { 00872 #ifdef DEBUG_MERGE_TYPES 00873 DOUT << "RefineAbstractType(" << (void*)OldType << "[" << *OldType 00874 << "], " << (void*)NewType << " [" << *NewType << "])\n"; 00875 #endif 00876 00877 // Otherwise, we are changing one subelement type into another. Clearly the 00878 // OldType must have been abstract, making us abstract. 00879 assert(Ty->isAbstract() && "Refining a non-abstract type!"); 00880 assert(OldType != NewType); 00881 00882 // Make a temporary type holder for the type so that it doesn't disappear on 00883 // us when we erase the entry from the map. 00884 PATypeHolder TyHolder = Ty; 00885 00886 // The old record is now out-of-date, because one of the children has been 00887 // updated. Remove the obsolete entry from the map. 00888 unsigned NumErased = Map.erase(ValType::get(Ty)); 00889 assert(NumErased && "Element not found!"); NumErased = NumErased; 00890 00891 // Remember the structural hash for the type before we start hacking on it, 00892 // in case we need it later. 00893 unsigned OldTypeHash = ValType::hashTypeStructure(Ty); 00894 00895 // Find the type element we are refining... and change it now! 00896 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) 00897 if (Ty->ContainedTys[i] == OldType) 00898 Ty->ContainedTys[i] = NewType; 00899 unsigned NewTypeHash = ValType::hashTypeStructure(Ty); 00900 00901 // If there are no cycles going through this node, we can do a simple, 00902 // efficient lookup in the map, instead of an inefficient nasty linear 00903 // lookup. 00904 if (!TypeHasCycleThroughItself(Ty)) { 00905 typename std::map<ValType, PATypeHolder>::iterator I; 00906 bool Inserted; 00907 00908 tie(I, Inserted) = Map.insert(std::make_pair(ValType::get(Ty), Ty)); 00909 if (!Inserted) { 00910 // Refined to a different type altogether? 00911 RemoveFromTypesByHash(OldTypeHash, Ty); 00912 00913 // We already have this type in the table. Get rid of the newly refined 00914 // type. 00915 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get()); 00916 Ty->refineAbstractTypeTo(NewTy); 00917 return; 00918 } 00919 } else { 00920 // Now we check to see if there is an existing entry in the table which is 00921 // structurally identical to the newly refined type. If so, this type 00922 // gets refined to the pre-existing type. 00923 // 00924 std::multimap<unsigned, PATypeHolder>::iterator I, E, Entry; 00925 tie(I, E) = TypesByHash.equal_range(NewTypeHash); 00926 Entry = E; 00927 for (; I != E; ++I) { 00928 if (I->second == Ty) { 00929 // Remember the position of the old type if we see it in our scan. 00930 Entry = I; 00931 } else { 00932 if (TypesEqual(Ty, I->second)) { 00933 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get()); 00934 00935 // Remove the old entry form TypesByHash. If the hash values differ 00936 // now, remove it from the old place. Otherwise, continue scanning 00937 // withing this hashcode to reduce work. 00938 if (NewTypeHash != OldTypeHash) { 00939 RemoveFromTypesByHash(OldTypeHash, Ty); 00940 } else { 00941 if (Entry == E) { 00942 // Find the location of Ty in the TypesByHash structure if we 00943 // haven't seen it already. 00944 while (I->second != Ty) { 00945 ++I; 00946 assert(I != E && "Structure doesn't contain type??"); 00947 } 00948 Entry = I; 00949 } 00950 TypesByHash.erase(Entry); 00951 } 00952 Ty->refineAbstractTypeTo(NewTy); 00953 return; 00954 } 00955 } 00956 } 00957 00958 // If there is no existing type of the same structure, we reinsert an 00959 // updated record into the map. 00960 Map.insert(std::make_pair(ValType::get(Ty), Ty)); 00961 } 00962 00963 // If the hash codes differ, update TypesByHash 00964 if (NewTypeHash != OldTypeHash) { 00965 RemoveFromTypesByHash(OldTypeHash, Ty); 00966 TypesByHash.insert(std::make_pair(NewTypeHash, Ty)); 00967 } 00968 00969 // If the type is currently thought to be abstract, rescan all of our 00970 // subtypes to see if the type has just become concrete! Note that this 00971 // may send out notifications to AbstractTypeUsers that types become 00972 // concrete. 00973 if (Ty->isAbstract()) 00974 Ty->PromoteAbstractToConcrete(); 00975 } 00976 00977 void print(const char *Arg) const { 00978 #ifdef DEBUG_MERGE_TYPES 00979 DOUT << "TypeMap<>::" << Arg << " table contents:\n"; 00980 unsigned i = 0; 00981 for (typename std::map<ValType, PATypeHolder>::const_iterator I 00982 = Map.begin(), E = Map.end(); I != E; ++I) 00983 DOUT << " " << (++i) << ". " << (void*)I->second.get() << " " 00984 << *I->second.get() << "\n"; 00985 #endif 00986 } 00987 00988 void dump() const { print("dump output"); } 00989 }; 00990 } 00991 00992 00993 //===----------------------------------------------------------------------===// 00994 // Function Type Factory and Value Class... 00995 // 00996 00997 //===----------------------------------------------------------------------===// 00998 // Integer Type Factory... 00999 // 01000 namespace llvm { 01001 class IntegerValType { 01002 uint32_t bits; 01003 public: 01004 IntegerValType(uint16_t numbits) : bits(numbits) {} 01005 01006 static IntegerValType get(const IntegerType *Ty) { 01007 return IntegerValType(Ty->getBitWidth()); 01008 } 01009 01010 static unsigned hashTypeStructure(const IntegerType *Ty) { 01011 return (unsigned)Ty->getBitWidth(); 01012 } 01013 01014 inline bool operator<(const IntegerValType &IVT) const { 01015 return bits < IVT.bits; 01016 } 01017 }; 01018 } 01019 01020 static ManagedStatic<TypeMap<IntegerValType, IntegerType> > IntegerTypes; 01021 01022 const IntegerType *IntegerType::get(unsigned NumBits) { 01023 assert(NumBits >= MIN_INT_BITS && "bitwidth too small"); 01024 assert(NumBits <= MAX_INT_BITS && "bitwidth too large"); 01025 01026 // Check for the built-in integer types 01027 switch (NumBits) { 01028 case 1: return cast<IntegerType>(Type::Int1Ty); 01029 case 8: return cast<IntegerType>(Type::Int8Ty); 01030 case 16: return cast<IntegerType>(Type::Int16Ty); 01031 case 32: return cast<IntegerType>(Type::Int32Ty); 01032 case 64: return cast<IntegerType>(Type::Int64Ty); 01033 default: 01034 break; 01035 } 01036 01037 IntegerValType IVT(NumBits); 01038 IntegerType *ITy = IntegerTypes->get(IVT); 01039 if (ITy) return ITy; // Found a match, return it! 01040 01041 // Value not found. Derive a new type! 01042 ITy = new IntegerType(NumBits); 01043 IntegerTypes->add(IVT, ITy); 01044 01045 #ifdef DEBUG_MERGE_TYPES 01046 DOUT << "Derived new type: " << *ITy << "\n"; 01047 #endif 01048 return ITy; 01049 } 01050 01051 bool IntegerType::isPowerOf2ByteWidth() const { 01052 unsigned BitWidth = getBitWidth(); 01053 return (BitWidth > 7) && isPowerOf2_32(BitWidth); 01054 } 01055 01056 APInt IntegerType::getMask() const { 01057 return APInt::getAllOnesValue(getBitWidth()); 01058 } 01059 01060 // FunctionValType - Define a class to hold the key that goes into the TypeMap 01061 // 01062 namespace llvm { 01063 class FunctionValType { 01064 const Type *RetTy; 01065 std::vector<const Type*> ArgTypes; 01066 bool isVarArg; 01067 public: 01068 FunctionValType(const Type *ret, const std::vector<const Type*> &args, 01069 bool isVA) : RetTy(ret), ArgTypes(args), isVarArg(isVA) {} 01070 01071 static FunctionValType get(const FunctionType *FT); 01072 01073 static unsigned hashTypeStructure(const FunctionType *FT) { 01074 unsigned Result = FT->getNumParams()*2 + FT->isVarArg(); 01075 return Result; 01076 } 01077 01078 inline bool operator<(const FunctionValType &MTV) const { 01079 if (RetTy < MTV.RetTy) return true; 01080 if (RetTy > MTV.RetTy) return false; 01081 if (isVarArg < MTV.isVarArg) return true; 01082 if (isVarArg > MTV.isVarArg) return false; 01083 if (ArgTypes < MTV.ArgTypes) return true; 01084 if (ArgTypes > MTV.ArgTypes) return false; 01085 return false; 01086 } 01087 }; 01088 } 01089 01090 // Define the actual map itself now... 01091 static ManagedStatic<TypeMap<FunctionValType, FunctionType> > FunctionTypes; 01092 01093 FunctionValType FunctionValType::get(const FunctionType *FT) { 01094 // Build up a FunctionValType 01095 std::vector<const Type *> ParamTypes; 01096 ParamTypes.reserve(FT->getNumParams()); 01097 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) 01098 ParamTypes.push_back(FT->getParamType(i)); 01099 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg()); 01100 } 01101 01102 01103 // FunctionType::get - The factory function for the FunctionType class... 01104 FunctionType *FunctionType::get(const Type *ReturnType, 01105 const std::vector<const Type*> &Params, 01106 bool isVarArg) { 01107 FunctionValType VT(ReturnType, Params, isVarArg); 01108 FunctionType *FT = FunctionTypes->get(VT); 01109 if (FT) 01110 return FT; 01111 01112 FT = (FunctionType*) operator new(sizeof(FunctionType) + 01113 sizeof(PATypeHandle)*(Params.size()+1)); 01114 new (FT) FunctionType(ReturnType, Params, isVarArg); 01115 FunctionTypes->add(VT, FT); 01116 01117 #ifdef DEBUG_MERGE_TYPES 01118 DOUT << "Derived new type: " << FT << "\n"; 01119 #endif 01120 return FT; 01121 } 01122 01123 //===----------------------------------------------------------------------===// 01124 // Array Type Factory... 01125 // 01126 namespace llvm { 01127 class ArrayValType { 01128 const Type *ValTy; 01129 uint64_t Size; 01130 public: 01131 ArrayValType(const Type *val, uint64_t sz) : ValTy(val), Size(sz) {} 01132 01133 static ArrayValType get(const ArrayType *AT) { 01134 return ArrayValType(AT->getElementType(), AT->getNumElements()); 01135 } 01136 01137 static unsigned hashTypeStructure(const ArrayType *AT) { 01138 return (unsigned)AT->getNumElements(); 01139 } 01140 01141 inline bool operator<(const ArrayValType &MTV) const { 01142 if (Size < MTV.Size) return true; 01143 return Size == MTV.Size && ValTy < MTV.ValTy; 01144 } 01145 }; 01146 } 01147 static ManagedStatic<TypeMap<ArrayValType, ArrayType> > ArrayTypes; 01148 01149 01150 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) { 01151 assert(ElementType && "Can't get array of null types!"); 01152 01153 ArrayValType AVT(ElementType, NumElements); 01154 ArrayType *AT = ArrayTypes->get(AVT); 01155 if (AT) return AT; // Found a match, return it! 01156 01157 // Value not found. Derive a new type! 01158 ArrayTypes->add(AVT, AT = new ArrayType(ElementType, NumElements)); 01159 01160 #ifdef DEBUG_MERGE_TYPES 01161 DOUT << "Derived new type: " << *AT << "\n"; 01162 #endif 01163 return AT; 01164 } 01165 01166 01167 //===----------------------------------------------------------------------===// 01168 // Vector Type Factory... 01169 // 01170 namespace llvm { 01171 class VectorValType { 01172 const Type *ValTy; 01173 unsigned Size; 01174 public: 01175 VectorValType(const Type *val, int sz) : ValTy(val), Size(sz) {} 01176 01177 static VectorValType get(const VectorType *PT) { 01178 return VectorValType(PT->getElementType(), PT->getNumElements()); 01179 } 01180 01181 static unsigned hashTypeStructure(const VectorType *PT) { 01182 return PT->getNumElements(); 01183 } 01184 01185 inline bool operator<(const VectorValType &MTV) const { 01186 if (Size < MTV.Size) return true; 01187 return Size == MTV.Size && ValTy < MTV.ValTy; 01188 } 01189 }; 01190 } 01191 static ManagedStatic<TypeMap<VectorValType, VectorType> > VectorTypes; 01192 01193 01194 VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) { 01195 assert(ElementType && "Can't get vector of null types!"); 01196 01197 VectorValType PVT(ElementType, NumElements); 01198 VectorType *PT = VectorTypes->get(PVT); 01199 if (PT) return PT; // Found a match, return it! 01200 01201 // Value not found. Derive a new type! 01202 VectorTypes->add(PVT, PT = new VectorType(ElementType, NumElements)); 01203 01204 #ifdef DEBUG_MERGE_TYPES 01205 DOUT << "Derived new type: " << *PT << "\n"; 01206 #endif 01207 return PT; 01208 } 01209 01210 //===----------------------------------------------------------------------===// 01211 // Struct Type Factory... 01212 // 01213 01214 namespace llvm { 01215 // StructValType - Define a class to hold the key that goes into the TypeMap 01216 // 01217 class StructValType { 01218 std::vector<const Type*> ElTypes; 01219 bool packed; 01220 public: 01221 StructValType(const std::vector<const Type*> &args, bool isPacked) 01222 : ElTypes(args), packed(isPacked) {} 01223 01224 static StructValType get(const StructType *ST) { 01225 std::vector<const Type *> ElTypes; 01226 ElTypes.reserve(ST->getNumElements()); 01227 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) 01228 ElTypes.push_back(ST->getElementType(i)); 01229 01230 return StructValType(ElTypes, ST->isPacked()); 01231 } 01232 01233 static unsigned hashTypeStructure(const StructType *ST) { 01234 return ST->getNumElements(); 01235 } 01236 01237 inline bool operator<(const StructValType &STV) const { 01238 if (ElTypes < STV.ElTypes) return true; 01239 else if (ElTypes > STV.ElTypes) return false; 01240 else return (int)packed < (int)STV.packed; 01241 } 01242 }; 01243 } 01244 01245 static ManagedStatic<TypeMap<StructValType, StructType> > StructTypes; 01246 01247 StructType *StructType::get(const std::vector<const Type*> &ETypes, 01248 bool isPacked) { 01249 StructValType STV(ETypes, isPacked); 01250 StructType *ST = StructTypes->get(STV); 01251 if (ST) return ST; 01252 01253 // Value not found. Derive a new type! 01254 ST = (StructType*) operator new(sizeof(StructType) + 01255 sizeof(PATypeHandle) * ETypes.size()); 01256 new (ST) StructType(ETypes, isPacked); 01257 StructTypes->add(STV, ST); 01258 01259 #ifdef DEBUG_MERGE_TYPES 01260 DOUT << "Derived new type: " << *ST << "\n"; 01261 #endif 01262 return ST; 01263 } 01264 01265 StructType *StructType::get(const Type *type, ...) { 01266 va_list ap; 01267 std::vector<const llvm::Type*> StructFields; 01268 va_start(ap, type); 01269 while (type) { 01270 StructFields.push_back(type); 01271 type = va_arg(ap, llvm::Type*); 01272 } 01273 return llvm::StructType::get(StructFields); 01274 } 01275 01276 01277 01278 //===----------------------------------------------------------------------===// 01279 // Pointer Type Factory... 01280 // 01281 01282 // PointerValType - Define a class to hold the key that goes into the TypeMap 01283 // 01284 namespace llvm { 01285 class PointerValType { 01286 const Type *ValTy; 01287 unsigned AddressSpace; 01288 public: 01289 PointerValType(const Type *val, unsigned as) : ValTy(val), AddressSpace(as) {} 01290 01291 static PointerValType get(const PointerType *PT) { 01292 return PointerValType(PT->getElementType(), PT->getAddressSpace()); 01293 } 01294 01295 static unsigned hashTypeStructure(const PointerType *PT) { 01296 return getSubElementHash(PT); 01297 } 01298 01299 bool operator<(const PointerValType &MTV) const { 01300 if (AddressSpace < MTV.AddressSpace) return true; 01301 return AddressSpace == MTV.AddressSpace && ValTy < MTV.ValTy; 01302 } 01303 }; 01304 } 01305 01306 static ManagedStatic<TypeMap<PointerValType, PointerType> > PointerTypes; 01307 01308 PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) { 01309 assert(ValueType && "Can't get a pointer to <null> type!"); 01310 assert(ValueType != Type::VoidTy && 01311 "Pointer to void is not valid, use sbyte* instead!"); 01312 assert(ValueType != Type::LabelTy && "Pointer to label is not valid!"); 01313 PointerValType PVT(ValueType, AddressSpace); 01314 01315 PointerType *PT = PointerTypes->get(PVT); 01316 if (PT) return PT; 01317 01318 // Value not found. Derive a new type! 01319 PointerTypes->add(PVT, PT = new PointerType(ValueType, AddressSpace)); 01320 01321 #ifdef DEBUG_MERGE_TYPES 01322 DOUT << "Derived new type: " << *PT << "\n"; 01323 #endif 01324 return PT; 01325 } 01326 01327 //===----------------------------------------------------------------------===// 01328 // Derived Type Refinement Functions 01329 //===----------------------------------------------------------------------===// 01330 01331 // removeAbstractTypeUser - Notify an abstract type that a user of the class 01332 // no longer has a handle to the type. This function is called primarily by 01333 // the PATypeHandle class. When there are no users of the abstract type, it 01334 // is annihilated, because there is no way to get a reference to it ever again. 01335 // 01336 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const { 01337 // Search from back to front because we will notify users from back to 01338 // front. Also, it is likely that there will be a stack like behavior to 01339 // users that register and unregister users. 01340 // 01341 unsigned i; 01342 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i) 01343 assert(i != 0 && "AbstractTypeUser not in user list!"); 01344 01345 --i; // Convert to be in range 0 <= i < size() 01346 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound? 01347 01348 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i); 01349 01350 #ifdef DEBUG_MERGE_TYPES 01351 DOUT << " remAbstractTypeUser[" << (void*)this << ", " 01352 << *this << "][" << i << "] User = " << U << "\n"; 01353 #endif 01354 01355 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) { 01356 #ifdef DEBUG_MERGE_TYPES 01357 DOUT << "DELETEing unused abstract type: <" << *this 01358 << ">[" << (void*)this << "]" << "\n"; 01359 #endif 01360 this->destroy(); 01361 } 01362 } 01363 01364 // refineAbstractTypeTo - This function is used when it is discovered that 01365 // the 'this' abstract type is actually equivalent to the NewType specified. 01366 // This causes all users of 'this' to switch to reference the more concrete type 01367 // NewType and for 'this' to be deleted. 01368 // 01369 void DerivedType::refineAbstractTypeTo(const Type *NewType) { 01370 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!"); 01371 assert(this != NewType && "Can't refine to myself!"); 01372 assert(ForwardType == 0 && "This type has already been refined!"); 01373 01374 // The descriptions may be out of date. Conservatively clear them all! 01375 AbstractTypeDescriptions->clear(); 01376 01377 #ifdef DEBUG_MERGE_TYPES 01378 DOUT << "REFINING abstract type [" << (void*)this << " " 01379 << *this << "] to [" << (void*)NewType << " " 01380 << *NewType << "]!\n"; 01381 #endif 01382 01383 // Make sure to put the type to be refined to into a holder so that if IT gets 01384 // refined, that we will not continue using a dead reference... 01385 // 01386 PATypeHolder NewTy(NewType); 01387 01388 // Any PATypeHolders referring to this type will now automatically forward to 01389 // the type we are resolved to. 01390 ForwardType = NewType; 01391 if (NewType->isAbstract()) 01392 cast<DerivedType>(NewType)->addRef(); 01393 01394 // Add a self use of the current type so that we don't delete ourself until 01395 // after the function exits. 01396 // 01397 PATypeHolder CurrentTy(this); 01398 01399 // To make the situation simpler, we ask the subclass to remove this type from 01400 // the type map, and to replace any type uses with uses of non-abstract types. 01401 // This dramatically limits the amount of recursive type trouble we can find 01402 // ourselves in. 01403 dropAllTypeUses(); 01404 01405 // Iterate over all of the uses of this type, invoking callback. Each user 01406 // should remove itself from our use list automatically. We have to check to 01407 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types 01408 // will not cause users to drop off of the use list. If we resolve to ourself 01409 // we succeed! 01410 // 01411 while (!AbstractTypeUsers.empty() && NewTy != this) { 01412 AbstractTypeUser *User = AbstractTypeUsers.back(); 01413 01414 unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize; 01415 #ifdef DEBUG_MERGE_TYPES 01416 DOUT << " REFINING user " << OldSize-1 << "[" << (void*)User 01417 << "] of abstract type [" << (void*)this << " " 01418 << *this << "] to [" << (void*)NewTy.get() << " " 01419 << *NewTy << "]!\n"; 01420 #endif 01421 User->refineAbstractType(this, NewTy); 01422 01423 assert(AbstractTypeUsers.size() != OldSize && 01424 "AbsTyUser did not remove self from user list!"); 01425 } 01426 01427 // If we were successful removing all users from the type, 'this' will be 01428 // deleted when the last PATypeHolder is destroyed or updated from this type. 01429 // This may occur on exit of this function, as the CurrentTy object is 01430 // destroyed. 01431 } 01432 01433 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that 01434 // the current type has transitioned from being abstract to being concrete. 01435 // 01436 void DerivedType::notifyUsesThatTypeBecameConcrete() { 01437 #ifdef DEBUG_MERGE_TYPES 01438 DOUT << "typeIsREFINED type: " << (void*)this << " " << *this << "\n"; 01439 #endif 01440 01441 unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize; 01442 while (!AbstractTypeUsers.empty()) { 01443 AbstractTypeUser *ATU = AbstractTypeUsers.back(); 01444 ATU->typeBecameConcrete(this); 01445 01446 assert(AbstractTypeUsers.size() < OldSize-- && 01447 "AbstractTypeUser did not remove itself from the use list!"); 01448 } 01449 } 01450 01451 // refineAbstractType - Called when a contained type is found to be more 01452 // concrete - this could potentially change us from an abstract type to a 01453 // concrete type. 01454 // 01455 void FunctionType::refineAbstractType(const DerivedType *OldType, 01456 const Type *NewType) { 01457 FunctionTypes->RefineAbstractType(this, OldType, NewType); 01458 } 01459 01460 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) { 01461 FunctionTypes->TypeBecameConcrete(this, AbsTy); 01462 } 01463 01464 01465 // refineAbstractType - Called when a contained type is found to be more 01466 // concrete - this could potentially change us from an abstract type to a 01467 // concrete type. 01468 // 01469 void ArrayType::refineAbstractType(const DerivedType *OldType, 01470 const Type *NewType) { 01471 ArrayTypes->RefineAbstractType(this, OldType, NewType); 01472 } 01473 01474 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) { 01475 ArrayTypes->TypeBecameConcrete(this, AbsTy); 01476 } 01477 01478 // refineAbstractType - Called when a contained type is found to be more 01479 // concrete - this could potentially change us from an abstract type to a 01480 // concrete type. 01481 // 01482 void VectorType::refineAbstractType(const DerivedType *OldType, 01483 const Type *NewType) { 01484 VectorTypes->RefineAbstractType(this, OldType, NewType); 01485 } 01486 01487 void VectorType::typeBecameConcrete(const DerivedType *AbsTy) { 01488 VectorTypes->TypeBecameConcrete(this, AbsTy); 01489 } 01490 01491 // refineAbstractType - Called when a contained type is found to be more 01492 // concrete - this could potentially change us from an abstract type to a 01493 // concrete type. 01494 // 01495 void StructType::refineAbstractType(const DerivedType *OldType, 01496 const Type *NewType) { 01497 StructTypes->RefineAbstractType(this, OldType, NewType); 01498 } 01499 01500 void StructType::typeBecameConcrete(const DerivedType *AbsTy) { 01501 StructTypes->TypeBecameConcrete(this, AbsTy); 01502 } 01503 01504 // refineAbstractType - Called when a contained type is found to be more 01505 // concrete - this could potentially change us from an abstract type to a 01506 // concrete type. 01507 // 01508 void PointerType::refineAbstractType(const DerivedType *OldType, 01509 const Type *NewType) { 01510 PointerTypes->RefineAbstractType(this, OldType, NewType); 01511 } 01512 01513 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) { 01514 PointerTypes->TypeBecameConcrete(this, AbsTy); 01515 } 01516 01517 bool SequentialType::indexValid(const Value *V) const { 01518 if (const IntegerType *IT = dyn_cast<IntegerType>(V->getType())) 01519 return IT->getBitWidth() == 32 || IT->getBitWidth() == 64; 01520 return false; 01521 } 01522 01523 namespace llvm { 01524 std::ostream &operator<<(std::ostream &OS, const Type *T) { 01525 if (T == 0) 01526 OS << "<null> value!\n"; 01527 else 01528 T->print(OS); 01529 return OS; 01530 } 01531 01532 std::ostream &operator<<(std::ostream &OS, const Type &T) { 01533 T.print(OS); 01534 return OS; 01535 } 01536 }