Home | History | Annotate | Download | only in CodeGen
      1 //===--- CGCXXRTTI.cpp - Emit LLVM Code for C++ RTTI descriptors ----------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This contains code dealing with C++ code generation of RTTI descriptors.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "CodeGenModule.h"
     15 #include "CGCXXABI.h"
     16 #include "CGObjCRuntime.h"
     17 #include "clang/AST/RecordLayout.h"
     18 #include "clang/AST/Type.h"
     19 #include "clang/Frontend/CodeGenOptions.h"
     20 
     21 using namespace clang;
     22 using namespace CodeGen;
     23 
     24 namespace {
     25 class RTTIBuilder {
     26   CodeGenModule &CGM;  // Per-module state.
     27   llvm::LLVMContext &VMContext;
     28 
     29   /// Fields - The fields of the RTTI descriptor currently being built.
     30   SmallVector<llvm::Constant *, 16> Fields;
     31 
     32   /// GetAddrOfTypeName - Returns the mangled type name of the given type.
     33   llvm::GlobalVariable *
     34   GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
     35 
     36   /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
     37   /// descriptor of the given type.
     38   llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
     39 
     40   /// BuildVTablePointer - Build the vtable pointer for the given type.
     41   void BuildVTablePointer(const Type *Ty);
     42 
     43   /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
     44   /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
     45   void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
     46 
     47   /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
     48   /// classes with bases that do not satisfy the abi::__si_class_type_info
     49   /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
     50   void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
     51 
     52   /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
     53   /// for pointer types.
     54   void BuildPointerTypeInfo(QualType PointeeTy);
     55 
     56   /// BuildObjCObjectTypeInfo - Build the appropriate kind of
     57   /// type_info for an object type.
     58   void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
     59 
     60   /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
     61   /// struct, used for member pointer types.
     62   void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
     63 
     64 public:
     65   RTTIBuilder(CodeGenModule &CGM) : CGM(CGM),
     66     VMContext(CGM.getModule().getContext()) { }
     67 
     68   // Pointer type info flags.
     69   enum {
     70     /// PTI_Const - Type has const qualifier.
     71     PTI_Const = 0x1,
     72 
     73     /// PTI_Volatile - Type has volatile qualifier.
     74     PTI_Volatile = 0x2,
     75 
     76     /// PTI_Restrict - Type has restrict qualifier.
     77     PTI_Restrict = 0x4,
     78 
     79     /// PTI_Incomplete - Type is incomplete.
     80     PTI_Incomplete = 0x8,
     81 
     82     /// PTI_ContainingClassIncomplete - Containing class is incomplete.
     83     /// (in pointer to member).
     84     PTI_ContainingClassIncomplete = 0x10
     85   };
     86 
     87   // VMI type info flags.
     88   enum {
     89     /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
     90     VMI_NonDiamondRepeat = 0x1,
     91 
     92     /// VMI_DiamondShaped - Class is diamond shaped.
     93     VMI_DiamondShaped = 0x2
     94   };
     95 
     96   // Base class type info flags.
     97   enum {
     98     /// BCTI_Virtual - Base class is virtual.
     99     BCTI_Virtual = 0x1,
    100 
    101     /// BCTI_Public - Base class is public.
    102     BCTI_Public = 0x2
    103   };
    104 
    105   /// BuildTypeInfo - Build the RTTI type info struct for the given type.
    106   ///
    107   /// \param Force - true to force the creation of this RTTI value
    108   llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
    109 };
    110 }
    111 
    112 llvm::GlobalVariable *
    113 RTTIBuilder::GetAddrOfTypeName(QualType Ty,
    114                                llvm::GlobalVariable::LinkageTypes Linkage) {
    115   SmallString<256> OutName;
    116   llvm::raw_svector_ostream Out(OutName);
    117   CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
    118   Out.flush();
    119   StringRef Name = OutName.str();
    120 
    121   // We know that the mangled name of the type starts at index 4 of the
    122   // mangled name of the typename, so we can just index into it in order to
    123   // get the mangled name of the type.
    124   llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
    125                                                             Name.substr(4));
    126 
    127   llvm::GlobalVariable *GV =
    128     CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
    129 
    130   GV->setInitializer(Init);
    131 
    132   return GV;
    133 }
    134 
    135 llvm::Constant *RTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
    136   // Mangle the RTTI name.
    137   SmallString<256> OutName;
    138   llvm::raw_svector_ostream Out(OutName);
    139   CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
    140   Out.flush();
    141   StringRef Name = OutName.str();
    142 
    143   // Look for an existing global.
    144   llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
    145 
    146   if (!GV) {
    147     // Create a new global variable.
    148     GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
    149                                   /*Constant=*/true,
    150                                   llvm::GlobalValue::ExternalLinkage, 0, Name);
    151   }
    152 
    153   return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
    154 }
    155 
    156 /// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
    157 /// info for that type is defined in the standard library.
    158 static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
    159   // Itanium C++ ABI 2.9.2:
    160   //   Basic type information (e.g. for "int", "bool", etc.) will be kept in
    161   //   the run-time support library. Specifically, the run-time support
    162   //   library should contain type_info objects for the types X, X* and
    163   //   X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
    164   //   unsigned char, signed char, short, unsigned short, int, unsigned int,
    165   //   long, unsigned long, long long, unsigned long long, float, double,
    166   //   long double, char16_t, char32_t, and the IEEE 754r decimal and
    167   //   half-precision floating point types.
    168   switch (Ty->getKind()) {
    169     case BuiltinType::Void:
    170     case BuiltinType::NullPtr:
    171     case BuiltinType::Bool:
    172     case BuiltinType::WChar_S:
    173     case BuiltinType::WChar_U:
    174     case BuiltinType::Char_U:
    175     case BuiltinType::Char_S:
    176     case BuiltinType::UChar:
    177     case BuiltinType::SChar:
    178     case BuiltinType::Short:
    179     case BuiltinType::UShort:
    180     case BuiltinType::Int:
    181     case BuiltinType::UInt:
    182     case BuiltinType::Long:
    183     case BuiltinType::ULong:
    184     case BuiltinType::LongLong:
    185     case BuiltinType::ULongLong:
    186     case BuiltinType::Half:
    187     case BuiltinType::Float:
    188     case BuiltinType::Double:
    189     case BuiltinType::LongDouble:
    190     case BuiltinType::Char16:
    191     case BuiltinType::Char32:
    192     case BuiltinType::Int128:
    193     case BuiltinType::UInt128:
    194     case BuiltinType::OCLImage1d:
    195     case BuiltinType::OCLImage1dArray:
    196     case BuiltinType::OCLImage1dBuffer:
    197     case BuiltinType::OCLImage2d:
    198     case BuiltinType::OCLImage2dArray:
    199     case BuiltinType::OCLImage3d:
    200     case BuiltinType::OCLSampler:
    201     case BuiltinType::OCLEvent:
    202       return true;
    203 
    204     case BuiltinType::Dependent:
    205 #define BUILTIN_TYPE(Id, SingletonId)
    206 #define PLACEHOLDER_TYPE(Id, SingletonId) \
    207     case BuiltinType::Id:
    208 #include "clang/AST/BuiltinTypes.def"
    209       llvm_unreachable("asking for RRTI for a placeholder type!");
    210 
    211     case BuiltinType::ObjCId:
    212     case BuiltinType::ObjCClass:
    213     case BuiltinType::ObjCSel:
    214       llvm_unreachable("FIXME: Objective-C types are unsupported!");
    215   }
    216 
    217   llvm_unreachable("Invalid BuiltinType Kind!");
    218 }
    219 
    220 static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
    221   QualType PointeeTy = PointerTy->getPointeeType();
    222   const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
    223   if (!BuiltinTy)
    224     return false;
    225 
    226   // Check the qualifiers.
    227   Qualifiers Quals = PointeeTy.getQualifiers();
    228   Quals.removeConst();
    229 
    230   if (!Quals.empty())
    231     return false;
    232 
    233   return TypeInfoIsInStandardLibrary(BuiltinTy);
    234 }
    235 
    236 /// IsStandardLibraryRTTIDescriptor - Returns whether the type
    237 /// information for the given type exists in the standard library.
    238 static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
    239   // Type info for builtin types is defined in the standard library.
    240   if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
    241     return TypeInfoIsInStandardLibrary(BuiltinTy);
    242 
    243   // Type info for some pointer types to builtin types is defined in the
    244   // standard library.
    245   if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
    246     return TypeInfoIsInStandardLibrary(PointerTy);
    247 
    248   return false;
    249 }
    250 
    251 /// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
    252 /// the given type exists somewhere else, and that we should not emit the type
    253 /// information in this translation unit.  Assumes that it is not a
    254 /// standard-library type.
    255 static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
    256                                             QualType Ty) {
    257   ASTContext &Context = CGM.getContext();
    258 
    259   // If RTTI is disabled, assume it might be disabled in the
    260   // translation unit that defines any potential key function, too.
    261   if (!Context.getLangOpts().RTTI) return false;
    262 
    263   if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
    264     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
    265     if (!RD->hasDefinition())
    266       return false;
    267 
    268     if (!RD->isDynamicClass())
    269       return false;
    270 
    271     // FIXME: this may need to be reconsidered if the key function
    272     // changes.
    273     return CGM.getVTables().isVTableExternal(RD);
    274   }
    275 
    276   return false;
    277 }
    278 
    279 /// IsIncompleteClassType - Returns whether the given record type is incomplete.
    280 static bool IsIncompleteClassType(const RecordType *RecordTy) {
    281   return !RecordTy->getDecl()->isCompleteDefinition();
    282 }
    283 
    284 /// ContainsIncompleteClassType - Returns whether the given type contains an
    285 /// incomplete class type. This is true if
    286 ///
    287 ///   * The given type is an incomplete class type.
    288 ///   * The given type is a pointer type whose pointee type contains an
    289 ///     incomplete class type.
    290 ///   * The given type is a member pointer type whose class is an incomplete
    291 ///     class type.
    292 ///   * The given type is a member pointer type whoise pointee type contains an
    293 ///     incomplete class type.
    294 /// is an indirect or direct pointer to an incomplete class type.
    295 static bool ContainsIncompleteClassType(QualType Ty) {
    296   if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
    297     if (IsIncompleteClassType(RecordTy))
    298       return true;
    299   }
    300 
    301   if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
    302     return ContainsIncompleteClassType(PointerTy->getPointeeType());
    303 
    304   if (const MemberPointerType *MemberPointerTy =
    305       dyn_cast<MemberPointerType>(Ty)) {
    306     // Check if the class type is incomplete.
    307     const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
    308     if (IsIncompleteClassType(ClassType))
    309       return true;
    310 
    311     return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
    312   }
    313 
    314   return false;
    315 }
    316 
    317 /// getTypeInfoLinkage - Return the linkage that the type info and type info
    318 /// name constants should have for the given type.
    319 static llvm::GlobalVariable::LinkageTypes
    320 getTypeInfoLinkage(CodeGenModule &CGM, QualType Ty) {
    321   // Itanium C++ ABI 2.9.5p7:
    322   //   In addition, it and all of the intermediate abi::__pointer_type_info
    323   //   structs in the chain down to the abi::__class_type_info for the
    324   //   incomplete class type must be prevented from resolving to the
    325   //   corresponding type_info structs for the complete class type, possibly
    326   //   by making them local static objects. Finally, a dummy class RTTI is
    327   //   generated for the incomplete type that will not resolve to the final
    328   //   complete class RTTI (because the latter need not exist), possibly by
    329   //   making it a local static object.
    330   if (ContainsIncompleteClassType(Ty))
    331     return llvm::GlobalValue::InternalLinkage;
    332 
    333   switch (Ty->getLinkage()) {
    334   case NoLinkage:
    335   case InternalLinkage:
    336   case UniqueExternalLinkage:
    337     return llvm::GlobalValue::InternalLinkage;
    338 
    339   case ExternalLinkage:
    340     if (!CGM.getLangOpts().RTTI) {
    341       // RTTI is not enabled, which means that this type info struct is going
    342       // to be used for exception handling. Give it linkonce_odr linkage.
    343       return llvm::GlobalValue::LinkOnceODRLinkage;
    344     }
    345 
    346     if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
    347       const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
    348       if (RD->hasAttr<WeakAttr>())
    349         return llvm::GlobalValue::WeakODRLinkage;
    350       if (RD->isDynamicClass())
    351         return CGM.getVTableLinkage(RD);
    352     }
    353 
    354     return llvm::GlobalValue::LinkOnceODRLinkage;
    355   }
    356 
    357   llvm_unreachable("Invalid linkage!");
    358 }
    359 
    360 // CanUseSingleInheritance - Return whether the given record decl has a "single,
    361 // public, non-virtual base at offset zero (i.e. the derived class is dynamic
    362 // iff the base is)", according to Itanium C++ ABI, 2.95p6b.
    363 static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
    364   // Check the number of bases.
    365   if (RD->getNumBases() != 1)
    366     return false;
    367 
    368   // Get the base.
    369   CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
    370 
    371   // Check that the base is not virtual.
    372   if (Base->isVirtual())
    373     return false;
    374 
    375   // Check that the base is public.
    376   if (Base->getAccessSpecifier() != AS_public)
    377     return false;
    378 
    379   // Check that the class is dynamic iff the base is.
    380   const CXXRecordDecl *BaseDecl =
    381     cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
    382   if (!BaseDecl->isEmpty() &&
    383       BaseDecl->isDynamicClass() != RD->isDynamicClass())
    384     return false;
    385 
    386   return true;
    387 }
    388 
    389 void RTTIBuilder::BuildVTablePointer(const Type *Ty) {
    390   // abi::__class_type_info.
    391   static const char * const ClassTypeInfo =
    392     "_ZTVN10__cxxabiv117__class_type_infoE";
    393   // abi::__si_class_type_info.
    394   static const char * const SIClassTypeInfo =
    395     "_ZTVN10__cxxabiv120__si_class_type_infoE";
    396   // abi::__vmi_class_type_info.
    397   static const char * const VMIClassTypeInfo =
    398     "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
    399 
    400   const char *VTableName = 0;
    401 
    402   switch (Ty->getTypeClass()) {
    403 #define TYPE(Class, Base)
    404 #define ABSTRACT_TYPE(Class, Base)
    405 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
    406 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
    407 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
    408 #include "clang/AST/TypeNodes.def"
    409     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
    410 
    411   case Type::LValueReference:
    412   case Type::RValueReference:
    413     llvm_unreachable("References shouldn't get here");
    414 
    415   case Type::Builtin:
    416   // GCC treats vector and complex types as fundamental types.
    417   case Type::Vector:
    418   case Type::ExtVector:
    419   case Type::Complex:
    420   case Type::Atomic:
    421   // FIXME: GCC treats block pointers as fundamental types?!
    422   case Type::BlockPointer:
    423     // abi::__fundamental_type_info.
    424     VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
    425     break;
    426 
    427   case Type::ConstantArray:
    428   case Type::IncompleteArray:
    429   case Type::VariableArray:
    430     // abi::__array_type_info.
    431     VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
    432     break;
    433 
    434   case Type::FunctionNoProto:
    435   case Type::FunctionProto:
    436     // abi::__function_type_info.
    437     VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
    438     break;
    439 
    440   case Type::Enum:
    441     // abi::__enum_type_info.
    442     VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
    443     break;
    444 
    445   case Type::Record: {
    446     const CXXRecordDecl *RD =
    447       cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
    448 
    449     if (!RD->hasDefinition() || !RD->getNumBases()) {
    450       VTableName = ClassTypeInfo;
    451     } else if (CanUseSingleInheritance(RD)) {
    452       VTableName = SIClassTypeInfo;
    453     } else {
    454       VTableName = VMIClassTypeInfo;
    455     }
    456 
    457     break;
    458   }
    459 
    460   case Type::ObjCObject:
    461     // Ignore protocol qualifiers.
    462     Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
    463 
    464     // Handle id and Class.
    465     if (isa<BuiltinType>(Ty)) {
    466       VTableName = ClassTypeInfo;
    467       break;
    468     }
    469 
    470     assert(isa<ObjCInterfaceType>(Ty));
    471     // Fall through.
    472 
    473   case Type::ObjCInterface:
    474     if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
    475       VTableName = SIClassTypeInfo;
    476     } else {
    477       VTableName = ClassTypeInfo;
    478     }
    479     break;
    480 
    481   case Type::ObjCObjectPointer:
    482   case Type::Pointer:
    483     // abi::__pointer_type_info.
    484     VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
    485     break;
    486 
    487   case Type::MemberPointer:
    488     // abi::__pointer_to_member_type_info.
    489     VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
    490     break;
    491   }
    492 
    493   llvm::Constant *VTable =
    494     CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
    495 
    496   llvm::Type *PtrDiffTy =
    497     CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
    498 
    499   // The vtable address point is 2.
    500   llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
    501   VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Two);
    502   VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
    503 
    504   Fields.push_back(VTable);
    505 }
    506 
    507 // maybeUpdateRTTILinkage - Will update the linkage of the RTTI data structures
    508 // from available_externally to the correct linkage if necessary. An example of
    509 // this is:
    510 //
    511 //   struct A {
    512 //     virtual void f();
    513 //   };
    514 //
    515 //   const std::type_info &g() {
    516 //     return typeid(A);
    517 //   }
    518 //
    519 //   void A::f() { }
    520 //
    521 // When we're generating the typeid(A) expression, we do not yet know that
    522 // A's key function is defined in this translation unit, so we will give the
    523 // typeinfo and typename structures available_externally linkage. When A::f
    524 // forces the vtable to be generated, we need to change the linkage of the
    525 // typeinfo and typename structs, otherwise we'll end up with undefined
    526 // externals when linking.
    527 static void
    528 maybeUpdateRTTILinkage(CodeGenModule &CGM, llvm::GlobalVariable *GV,
    529                        QualType Ty) {
    530   // We're only interested in globals with available_externally linkage.
    531   if (!GV->hasAvailableExternallyLinkage())
    532     return;
    533 
    534   // Get the real linkage for the type.
    535   llvm::GlobalVariable::LinkageTypes Linkage = getTypeInfoLinkage(CGM, Ty);
    536 
    537   // If variable is supposed to have available_externally linkage, we don't
    538   // need to do anything.
    539   if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
    540     return;
    541 
    542   // Update the typeinfo linkage.
    543   GV->setLinkage(Linkage);
    544 
    545   // Get the typename global.
    546   SmallString<256> OutName;
    547   llvm::raw_svector_ostream Out(OutName);
    548   CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
    549   Out.flush();
    550   StringRef Name = OutName.str();
    551 
    552   llvm::GlobalVariable *TypeNameGV = CGM.getModule().getNamedGlobal(Name);
    553 
    554   assert(TypeNameGV->hasAvailableExternallyLinkage() &&
    555          "Type name has different linkage from type info!");
    556 
    557   // And update its linkage.
    558   TypeNameGV->setLinkage(Linkage);
    559 }
    560 
    561 llvm::Constant *RTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
    562   // We want to operate on the canonical type.
    563   Ty = CGM.getContext().getCanonicalType(Ty);
    564 
    565   // Check if we've already emitted an RTTI descriptor for this type.
    566   SmallString<256> OutName;
    567   llvm::raw_svector_ostream Out(OutName);
    568   CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
    569   Out.flush();
    570   StringRef Name = OutName.str();
    571 
    572   llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
    573   if (OldGV && !OldGV->isDeclaration()) {
    574     maybeUpdateRTTILinkage(CGM, OldGV, Ty);
    575 
    576     return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
    577   }
    578 
    579   // Check if there is already an external RTTI descriptor for this type.
    580   bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
    581   if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
    582     return GetAddrOfExternalRTTIDescriptor(Ty);
    583 
    584   // Emit the standard library with external linkage.
    585   llvm::GlobalVariable::LinkageTypes Linkage;
    586   if (IsStdLib)
    587     Linkage = llvm::GlobalValue::ExternalLinkage;
    588   else
    589     Linkage = getTypeInfoLinkage(CGM, Ty);
    590 
    591   // Add the vtable pointer.
    592   BuildVTablePointer(cast<Type>(Ty));
    593 
    594   // And the name.
    595   llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
    596 
    597   Fields.push_back(llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy));
    598 
    599   switch (Ty->getTypeClass()) {
    600 #define TYPE(Class, Base)
    601 #define ABSTRACT_TYPE(Class, Base)
    602 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
    603 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
    604 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
    605 #include "clang/AST/TypeNodes.def"
    606     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
    607 
    608   // GCC treats vector types as fundamental types.
    609   case Type::Builtin:
    610   case Type::Vector:
    611   case Type::ExtVector:
    612   case Type::Complex:
    613   case Type::BlockPointer:
    614     // Itanium C++ ABI 2.9.5p4:
    615     // abi::__fundamental_type_info adds no data members to std::type_info.
    616     break;
    617 
    618   case Type::LValueReference:
    619   case Type::RValueReference:
    620     llvm_unreachable("References shouldn't get here");
    621 
    622   case Type::ConstantArray:
    623   case Type::IncompleteArray:
    624   case Type::VariableArray:
    625     // Itanium C++ ABI 2.9.5p5:
    626     // abi::__array_type_info adds no data members to std::type_info.
    627     break;
    628 
    629   case Type::FunctionNoProto:
    630   case Type::FunctionProto:
    631     // Itanium C++ ABI 2.9.5p5:
    632     // abi::__function_type_info adds no data members to std::type_info.
    633     break;
    634 
    635   case Type::Enum:
    636     // Itanium C++ ABI 2.9.5p5:
    637     // abi::__enum_type_info adds no data members to std::type_info.
    638     break;
    639 
    640   case Type::Record: {
    641     const CXXRecordDecl *RD =
    642       cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
    643     if (!RD->hasDefinition() || !RD->getNumBases()) {
    644       // We don't need to emit any fields.
    645       break;
    646     }
    647 
    648     if (CanUseSingleInheritance(RD))
    649       BuildSIClassTypeInfo(RD);
    650     else
    651       BuildVMIClassTypeInfo(RD);
    652 
    653     break;
    654   }
    655 
    656   case Type::ObjCObject:
    657   case Type::ObjCInterface:
    658     BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
    659     break;
    660 
    661   case Type::ObjCObjectPointer:
    662     BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
    663     break;
    664 
    665   case Type::Pointer:
    666     BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
    667     break;
    668 
    669   case Type::MemberPointer:
    670     BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
    671     break;
    672 
    673   case Type::Atomic:
    674     // No fields, at least for the moment.
    675     break;
    676   }
    677 
    678   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
    679 
    680   llvm::GlobalVariable *GV =
    681     new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
    682                              /*Constant=*/true, Linkage, Init, Name);
    683 
    684   // If there's already an old global variable, replace it with the new one.
    685   if (OldGV) {
    686     GV->takeName(OldGV);
    687     llvm::Constant *NewPtr =
    688       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
    689     OldGV->replaceAllUsesWith(NewPtr);
    690     OldGV->eraseFromParent();
    691   }
    692 
    693   // GCC only relies on the uniqueness of the type names, not the
    694   // type_infos themselves, so we can emit these as hidden symbols.
    695   // But don't do this if we're worried about strict visibility
    696   // compatibility.
    697   if (const RecordType *RT = dyn_cast<RecordType>(Ty)) {
    698     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
    699 
    700     CGM.setTypeVisibility(GV, RD, CodeGenModule::TVK_ForRTTI);
    701     CGM.setTypeVisibility(TypeName, RD, CodeGenModule::TVK_ForRTTIName);
    702   } else {
    703     Visibility TypeInfoVisibility = DefaultVisibility;
    704     if (CGM.getCodeGenOpts().HiddenWeakVTables &&
    705         Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
    706       TypeInfoVisibility = HiddenVisibility;
    707 
    708     // The type name should have the same visibility as the type itself.
    709     Visibility ExplicitVisibility = Ty->getVisibility();
    710     TypeName->setVisibility(CodeGenModule::
    711                             GetLLVMVisibility(ExplicitVisibility));
    712 
    713     TypeInfoVisibility = minVisibility(TypeInfoVisibility, Ty->getVisibility());
    714     GV->setVisibility(CodeGenModule::GetLLVMVisibility(TypeInfoVisibility));
    715   }
    716 
    717   GV->setUnnamedAddr(true);
    718 
    719   return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
    720 }
    721 
    722 /// ComputeQualifierFlags - Compute the pointer type info flags from the
    723 /// given qualifier.
    724 static unsigned ComputeQualifierFlags(Qualifiers Quals) {
    725   unsigned Flags = 0;
    726 
    727   if (Quals.hasConst())
    728     Flags |= RTTIBuilder::PTI_Const;
    729   if (Quals.hasVolatile())
    730     Flags |= RTTIBuilder::PTI_Volatile;
    731   if (Quals.hasRestrict())
    732     Flags |= RTTIBuilder::PTI_Restrict;
    733 
    734   return Flags;
    735 }
    736 
    737 /// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
    738 /// for the given Objective-C object type.
    739 void RTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
    740   // Drop qualifiers.
    741   const Type *T = OT->getBaseType().getTypePtr();
    742   assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
    743 
    744   // The builtin types are abi::__class_type_infos and don't require
    745   // extra fields.
    746   if (isa<BuiltinType>(T)) return;
    747 
    748   ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
    749   ObjCInterfaceDecl *Super = Class->getSuperClass();
    750 
    751   // Root classes are also __class_type_info.
    752   if (!Super) return;
    753 
    754   QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
    755 
    756   // Everything else is single inheritance.
    757   llvm::Constant *BaseTypeInfo = RTTIBuilder(CGM).BuildTypeInfo(SuperTy);
    758   Fields.push_back(BaseTypeInfo);
    759 }
    760 
    761 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
    762 /// inheritance, according to the Itanium C++ ABI, 2.95p6b.
    763 void RTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
    764   // Itanium C++ ABI 2.9.5p6b:
    765   // It adds to abi::__class_type_info a single member pointing to the
    766   // type_info structure for the base type,
    767   llvm::Constant *BaseTypeInfo =
    768     RTTIBuilder(CGM).BuildTypeInfo(RD->bases_begin()->getType());
    769   Fields.push_back(BaseTypeInfo);
    770 }
    771 
    772 namespace {
    773   /// SeenBases - Contains virtual and non-virtual bases seen when traversing
    774   /// a class hierarchy.
    775   struct SeenBases {
    776     llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
    777     llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
    778   };
    779 }
    780 
    781 /// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
    782 /// abi::__vmi_class_type_info.
    783 ///
    784 static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
    785                                              SeenBases &Bases) {
    786 
    787   unsigned Flags = 0;
    788 
    789   const CXXRecordDecl *BaseDecl =
    790     cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
    791 
    792   if (Base->isVirtual()) {
    793     // Mark the virtual base as seen.
    794     if (!Bases.VirtualBases.insert(BaseDecl)) {
    795       // If this virtual base has been seen before, then the class is diamond
    796       // shaped.
    797       Flags |= RTTIBuilder::VMI_DiamondShaped;
    798     } else {
    799       if (Bases.NonVirtualBases.count(BaseDecl))
    800         Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
    801     }
    802   } else {
    803     // Mark the non-virtual base as seen.
    804     if (!Bases.NonVirtualBases.insert(BaseDecl)) {
    805       // If this non-virtual base has been seen before, then the class has non-
    806       // diamond shaped repeated inheritance.
    807       Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
    808     } else {
    809       if (Bases.VirtualBases.count(BaseDecl))
    810         Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
    811     }
    812   }
    813 
    814   // Walk all bases.
    815   for (CXXRecordDecl::base_class_const_iterator I = BaseDecl->bases_begin(),
    816        E = BaseDecl->bases_end(); I != E; ++I)
    817     Flags |= ComputeVMIClassTypeInfoFlags(I, Bases);
    818 
    819   return Flags;
    820 }
    821 
    822 static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
    823   unsigned Flags = 0;
    824   SeenBases Bases;
    825 
    826   // Walk all bases.
    827   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
    828        E = RD->bases_end(); I != E; ++I)
    829     Flags |= ComputeVMIClassTypeInfoFlags(I, Bases);
    830 
    831   return Flags;
    832 }
    833 
    834 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
    835 /// classes with bases that do not satisfy the abi::__si_class_type_info
    836 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
    837 void RTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
    838   llvm::Type *UnsignedIntLTy =
    839     CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
    840 
    841   // Itanium C++ ABI 2.9.5p6c:
    842   //   __flags is a word with flags describing details about the class
    843   //   structure, which may be referenced by using the __flags_masks
    844   //   enumeration. These flags refer to both direct and indirect bases.
    845   unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
    846   Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
    847 
    848   // Itanium C++ ABI 2.9.5p6c:
    849   //   __base_count is a word with the number of direct proper base class
    850   //   descriptions that follow.
    851   Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
    852 
    853   if (!RD->getNumBases())
    854     return;
    855 
    856   llvm::Type *LongLTy =
    857     CGM.getTypes().ConvertType(CGM.getContext().LongTy);
    858 
    859   // Now add the base class descriptions.
    860 
    861   // Itanium C++ ABI 2.9.5p6c:
    862   //   __base_info[] is an array of base class descriptions -- one for every
    863   //   direct proper base. Each description is of the type:
    864   //
    865   //   struct abi::__base_class_type_info {
    866   //   public:
    867   //     const __class_type_info *__base_type;
    868   //     long __offset_flags;
    869   //
    870   //     enum __offset_flags_masks {
    871   //       __virtual_mask = 0x1,
    872   //       __public_mask = 0x2,
    873   //       __offset_shift = 8
    874   //     };
    875   //   };
    876   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
    877        E = RD->bases_end(); I != E; ++I) {
    878     const CXXBaseSpecifier *Base = I;
    879 
    880     // The __base_type member points to the RTTI for the base type.
    881     Fields.push_back(RTTIBuilder(CGM).BuildTypeInfo(Base->getType()));
    882 
    883     const CXXRecordDecl *BaseDecl =
    884       cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
    885 
    886     int64_t OffsetFlags = 0;
    887 
    888     // All but the lower 8 bits of __offset_flags are a signed offset.
    889     // For a non-virtual base, this is the offset in the object of the base
    890     // subobject. For a virtual base, this is the offset in the virtual table of
    891     // the virtual base offset for the virtual base referenced (negative).
    892     CharUnits Offset;
    893     if (Base->isVirtual())
    894       Offset =
    895         CGM.getVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
    896     else {
    897       const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
    898       Offset = Layout.getBaseClassOffset(BaseDecl);
    899     };
    900 
    901     OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
    902 
    903     // The low-order byte of __offset_flags contains flags, as given by the
    904     // masks from the enumeration __offset_flags_masks.
    905     if (Base->isVirtual())
    906       OffsetFlags |= BCTI_Virtual;
    907     if (Base->getAccessSpecifier() == AS_public)
    908       OffsetFlags |= BCTI_Public;
    909 
    910     Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
    911   }
    912 }
    913 
    914 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
    915 /// used for pointer types.
    916 void RTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
    917   Qualifiers Quals;
    918   QualType UnqualifiedPointeeTy =
    919     CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
    920 
    921   // Itanium C++ ABI 2.9.5p7:
    922   //   __flags is a flag word describing the cv-qualification and other
    923   //   attributes of the type pointed to
    924   unsigned Flags = ComputeQualifierFlags(Quals);
    925 
    926   // Itanium C++ ABI 2.9.5p7:
    927   //   When the abi::__pbase_type_info is for a direct or indirect pointer to an
    928   //   incomplete class type, the incomplete target type flag is set.
    929   if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
    930     Flags |= PTI_Incomplete;
    931 
    932   llvm::Type *UnsignedIntLTy =
    933     CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
    934   Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
    935 
    936   // Itanium C++ ABI 2.9.5p7:
    937   //  __pointee is a pointer to the std::type_info derivation for the
    938   //  unqualified type being pointed to.
    939   llvm::Constant *PointeeTypeInfo =
    940     RTTIBuilder(CGM).BuildTypeInfo(UnqualifiedPointeeTy);
    941   Fields.push_back(PointeeTypeInfo);
    942 }
    943 
    944 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
    945 /// struct, used for member pointer types.
    946 void RTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
    947   QualType PointeeTy = Ty->getPointeeType();
    948 
    949   Qualifiers Quals;
    950   QualType UnqualifiedPointeeTy =
    951     CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
    952 
    953   // Itanium C++ ABI 2.9.5p7:
    954   //   __flags is a flag word describing the cv-qualification and other
    955   //   attributes of the type pointed to.
    956   unsigned Flags = ComputeQualifierFlags(Quals);
    957 
    958   const RecordType *ClassType = cast<RecordType>(Ty->getClass());
    959 
    960   // Itanium C++ ABI 2.9.5p7:
    961   //   When the abi::__pbase_type_info is for a direct or indirect pointer to an
    962   //   incomplete class type, the incomplete target type flag is set.
    963   if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
    964     Flags |= PTI_Incomplete;
    965 
    966   if (IsIncompleteClassType(ClassType))
    967     Flags |= PTI_ContainingClassIncomplete;
    968 
    969   llvm::Type *UnsignedIntLTy =
    970     CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
    971   Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
    972 
    973   // Itanium C++ ABI 2.9.5p7:
    974   //   __pointee is a pointer to the std::type_info derivation for the
    975   //   unqualified type being pointed to.
    976   llvm::Constant *PointeeTypeInfo =
    977     RTTIBuilder(CGM).BuildTypeInfo(UnqualifiedPointeeTy);
    978   Fields.push_back(PointeeTypeInfo);
    979 
    980   // Itanium C++ ABI 2.9.5p9:
    981   //   __context is a pointer to an abi::__class_type_info corresponding to the
    982   //   class type containing the member pointed to
    983   //   (e.g., the "A" in "int A::*").
    984   Fields.push_back(RTTIBuilder(CGM).BuildTypeInfo(QualType(ClassType, 0)));
    985 }
    986 
    987 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
    988                                                        bool ForEH) {
    989   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
    990   // FIXME: should we even be calling this method if RTTI is disabled
    991   // and it's not for EH?
    992   if (!ForEH && !getLangOpts().RTTI)
    993     return llvm::Constant::getNullValue(Int8PtrTy);
    994 
    995   if (ForEH && Ty->isObjCObjectPointerType() &&
    996       LangOpts.ObjCRuntime.isGNUFamily())
    997     return ObjCRuntime->GetEHType(Ty);
    998 
    999   return RTTIBuilder(*this).BuildTypeInfo(Ty);
   1000 }
   1001 
   1002 void CodeGenModule::EmitFundamentalRTTIDescriptor(QualType Type) {
   1003   QualType PointerType = Context.getPointerType(Type);
   1004   QualType PointerTypeConst = Context.getPointerType(Type.withConst());
   1005   RTTIBuilder(*this).BuildTypeInfo(Type, true);
   1006   RTTIBuilder(*this).BuildTypeInfo(PointerType, true);
   1007   RTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
   1008 }
   1009 
   1010 void CodeGenModule::EmitFundamentalRTTIDescriptors() {
   1011   QualType FundamentalTypes[] = { Context.VoidTy, Context.NullPtrTy,
   1012                                   Context.BoolTy, Context.WCharTy,
   1013                                   Context.CharTy, Context.UnsignedCharTy,
   1014                                   Context.SignedCharTy, Context.ShortTy,
   1015                                   Context.UnsignedShortTy, Context.IntTy,
   1016                                   Context.UnsignedIntTy, Context.LongTy,
   1017                                   Context.UnsignedLongTy, Context.LongLongTy,
   1018                                   Context.UnsignedLongLongTy, Context.FloatTy,
   1019                                   Context.DoubleTy, Context.LongDoubleTy,
   1020                                   Context.Char16Ty, Context.Char32Ty };
   1021   for (unsigned i = 0; i < sizeof(FundamentalTypes)/sizeof(QualType); ++i)
   1022     EmitFundamentalRTTIDescriptor(FundamentalTypes[i]);
   1023 }
   1024