clang API Documentation

CGRTTI.cpp
Go to the documentation of this file.
00001 //===--- CGCXXRTTI.cpp - Emit LLVM Code for C++ RTTI descriptors ----------===//
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 contains code dealing with C++ code generation of RTTI descriptors.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "CodeGenModule.h"
00015 #include "CGCXXABI.h"
00016 #include "clang/AST/RecordLayout.h"
00017 #include "clang/AST/Type.h"
00018 #include "clang/Frontend/CodeGenOptions.h"
00019 #include "CGObjCRuntime.h"
00020 
00021 using namespace clang;
00022 using namespace CodeGen;
00023 
00024 namespace {
00025 class RTTIBuilder {
00026   CodeGenModule &CGM;  // Per-module state.
00027   llvm::LLVMContext &VMContext;
00028   
00029   /// Fields - The fields of the RTTI descriptor currently being built.
00030   SmallVector<llvm::Constant *, 16> Fields;
00031 
00032   /// GetAddrOfTypeName - Returns the mangled type name of the given type.
00033   llvm::GlobalVariable *
00034   GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
00035 
00036   /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI 
00037   /// descriptor of the given type.
00038   llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
00039   
00040   /// BuildVTablePointer - Build the vtable pointer for the given type.
00041   void BuildVTablePointer(const Type *Ty);
00042   
00043   /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
00044   /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
00045   void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
00046   
00047   /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
00048   /// classes with bases that do not satisfy the abi::__si_class_type_info 
00049   /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
00050   void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
00051   
00052   /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
00053   /// for pointer types.
00054   void BuildPointerTypeInfo(QualType PointeeTy);
00055 
00056   /// BuildObjCObjectTypeInfo - Build the appropriate kind of
00057   /// type_info for an object type.
00058   void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
00059   
00060   /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info 
00061   /// struct, used for member pointer types.
00062   void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
00063   
00064 public:
00065   RTTIBuilder(CodeGenModule &CGM) : CGM(CGM), 
00066     VMContext(CGM.getModule().getContext()) { }
00067 
00068   // Pointer type info flags.
00069   enum {
00070     /// PTI_Const - Type has const qualifier.
00071     PTI_Const = 0x1,
00072     
00073     /// PTI_Volatile - Type has volatile qualifier.
00074     PTI_Volatile = 0x2,
00075     
00076     /// PTI_Restrict - Type has restrict qualifier.
00077     PTI_Restrict = 0x4,
00078     
00079     /// PTI_Incomplete - Type is incomplete.
00080     PTI_Incomplete = 0x8,
00081     
00082     /// PTI_ContainingClassIncomplete - Containing class is incomplete.
00083     /// (in pointer to member).
00084     PTI_ContainingClassIncomplete = 0x10
00085   };
00086   
00087   // VMI type info flags.
00088   enum {
00089     /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
00090     VMI_NonDiamondRepeat = 0x1,
00091     
00092     /// VMI_DiamondShaped - Class is diamond shaped.
00093     VMI_DiamondShaped = 0x2
00094   };
00095   
00096   // Base class type info flags.
00097   enum {
00098     /// BCTI_Virtual - Base class is virtual.
00099     BCTI_Virtual = 0x1,
00100     
00101     /// BCTI_Public - Base class is public.
00102     BCTI_Public = 0x2
00103   };
00104   
00105   /// BuildTypeInfo - Build the RTTI type info struct for the given type.
00106   ///
00107   /// \param Force - true to force the creation of this RTTI value
00108   /// \param ForEH - true if this is for exception handling
00109   llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
00110 };
00111 }
00112 
00113 llvm::GlobalVariable *
00114 RTTIBuilder::GetAddrOfTypeName(QualType Ty, 
00115                                llvm::GlobalVariable::LinkageTypes Linkage) {
00116   SmallString<256> OutName;
00117   llvm::raw_svector_ostream Out(OutName);
00118   CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
00119   Out.flush();
00120   StringRef Name = OutName.str();
00121 
00122   // We know that the mangled name of the type starts at index 4 of the
00123   // mangled name of the typename, so we can just index into it in order to
00124   // get the mangled name of the type.
00125   llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
00126                                                             Name.substr(4));
00127 
00128   llvm::GlobalVariable *GV = 
00129     CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
00130 
00131   GV->setInitializer(Init);
00132 
00133   return GV;
00134 }
00135 
00136 llvm::Constant *RTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
00137   // Mangle the RTTI name.
00138   SmallString<256> OutName;
00139   llvm::raw_svector_ostream Out(OutName);
00140   CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
00141   Out.flush();
00142   StringRef Name = OutName.str();
00143 
00144   // Look for an existing global.
00145   llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
00146   
00147   if (!GV) {
00148     // Create a new global variable.
00149     GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
00150                                   /*Constant=*/true,
00151                                   llvm::GlobalValue::ExternalLinkage, 0, Name);
00152   }
00153   
00154   return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
00155 }
00156 
00157 /// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
00158 /// info for that type is defined in the standard library.
00159 static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
00160   // Itanium C++ ABI 2.9.2:
00161   //   Basic type information (e.g. for "int", "bool", etc.) will be kept in
00162   //   the run-time support library. Specifically, the run-time support
00163   //   library should contain type_info objects for the types X, X* and 
00164   //   X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
00165   //   unsigned char, signed char, short, unsigned short, int, unsigned int,
00166   //   long, unsigned long, long long, unsigned long long, float, double,
00167   //   long double, char16_t, char32_t, and the IEEE 754r decimal and 
00168   //   half-precision floating point types.
00169   switch (Ty->getKind()) {
00170     case BuiltinType::Void:
00171     case BuiltinType::NullPtr:
00172     case BuiltinType::Bool:
00173     case BuiltinType::WChar_S:
00174     case BuiltinType::WChar_U:
00175     case BuiltinType::Char_U:
00176     case BuiltinType::Char_S:
00177     case BuiltinType::UChar:
00178     case BuiltinType::SChar:
00179     case BuiltinType::Short:
00180     case BuiltinType::UShort:
00181     case BuiltinType::Int:
00182     case BuiltinType::UInt:
00183     case BuiltinType::Long:
00184     case BuiltinType::ULong:
00185     case BuiltinType::LongLong:
00186     case BuiltinType::ULongLong:
00187     case BuiltinType::Half:
00188     case BuiltinType::Float:
00189     case BuiltinType::Double:
00190     case BuiltinType::LongDouble:
00191     case BuiltinType::Char16:
00192     case BuiltinType::Char32:
00193     case BuiltinType::Int128:
00194     case BuiltinType::UInt128:
00195       return true;
00196       
00197     case BuiltinType::Dependent:
00198 #define BUILTIN_TYPE(Id, SingletonId)
00199 #define PLACEHOLDER_TYPE(Id, SingletonId) \
00200     case BuiltinType::Id:
00201 #include "clang/AST/BuiltinTypes.def"
00202       llvm_unreachable("asking for RRTI for a placeholder type!");
00203       
00204     case BuiltinType::ObjCId:
00205     case BuiltinType::ObjCClass:
00206     case BuiltinType::ObjCSel:
00207       llvm_unreachable("FIXME: Objective-C types are unsupported!");
00208   }
00209 
00210   llvm_unreachable("Invalid BuiltinType Kind!");
00211 }
00212 
00213 static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
00214   QualType PointeeTy = PointerTy->getPointeeType();
00215   const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
00216   if (!BuiltinTy)
00217     return false;
00218     
00219   // Check the qualifiers.
00220   Qualifiers Quals = PointeeTy.getQualifiers();
00221   Quals.removeConst();
00222     
00223   if (!Quals.empty())
00224     return false;
00225     
00226   return TypeInfoIsInStandardLibrary(BuiltinTy);
00227 }
00228 
00229 /// IsStandardLibraryRTTIDescriptor - Returns whether the type
00230 /// information for the given type exists in the standard library.
00231 static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
00232   // Type info for builtin types is defined in the standard library.
00233   if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
00234     return TypeInfoIsInStandardLibrary(BuiltinTy);
00235   
00236   // Type info for some pointer types to builtin types is defined in the
00237   // standard library.
00238   if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
00239     return TypeInfoIsInStandardLibrary(PointerTy);
00240 
00241   return false;
00242 }
00243 
00244 /// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
00245 /// the given type exists somewhere else, and that we should not emit the type
00246 /// information in this translation unit.  Assumes that it is not a
00247 /// standard-library type.
00248 static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM, QualType Ty) {
00249   ASTContext &Context = CGM.getContext();
00250 
00251   // If RTTI is disabled, don't consider key functions.
00252   if (!Context.getLangOpts().RTTI) return false;
00253 
00254   if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
00255     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
00256     if (!RD->hasDefinition())
00257       return false;
00258 
00259     if (!RD->isDynamicClass())
00260       return false;
00261 
00262     return !CGM.getVTables().ShouldEmitVTableInThisTU(RD);
00263   }
00264   
00265   return false;
00266 }
00267 
00268 /// IsIncompleteClassType - Returns whether the given record type is incomplete.
00269 static bool IsIncompleteClassType(const RecordType *RecordTy) {
00270   return !RecordTy->getDecl()->isCompleteDefinition();
00271 }  
00272 
00273 /// ContainsIncompleteClassType - Returns whether the given type contains an
00274 /// incomplete class type. This is true if
00275 ///
00276 ///   * The given type is an incomplete class type.
00277 ///   * The given type is a pointer type whose pointee type contains an 
00278 ///     incomplete class type.
00279 ///   * The given type is a member pointer type whose class is an incomplete
00280 ///     class type.
00281 ///   * The given type is a member pointer type whoise pointee type contains an
00282 ///     incomplete class type.
00283 /// is an indirect or direct pointer to an incomplete class type.
00284 static bool ContainsIncompleteClassType(QualType Ty) {
00285   if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
00286     if (IsIncompleteClassType(RecordTy))
00287       return true;
00288   }
00289   
00290   if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
00291     return ContainsIncompleteClassType(PointerTy->getPointeeType());
00292   
00293   if (const MemberPointerType *MemberPointerTy = 
00294       dyn_cast<MemberPointerType>(Ty)) {
00295     // Check if the class type is incomplete.
00296     const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
00297     if (IsIncompleteClassType(ClassType))
00298       return true;
00299     
00300     return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
00301   }
00302   
00303   return false;
00304 }
00305 
00306 /// getTypeInfoLinkage - Return the linkage that the type info and type info
00307 /// name constants should have for the given type.
00308 static llvm::GlobalVariable::LinkageTypes 
00309 getTypeInfoLinkage(CodeGenModule &CGM, QualType Ty) {
00310   // Itanium C++ ABI 2.9.5p7:
00311   //   In addition, it and all of the intermediate abi::__pointer_type_info 
00312   //   structs in the chain down to the abi::__class_type_info for the
00313   //   incomplete class type must be prevented from resolving to the 
00314   //   corresponding type_info structs for the complete class type, possibly
00315   //   by making them local static objects. Finally, a dummy class RTTI is
00316   //   generated for the incomplete type that will not resolve to the final 
00317   //   complete class RTTI (because the latter need not exist), possibly by 
00318   //   making it a local static object.
00319   if (ContainsIncompleteClassType(Ty))
00320     return llvm::GlobalValue::InternalLinkage;
00321   
00322   switch (Ty->getLinkage()) {
00323   case NoLinkage:
00324   case InternalLinkage:
00325   case UniqueExternalLinkage:
00326     return llvm::GlobalValue::InternalLinkage;
00327 
00328   case ExternalLinkage:
00329     if (!CGM.getLangOpts().RTTI) {
00330       // RTTI is not enabled, which means that this type info struct is going
00331       // to be used for exception handling. Give it linkonce_odr linkage.
00332       return llvm::GlobalValue::LinkOnceODRLinkage;
00333     }
00334 
00335     if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
00336       const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
00337       if (RD->hasAttr<WeakAttr>())
00338         return llvm::GlobalValue::WeakODRLinkage;
00339       if (RD->isDynamicClass())
00340         return CGM.getVTableLinkage(RD);
00341     }
00342 
00343     return llvm::GlobalValue::LinkOnceODRLinkage;
00344   }
00345 
00346   llvm_unreachable("Invalid linkage!");
00347 }
00348 
00349 // CanUseSingleInheritance - Return whether the given record decl has a "single, 
00350 // public, non-virtual base at offset zero (i.e. the derived class is dynamic 
00351 // iff the base is)", according to Itanium C++ ABI, 2.95p6b.
00352 static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
00353   // Check the number of bases.
00354   if (RD->getNumBases() != 1)
00355     return false;
00356   
00357   // Get the base.
00358   CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
00359   
00360   // Check that the base is not virtual.
00361   if (Base->isVirtual())
00362     return false;
00363   
00364   // Check that the base is public.
00365   if (Base->getAccessSpecifier() != AS_public)
00366     return false;
00367   
00368   // Check that the class is dynamic iff the base is.
00369   const CXXRecordDecl *BaseDecl = 
00370     cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
00371   if (!BaseDecl->isEmpty() && 
00372       BaseDecl->isDynamicClass() != RD->isDynamicClass())
00373     return false;
00374   
00375   return true;
00376 }
00377 
00378 void RTTIBuilder::BuildVTablePointer(const Type *Ty) {
00379   // abi::__class_type_info.
00380   static const char * const ClassTypeInfo =
00381     "_ZTVN10__cxxabiv117__class_type_infoE";
00382   // abi::__si_class_type_info.
00383   static const char * const SIClassTypeInfo =
00384     "_ZTVN10__cxxabiv120__si_class_type_infoE";
00385   // abi::__vmi_class_type_info.
00386   static const char * const VMIClassTypeInfo =
00387     "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
00388 
00389   const char *VTableName = 0;
00390 
00391   switch (Ty->getTypeClass()) {
00392 #define TYPE(Class, Base)
00393 #define ABSTRACT_TYPE(Class, Base)
00394 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
00395 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
00396 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
00397 #include "clang/AST/TypeNodes.def"
00398     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
00399 
00400   case Type::LValueReference:
00401   case Type::RValueReference:
00402     llvm_unreachable("References shouldn't get here");
00403 
00404   case Type::Builtin:
00405   // GCC treats vector and complex types as fundamental types.
00406   case Type::Vector:
00407   case Type::ExtVector:
00408   case Type::Complex:
00409   case Type::Atomic:
00410   // FIXME: GCC treats block pointers as fundamental types?!
00411   case Type::BlockPointer:
00412     // abi::__fundamental_type_info.
00413     VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
00414     break;
00415 
00416   case Type::ConstantArray:
00417   case Type::IncompleteArray:
00418   case Type::VariableArray:
00419     // abi::__array_type_info.
00420     VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
00421     break;
00422 
00423   case Type::FunctionNoProto:
00424   case Type::FunctionProto:
00425     // abi::__function_type_info.
00426     VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
00427     break;
00428 
00429   case Type::Enum:
00430     // abi::__enum_type_info.
00431     VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
00432     break;
00433 
00434   case Type::Record: {
00435     const CXXRecordDecl *RD = 
00436       cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
00437     
00438     if (!RD->hasDefinition() || !RD->getNumBases()) {
00439       VTableName = ClassTypeInfo;
00440     } else if (CanUseSingleInheritance(RD)) {
00441       VTableName = SIClassTypeInfo;
00442     } else {
00443       VTableName = VMIClassTypeInfo;
00444     }
00445     
00446     break;
00447   }
00448 
00449   case Type::ObjCObject:
00450     // Ignore protocol qualifiers.
00451     Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
00452 
00453     // Handle id and Class.
00454     if (isa<BuiltinType>(Ty)) {
00455       VTableName = ClassTypeInfo;
00456       break;
00457     }
00458 
00459     assert(isa<ObjCInterfaceType>(Ty));
00460     // Fall through.
00461 
00462   case Type::ObjCInterface:
00463     if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
00464       VTableName = SIClassTypeInfo;
00465     } else {
00466       VTableName = ClassTypeInfo;
00467     }
00468     break;
00469 
00470   case Type::ObjCObjectPointer:
00471   case Type::Pointer:
00472     // abi::__pointer_type_info.
00473     VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
00474     break;
00475 
00476   case Type::MemberPointer:
00477     // abi::__pointer_to_member_type_info.
00478     VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
00479     break;
00480   }
00481 
00482   llvm::Constant *VTable = 
00483     CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
00484     
00485   llvm::Type *PtrDiffTy = 
00486     CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
00487 
00488   // The vtable address point is 2.
00489   llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
00490   VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Two);
00491   VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
00492 
00493   Fields.push_back(VTable);
00494 }
00495 
00496 // maybeUpdateRTTILinkage - Will update the linkage of the RTTI data structures
00497 // from available_externally to the correct linkage if necessary. An example of
00498 // this is:
00499 //
00500 //   struct A {
00501 //     virtual void f();
00502 //   };
00503 //
00504 //   const std::type_info &g() {
00505 //     return typeid(A);
00506 //   }
00507 //
00508 //   void A::f() { }
00509 //
00510 // When we're generating the typeid(A) expression, we do not yet know that
00511 // A's key function is defined in this translation unit, so we will give the
00512 // typeinfo and typename structures available_externally linkage. When A::f
00513 // forces the vtable to be generated, we need to change the linkage of the
00514 // typeinfo and typename structs, otherwise we'll end up with undefined
00515 // externals when linking.
00516 static void 
00517 maybeUpdateRTTILinkage(CodeGenModule &CGM, llvm::GlobalVariable *GV,
00518                        QualType Ty) {
00519   // We're only interested in globals with available_externally linkage.
00520   if (!GV->hasAvailableExternallyLinkage())
00521     return;
00522 
00523   // Get the real linkage for the type.
00524   llvm::GlobalVariable::LinkageTypes Linkage = getTypeInfoLinkage(CGM, Ty);
00525 
00526   // If variable is supposed to have available_externally linkage, we don't
00527   // need to do anything.
00528   if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
00529     return;
00530 
00531   // Update the typeinfo linkage.
00532   GV->setLinkage(Linkage);
00533 
00534   // Get the typename global.
00535   SmallString<256> OutName;
00536   llvm::raw_svector_ostream Out(OutName);
00537   CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
00538   Out.flush();
00539   StringRef Name = OutName.str();
00540 
00541   llvm::GlobalVariable *TypeNameGV = CGM.getModule().getNamedGlobal(Name);
00542 
00543   assert(TypeNameGV->hasAvailableExternallyLinkage() &&
00544          "Type name has different linkage from type info!");
00545 
00546   // And update its linkage.
00547   TypeNameGV->setLinkage(Linkage);
00548 }
00549 
00550 llvm::Constant *RTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
00551   // We want to operate on the canonical type.
00552   Ty = CGM.getContext().getCanonicalType(Ty);
00553 
00554   // Check if we've already emitted an RTTI descriptor for this type.
00555   SmallString<256> OutName;
00556   llvm::raw_svector_ostream Out(OutName);
00557   CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
00558   Out.flush();
00559   StringRef Name = OutName.str();
00560 
00561   llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
00562   if (OldGV && !OldGV->isDeclaration()) {
00563     maybeUpdateRTTILinkage(CGM, OldGV, Ty);
00564 
00565     return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
00566   }
00567 
00568   // Check if there is already an external RTTI descriptor for this type.
00569   bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
00570   if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
00571     return GetAddrOfExternalRTTIDescriptor(Ty);
00572 
00573   // Emit the standard library with external linkage.
00574   llvm::GlobalVariable::LinkageTypes Linkage;
00575   if (IsStdLib)
00576     Linkage = llvm::GlobalValue::ExternalLinkage;
00577   else
00578     Linkage = getTypeInfoLinkage(CGM, Ty);
00579 
00580   // Add the vtable pointer.
00581   BuildVTablePointer(cast<Type>(Ty));
00582   
00583   // And the name.
00584   llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
00585 
00586   Fields.push_back(llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy));
00587 
00588   switch (Ty->getTypeClass()) {
00589 #define TYPE(Class, Base)
00590 #define ABSTRACT_TYPE(Class, Base)
00591 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
00592 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
00593 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
00594 #include "clang/AST/TypeNodes.def"
00595     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
00596 
00597   // GCC treats vector types as fundamental types.
00598   case Type::Builtin:
00599   case Type::Vector:
00600   case Type::ExtVector:
00601   case Type::Complex:
00602   case Type::BlockPointer:
00603     // Itanium C++ ABI 2.9.5p4:
00604     // abi::__fundamental_type_info adds no data members to std::type_info.
00605     break;
00606 
00607   case Type::LValueReference:
00608   case Type::RValueReference:
00609     llvm_unreachable("References shouldn't get here");
00610 
00611   case Type::ConstantArray:
00612   case Type::IncompleteArray:
00613   case Type::VariableArray:
00614     // Itanium C++ ABI 2.9.5p5:
00615     // abi::__array_type_info adds no data members to std::type_info.
00616     break;
00617 
00618   case Type::FunctionNoProto:
00619   case Type::FunctionProto:
00620     // Itanium C++ ABI 2.9.5p5:
00621     // abi::__function_type_info adds no data members to std::type_info.
00622     break;
00623 
00624   case Type::Enum:
00625     // Itanium C++ ABI 2.9.5p5:
00626     // abi::__enum_type_info adds no data members to std::type_info.
00627     break;
00628 
00629   case Type::Record: {
00630     const CXXRecordDecl *RD = 
00631       cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
00632     if (!RD->hasDefinition() || !RD->getNumBases()) {
00633       // We don't need to emit any fields.
00634       break;
00635     }
00636     
00637     if (CanUseSingleInheritance(RD))
00638       BuildSIClassTypeInfo(RD);
00639     else 
00640       BuildVMIClassTypeInfo(RD);
00641 
00642     break;
00643   }
00644 
00645   case Type::ObjCObject:
00646   case Type::ObjCInterface:
00647     BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
00648     break;
00649 
00650   case Type::ObjCObjectPointer:
00651     BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
00652     break; 
00653       
00654   case Type::Pointer:
00655     BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
00656     break;
00657 
00658   case Type::MemberPointer:
00659     BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
00660     break;
00661 
00662   case Type::Atomic:
00663     // No fields, at least for the moment.
00664     break;
00665   }
00666 
00667   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
00668 
00669   llvm::GlobalVariable *GV = 
00670     new llvm::GlobalVariable(CGM.getModule(), Init->getType(), 
00671                              /*Constant=*/true, Linkage, Init, Name);
00672   
00673   // If there's already an old global variable, replace it with the new one.
00674   if (OldGV) {
00675     GV->takeName(OldGV);
00676     llvm::Constant *NewPtr = 
00677       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
00678     OldGV->replaceAllUsesWith(NewPtr);
00679     OldGV->eraseFromParent();
00680   }
00681 
00682   // GCC only relies on the uniqueness of the type names, not the
00683   // type_infos themselves, so we can emit these as hidden symbols.
00684   // But don't do this if we're worried about strict visibility
00685   // compatibility.
00686   if (const RecordType *RT = dyn_cast<RecordType>(Ty)) {
00687     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
00688 
00689     CGM.setTypeVisibility(GV, RD, CodeGenModule::TVK_ForRTTI);
00690     CGM.setTypeVisibility(TypeName, RD, CodeGenModule::TVK_ForRTTIName);
00691   } else {
00692     Visibility TypeInfoVisibility = DefaultVisibility;
00693     if (CGM.getCodeGenOpts().HiddenWeakVTables &&
00694         Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
00695       TypeInfoVisibility = HiddenVisibility;
00696 
00697     // The type name should have the same visibility as the type itself.
00698     Visibility ExplicitVisibility = Ty->getVisibility();
00699     TypeName->setVisibility(CodeGenModule::
00700                             GetLLVMVisibility(ExplicitVisibility));
00701   
00702     TypeInfoVisibility = minVisibility(TypeInfoVisibility, Ty->getVisibility());
00703     GV->setVisibility(CodeGenModule::GetLLVMVisibility(TypeInfoVisibility));
00704   }
00705 
00706   GV->setUnnamedAddr(true);
00707 
00708   return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
00709 }
00710 
00711 /// ComputeQualifierFlags - Compute the pointer type info flags from the
00712 /// given qualifier.
00713 static unsigned ComputeQualifierFlags(Qualifiers Quals) {
00714   unsigned Flags = 0;
00715 
00716   if (Quals.hasConst())
00717     Flags |= RTTIBuilder::PTI_Const;
00718   if (Quals.hasVolatile())
00719     Flags |= RTTIBuilder::PTI_Volatile;
00720   if (Quals.hasRestrict())
00721     Flags |= RTTIBuilder::PTI_Restrict;
00722 
00723   return Flags;
00724 }
00725 
00726 /// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
00727 /// for the given Objective-C object type.
00728 void RTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
00729   // Drop qualifiers.
00730   const Type *T = OT->getBaseType().getTypePtr();
00731   assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
00732 
00733   // The builtin types are abi::__class_type_infos and don't require
00734   // extra fields.
00735   if (isa<BuiltinType>(T)) return;
00736 
00737   ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
00738   ObjCInterfaceDecl *Super = Class->getSuperClass();
00739 
00740   // Root classes are also __class_type_info.
00741   if (!Super) return;
00742 
00743   QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
00744 
00745   // Everything else is single inheritance.
00746   llvm::Constant *BaseTypeInfo = RTTIBuilder(CGM).BuildTypeInfo(SuperTy);
00747   Fields.push_back(BaseTypeInfo);
00748 }
00749 
00750 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
00751 /// inheritance, according to the Itanium C++ ABI, 2.95p6b.
00752 void RTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
00753   // Itanium C++ ABI 2.9.5p6b:
00754   // It adds to abi::__class_type_info a single member pointing to the 
00755   // type_info structure for the base type,
00756   llvm::Constant *BaseTypeInfo = 
00757     RTTIBuilder(CGM).BuildTypeInfo(RD->bases_begin()->getType());
00758   Fields.push_back(BaseTypeInfo);
00759 }
00760 
00761 namespace {
00762   /// SeenBases - Contains virtual and non-virtual bases seen when traversing
00763   /// a class hierarchy.
00764   struct SeenBases {
00765     llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
00766     llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
00767   };
00768 }
00769 
00770 /// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
00771 /// abi::__vmi_class_type_info.
00772 ///
00773 static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base, 
00774                                              SeenBases &Bases) {
00775   
00776   unsigned Flags = 0;
00777   
00778   const CXXRecordDecl *BaseDecl = 
00779     cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
00780   
00781   if (Base->isVirtual()) {
00782     if (Bases.VirtualBases.count(BaseDecl)) {
00783       // If this virtual base has been seen before, then the class is diamond
00784       // shaped.
00785       Flags |= RTTIBuilder::VMI_DiamondShaped;
00786     } else {
00787       if (Bases.NonVirtualBases.count(BaseDecl))
00788         Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
00789 
00790       // Mark the virtual base as seen.
00791       Bases.VirtualBases.insert(BaseDecl);
00792     }
00793   } else {
00794     if (Bases.NonVirtualBases.count(BaseDecl)) {
00795       // If this non-virtual base has been seen before, then the class has non-
00796       // diamond shaped repeated inheritance.
00797       Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
00798     } else {
00799       if (Bases.VirtualBases.count(BaseDecl))
00800         Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
00801         
00802       // Mark the non-virtual base as seen.
00803       Bases.NonVirtualBases.insert(BaseDecl);
00804     }
00805   }
00806 
00807   // Walk all bases.
00808   for (CXXRecordDecl::base_class_const_iterator I = BaseDecl->bases_begin(),
00809        E = BaseDecl->bases_end(); I != E; ++I) 
00810     Flags |= ComputeVMIClassTypeInfoFlags(I, Bases);
00811   
00812   return Flags;
00813 }
00814 
00815 static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
00816   unsigned Flags = 0;
00817   SeenBases Bases;
00818   
00819   // Walk all bases.
00820   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
00821        E = RD->bases_end(); I != E; ++I) 
00822     Flags |= ComputeVMIClassTypeInfoFlags(I, Bases);
00823   
00824   return Flags;
00825 }
00826 
00827 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
00828 /// classes with bases that do not satisfy the abi::__si_class_type_info 
00829 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
00830 void RTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
00831   llvm::Type *UnsignedIntLTy = 
00832     CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
00833   
00834   // Itanium C++ ABI 2.9.5p6c:
00835   //   __flags is a word with flags describing details about the class 
00836   //   structure, which may be referenced by using the __flags_masks 
00837   //   enumeration. These flags refer to both direct and indirect bases. 
00838   unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
00839   Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
00840 
00841   // Itanium C++ ABI 2.9.5p6c:
00842   //   __base_count is a word with the number of direct proper base class 
00843   //   descriptions that follow.
00844   Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
00845   
00846   if (!RD->getNumBases())
00847     return;
00848   
00849   llvm::Type *LongLTy = 
00850     CGM.getTypes().ConvertType(CGM.getContext().LongTy);
00851 
00852   // Now add the base class descriptions.
00853   
00854   // Itanium C++ ABI 2.9.5p6c:
00855   //   __base_info[] is an array of base class descriptions -- one for every 
00856   //   direct proper base. Each description is of the type:
00857   //
00858   //   struct abi::__base_class_type_info {
00859   //   public:
00860   //     const __class_type_info *__base_type;
00861   //     long __offset_flags;
00862   //
00863   //     enum __offset_flags_masks {
00864   //       __virtual_mask = 0x1,
00865   //       __public_mask = 0x2,
00866   //       __offset_shift = 8
00867   //     };
00868   //   };
00869   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
00870        E = RD->bases_end(); I != E; ++I) {
00871     const CXXBaseSpecifier *Base = I;
00872 
00873     // The __base_type member points to the RTTI for the base type.
00874     Fields.push_back(RTTIBuilder(CGM).BuildTypeInfo(Base->getType()));
00875 
00876     const CXXRecordDecl *BaseDecl = 
00877       cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
00878 
00879     int64_t OffsetFlags = 0;
00880     
00881     // All but the lower 8 bits of __offset_flags are a signed offset. 
00882     // For a non-virtual base, this is the offset in the object of the base
00883     // subobject. For a virtual base, this is the offset in the virtual table of
00884     // the virtual base offset for the virtual base referenced (negative).
00885     CharUnits Offset;
00886     if (Base->isVirtual())
00887       Offset = 
00888         CGM.getVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
00889     else {
00890       const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
00891       Offset = Layout.getBaseClassOffset(BaseDecl);
00892     };
00893     
00894     OffsetFlags = Offset.getQuantity() << 8;
00895     
00896     // The low-order byte of __offset_flags contains flags, as given by the 
00897     // masks from the enumeration __offset_flags_masks.
00898     if (Base->isVirtual())
00899       OffsetFlags |= BCTI_Virtual;
00900     if (Base->getAccessSpecifier() == AS_public)
00901       OffsetFlags |= BCTI_Public;
00902 
00903     Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
00904   }
00905 }
00906 
00907 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
00908 /// used for pointer types.
00909 void RTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {  
00910   Qualifiers Quals;
00911   QualType UnqualifiedPointeeTy = 
00912     CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
00913   
00914   // Itanium C++ ABI 2.9.5p7:
00915   //   __flags is a flag word describing the cv-qualification and other 
00916   //   attributes of the type pointed to
00917   unsigned Flags = ComputeQualifierFlags(Quals);
00918 
00919   // Itanium C++ ABI 2.9.5p7:
00920   //   When the abi::__pbase_type_info is for a direct or indirect pointer to an
00921   //   incomplete class type, the incomplete target type flag is set. 
00922   if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
00923     Flags |= PTI_Incomplete;
00924 
00925   llvm::Type *UnsignedIntLTy = 
00926     CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
00927   Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
00928   
00929   // Itanium C++ ABI 2.9.5p7:
00930   //  __pointee is a pointer to the std::type_info derivation for the 
00931   //  unqualified type being pointed to.
00932   llvm::Constant *PointeeTypeInfo = 
00933     RTTIBuilder(CGM).BuildTypeInfo(UnqualifiedPointeeTy);
00934   Fields.push_back(PointeeTypeInfo);
00935 }
00936 
00937 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info 
00938 /// struct, used for member pointer types.
00939 void RTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
00940   QualType PointeeTy = Ty->getPointeeType();
00941   
00942   Qualifiers Quals;
00943   QualType UnqualifiedPointeeTy = 
00944     CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
00945   
00946   // Itanium C++ ABI 2.9.5p7:
00947   //   __flags is a flag word describing the cv-qualification and other 
00948   //   attributes of the type pointed to.
00949   unsigned Flags = ComputeQualifierFlags(Quals);
00950 
00951   const RecordType *ClassType = cast<RecordType>(Ty->getClass());
00952 
00953   // Itanium C++ ABI 2.9.5p7:
00954   //   When the abi::__pbase_type_info is for a direct or indirect pointer to an
00955   //   incomplete class type, the incomplete target type flag is set. 
00956   if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
00957     Flags |= PTI_Incomplete;
00958 
00959   if (IsIncompleteClassType(ClassType))
00960     Flags |= PTI_ContainingClassIncomplete;
00961   
00962   llvm::Type *UnsignedIntLTy = 
00963     CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
00964   Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
00965   
00966   // Itanium C++ ABI 2.9.5p7:
00967   //   __pointee is a pointer to the std::type_info derivation for the 
00968   //   unqualified type being pointed to.
00969   llvm::Constant *PointeeTypeInfo = 
00970     RTTIBuilder(CGM).BuildTypeInfo(UnqualifiedPointeeTy);
00971   Fields.push_back(PointeeTypeInfo);
00972 
00973   // Itanium C++ ABI 2.9.5p9:
00974   //   __context is a pointer to an abi::__class_type_info corresponding to the
00975   //   class type containing the member pointed to 
00976   //   (e.g., the "A" in "int A::*").
00977   Fields.push_back(RTTIBuilder(CGM).BuildTypeInfo(QualType(ClassType, 0)));
00978 }
00979 
00980 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
00981                                                        bool ForEH) {
00982   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
00983   // FIXME: should we even be calling this method if RTTI is disabled
00984   // and it's not for EH?
00985   if (!ForEH && !getContext().getLangOpts().RTTI)
00986     return llvm::Constant::getNullValue(Int8PtrTy);
00987   
00988   if (ForEH && Ty->isObjCObjectPointerType() && !LangOpts.NeXTRuntime)
00989     return ObjCRuntime->GetEHType(Ty);
00990 
00991   return RTTIBuilder(*this).BuildTypeInfo(Ty);
00992 }
00993 
00994 void CodeGenModule::EmitFundamentalRTTIDescriptor(QualType Type) {
00995   QualType PointerType = Context.getPointerType(Type);
00996   QualType PointerTypeConst = Context.getPointerType(Type.withConst());
00997   RTTIBuilder(*this).BuildTypeInfo(Type, true);
00998   RTTIBuilder(*this).BuildTypeInfo(PointerType, true);
00999   RTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
01000 }
01001 
01002 void CodeGenModule::EmitFundamentalRTTIDescriptors() {
01003   QualType FundamentalTypes[] = { Context.VoidTy, Context.NullPtrTy,
01004                                   Context.BoolTy, Context.WCharTy,
01005                                   Context.CharTy, Context.UnsignedCharTy,
01006                                   Context.SignedCharTy, Context.ShortTy, 
01007                                   Context.UnsignedShortTy, Context.IntTy,
01008                                   Context.UnsignedIntTy, Context.LongTy, 
01009                                   Context.UnsignedLongTy, Context.LongLongTy, 
01010                                   Context.UnsignedLongLongTy, Context.FloatTy,
01011                                   Context.DoubleTy, Context.LongDoubleTy,
01012                                   Context.Char16Ty, Context.Char32Ty };
01013   for (unsigned i = 0; i < sizeof(FundamentalTypes)/sizeof(QualType); ++i)
01014     EmitFundamentalRTTIDescriptor(FundamentalTypes[i]);
01015 }