1 //===--- CGCXXRTTI.cpp - Emit LLVM Code for C++ RTTI descriptors ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code dealing with C++ code generation of RTTI descriptors.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenModule.h"
16 #include "clang/AST/RecordLayout.h"
17 #include "clang/AST/Type.h"
18 #include "clang/Frontend/CodeGenOptions.h"
19 #include "CGObjCRuntime.h"
21 using namespace clang;
22 using namespace CodeGen;
26 CodeGenModule &CGM; // Per-module state.
27 llvm::LLVMContext &VMContext;
29 /// Fields - The fields of the RTTI descriptor currently being built.
30 SmallVector<llvm::Constant *, 16> Fields;
32 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
33 llvm::GlobalVariable *
34 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
36 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
37 /// descriptor of the given type.
38 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
40 /// BuildVTablePointer - Build the vtable pointer for the given type.
41 void BuildVTablePointer(const Type *Ty);
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);
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);
52 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
53 /// for pointer types.
54 void BuildPointerTypeInfo(QualType PointeeTy);
56 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
57 /// type_info for an object type.
58 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
60 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
61 /// struct, used for member pointer types.
62 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
65 RTTIBuilder(CodeGenModule &CGM) : CGM(CGM),
66 VMContext(CGM.getModule().getContext()) { }
68 // Pointer type info flags.
70 /// PTI_Const - Type has const qualifier.
73 /// PTI_Volatile - Type has volatile qualifier.
76 /// PTI_Restrict - Type has restrict qualifier.
79 /// PTI_Incomplete - Type is incomplete.
82 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
83 /// (in pointer to member).
84 PTI_ContainingClassIncomplete = 0x10
87 // VMI type info flags.
89 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
90 VMI_NonDiamondRepeat = 0x1,
92 /// VMI_DiamondShaped - Class is diamond shaped.
93 VMI_DiamondShaped = 0x2
96 // Base class type info flags.
98 /// BCTI_Virtual - Base class is virtual.
101 /// BCTI_Public - Base class is public.
105 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
107 /// \param Force - true to force the creation of this RTTI value
108 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
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);
119 StringRef Name = OutName.str();
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,
127 llvm::GlobalVariable *GV =
128 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
130 GV->setInitializer(Init);
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);
141 StringRef Name = OutName.str();
143 // Look for an existing global.
144 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
147 // Create a new global variable.
148 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
150 llvm::GlobalValue::ExternalLinkage, 0, Name);
153 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
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:
196 case BuiltinType::Dependent:
197 #define BUILTIN_TYPE(Id, SingletonId)
198 #define PLACEHOLDER_TYPE(Id, SingletonId) \
199 case BuiltinType::Id:
200 #include "clang/AST/BuiltinTypes.def"
201 llvm_unreachable("asking for RRTI for a placeholder type!");
203 case BuiltinType::ObjCId:
204 case BuiltinType::ObjCClass:
205 case BuiltinType::ObjCSel:
206 llvm_unreachable("FIXME: Objective-C types are unsupported!");
209 llvm_unreachable("Invalid BuiltinType Kind!");
212 static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
213 QualType PointeeTy = PointerTy->getPointeeType();
214 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
218 // Check the qualifiers.
219 Qualifiers Quals = PointeeTy.getQualifiers();
225 return TypeInfoIsInStandardLibrary(BuiltinTy);
228 /// IsStandardLibraryRTTIDescriptor - Returns whether the type
229 /// information for the given type exists in the standard library.
230 static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
231 // Type info for builtin types is defined in the standard library.
232 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
233 return TypeInfoIsInStandardLibrary(BuiltinTy);
235 // Type info for some pointer types to builtin types is defined in the
237 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
238 return TypeInfoIsInStandardLibrary(PointerTy);
243 /// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
244 /// the given type exists somewhere else, and that we should not emit the type
245 /// information in this translation unit. Assumes that it is not a
246 /// standard-library type.
247 static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM, QualType Ty) {
248 ASTContext &Context = CGM.getContext();
250 // If RTTI is disabled, don't consider key functions.
251 if (!Context.getLangOpts().RTTI) return false;
253 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
254 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
255 if (!RD->hasDefinition())
258 if (!RD->isDynamicClass())
261 return !CGM.getVTables().ShouldEmitVTableInThisTU(RD);
267 /// IsIncompleteClassType - Returns whether the given record type is incomplete.
268 static bool IsIncompleteClassType(const RecordType *RecordTy) {
269 return !RecordTy->getDecl()->isCompleteDefinition();
272 /// ContainsIncompleteClassType - Returns whether the given type contains an
273 /// incomplete class type. This is true if
275 /// * The given type is an incomplete class type.
276 /// * The given type is a pointer type whose pointee type contains an
277 /// incomplete class type.
278 /// * The given type is a member pointer type whose class is an incomplete
280 /// * The given type is a member pointer type whoise pointee type contains an
281 /// incomplete class type.
282 /// is an indirect or direct pointer to an incomplete class type.
283 static bool ContainsIncompleteClassType(QualType Ty) {
284 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
285 if (IsIncompleteClassType(RecordTy))
289 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
290 return ContainsIncompleteClassType(PointerTy->getPointeeType());
292 if (const MemberPointerType *MemberPointerTy =
293 dyn_cast<MemberPointerType>(Ty)) {
294 // Check if the class type is incomplete.
295 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
296 if (IsIncompleteClassType(ClassType))
299 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
305 /// getTypeInfoLinkage - Return the linkage that the type info and type info
306 /// name constants should have for the given type.
307 static llvm::GlobalVariable::LinkageTypes
308 getTypeInfoLinkage(CodeGenModule &CGM, QualType Ty) {
309 // Itanium C++ ABI 2.9.5p7:
310 // In addition, it and all of the intermediate abi::__pointer_type_info
311 // structs in the chain down to the abi::__class_type_info for the
312 // incomplete class type must be prevented from resolving to the
313 // corresponding type_info structs for the complete class type, possibly
314 // by making them local static objects. Finally, a dummy class RTTI is
315 // generated for the incomplete type that will not resolve to the final
316 // complete class RTTI (because the latter need not exist), possibly by
317 // making it a local static object.
318 if (ContainsIncompleteClassType(Ty))
319 return llvm::GlobalValue::InternalLinkage;
321 switch (Ty->getLinkage()) {
323 case InternalLinkage:
324 case UniqueExternalLinkage:
325 return llvm::GlobalValue::InternalLinkage;
327 case ExternalLinkage:
328 if (!CGM.getLangOpts().RTTI) {
329 // RTTI is not enabled, which means that this type info struct is going
330 // to be used for exception handling. Give it linkonce_odr linkage.
331 return llvm::GlobalValue::LinkOnceODRLinkage;
334 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
335 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
336 if (RD->hasAttr<WeakAttr>())
337 return llvm::GlobalValue::WeakODRLinkage;
338 if (RD->isDynamicClass())
339 return CGM.getVTableLinkage(RD);
342 return llvm::GlobalValue::LinkOnceODRLinkage;
345 llvm_unreachable("Invalid linkage!");
348 // CanUseSingleInheritance - Return whether the given record decl has a "single,
349 // public, non-virtual base at offset zero (i.e. the derived class is dynamic
350 // iff the base is)", according to Itanium C++ ABI, 2.95p6b.
351 static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
352 // Check the number of bases.
353 if (RD->getNumBases() != 1)
357 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
359 // Check that the base is not virtual.
360 if (Base->isVirtual())
363 // Check that the base is public.
364 if (Base->getAccessSpecifier() != AS_public)
367 // Check that the class is dynamic iff the base is.
368 const CXXRecordDecl *BaseDecl =
369 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
370 if (!BaseDecl->isEmpty() &&
371 BaseDecl->isDynamicClass() != RD->isDynamicClass())
377 void RTTIBuilder::BuildVTablePointer(const Type *Ty) {
378 // abi::__class_type_info.
379 static const char * const ClassTypeInfo =
380 "_ZTVN10__cxxabiv117__class_type_infoE";
381 // abi::__si_class_type_info.
382 static const char * const SIClassTypeInfo =
383 "_ZTVN10__cxxabiv120__si_class_type_infoE";
384 // abi::__vmi_class_type_info.
385 static const char * const VMIClassTypeInfo =
386 "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
388 const char *VTableName = 0;
390 switch (Ty->getTypeClass()) {
391 #define TYPE(Class, Base)
392 #define ABSTRACT_TYPE(Class, Base)
393 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
394 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
395 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
396 #include "clang/AST/TypeNodes.def"
397 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
399 case Type::LValueReference:
400 case Type::RValueReference:
401 llvm_unreachable("References shouldn't get here");
404 // GCC treats vector and complex types as fundamental types.
406 case Type::ExtVector:
409 // FIXME: GCC treats block pointers as fundamental types?!
410 case Type::BlockPointer:
411 // abi::__fundamental_type_info.
412 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
415 case Type::ConstantArray:
416 case Type::IncompleteArray:
417 case Type::VariableArray:
418 // abi::__array_type_info.
419 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
422 case Type::FunctionNoProto:
423 case Type::FunctionProto:
424 // abi::__function_type_info.
425 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
429 // abi::__enum_type_info.
430 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
434 const CXXRecordDecl *RD =
435 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
437 if (!RD->hasDefinition() || !RD->getNumBases()) {
438 VTableName = ClassTypeInfo;
439 } else if (CanUseSingleInheritance(RD)) {
440 VTableName = SIClassTypeInfo;
442 VTableName = VMIClassTypeInfo;
448 case Type::ObjCObject:
449 // Ignore protocol qualifiers.
450 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
452 // Handle id and Class.
453 if (isa<BuiltinType>(Ty)) {
454 VTableName = ClassTypeInfo;
458 assert(isa<ObjCInterfaceType>(Ty));
461 case Type::ObjCInterface:
462 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
463 VTableName = SIClassTypeInfo;
465 VTableName = ClassTypeInfo;
469 case Type::ObjCObjectPointer:
471 // abi::__pointer_type_info.
472 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
475 case Type::MemberPointer:
476 // abi::__pointer_to_member_type_info.
477 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
481 llvm::Constant *VTable =
482 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
484 llvm::Type *PtrDiffTy =
485 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
487 // The vtable address point is 2.
488 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
489 VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Two);
490 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
492 Fields.push_back(VTable);
495 // maybeUpdateRTTILinkage - Will update the linkage of the RTTI data structures
496 // from available_externally to the correct linkage if necessary. An example of
503 // const std::type_info &g() {
509 // When we're generating the typeid(A) expression, we do not yet know that
510 // A's key function is defined in this translation unit, so we will give the
511 // typeinfo and typename structures available_externally linkage. When A::f
512 // forces the vtable to be generated, we need to change the linkage of the
513 // typeinfo and typename structs, otherwise we'll end up with undefined
514 // externals when linking.
516 maybeUpdateRTTILinkage(CodeGenModule &CGM, llvm::GlobalVariable *GV,
518 // We're only interested in globals with available_externally linkage.
519 if (!GV->hasAvailableExternallyLinkage())
522 // Get the real linkage for the type.
523 llvm::GlobalVariable::LinkageTypes Linkage = getTypeInfoLinkage(CGM, Ty);
525 // If variable is supposed to have available_externally linkage, we don't
526 // need to do anything.
527 if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
530 // Update the typeinfo linkage.
531 GV->setLinkage(Linkage);
533 // Get the typename global.
534 SmallString<256> OutName;
535 llvm::raw_svector_ostream Out(OutName);
536 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
538 StringRef Name = OutName.str();
540 llvm::GlobalVariable *TypeNameGV = CGM.getModule().getNamedGlobal(Name);
542 assert(TypeNameGV->hasAvailableExternallyLinkage() &&
543 "Type name has different linkage from type info!");
545 // And update its linkage.
546 TypeNameGV->setLinkage(Linkage);
549 llvm::Constant *RTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
550 // We want to operate on the canonical type.
551 Ty = CGM.getContext().getCanonicalType(Ty);
553 // Check if we've already emitted an RTTI descriptor for this type.
554 SmallString<256> OutName;
555 llvm::raw_svector_ostream Out(OutName);
556 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
558 StringRef Name = OutName.str();
560 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
561 if (OldGV && !OldGV->isDeclaration()) {
562 maybeUpdateRTTILinkage(CGM, OldGV, Ty);
564 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
567 // Check if there is already an external RTTI descriptor for this type.
568 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
569 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
570 return GetAddrOfExternalRTTIDescriptor(Ty);
572 // Emit the standard library with external linkage.
573 llvm::GlobalVariable::LinkageTypes Linkage;
575 Linkage = llvm::GlobalValue::ExternalLinkage;
577 Linkage = getTypeInfoLinkage(CGM, Ty);
579 // Add the vtable pointer.
580 BuildVTablePointer(cast<Type>(Ty));
583 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
585 Fields.push_back(llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy));
587 switch (Ty->getTypeClass()) {
588 #define TYPE(Class, Base)
589 #define ABSTRACT_TYPE(Class, Base)
590 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
591 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
592 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
593 #include "clang/AST/TypeNodes.def"
594 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
596 // GCC treats vector types as fundamental types.
599 case Type::ExtVector:
601 case Type::BlockPointer:
602 // Itanium C++ ABI 2.9.5p4:
603 // abi::__fundamental_type_info adds no data members to std::type_info.
606 case Type::LValueReference:
607 case Type::RValueReference:
608 llvm_unreachable("References shouldn't get here");
610 case Type::ConstantArray:
611 case Type::IncompleteArray:
612 case Type::VariableArray:
613 // Itanium C++ ABI 2.9.5p5:
614 // abi::__array_type_info adds no data members to std::type_info.
617 case Type::FunctionNoProto:
618 case Type::FunctionProto:
619 // Itanium C++ ABI 2.9.5p5:
620 // abi::__function_type_info adds no data members to std::type_info.
624 // Itanium C++ ABI 2.9.5p5:
625 // abi::__enum_type_info adds no data members to std::type_info.
629 const CXXRecordDecl *RD =
630 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
631 if (!RD->hasDefinition() || !RD->getNumBases()) {
632 // We don't need to emit any fields.
636 if (CanUseSingleInheritance(RD))
637 BuildSIClassTypeInfo(RD);
639 BuildVMIClassTypeInfo(RD);
644 case Type::ObjCObject:
645 case Type::ObjCInterface:
646 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
649 case Type::ObjCObjectPointer:
650 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
654 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
657 case Type::MemberPointer:
658 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
662 // No fields, at least for the moment.
666 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
668 llvm::GlobalVariable *GV =
669 new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
670 /*Constant=*/true, Linkage, Init, Name);
672 // If there's already an old global variable, replace it with the new one.
675 llvm::Constant *NewPtr =
676 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
677 OldGV->replaceAllUsesWith(NewPtr);
678 OldGV->eraseFromParent();
681 // GCC only relies on the uniqueness of the type names, not the
682 // type_infos themselves, so we can emit these as hidden symbols.
683 // But don't do this if we're worried about strict visibility
685 if (const RecordType *RT = dyn_cast<RecordType>(Ty)) {
686 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
688 CGM.setTypeVisibility(GV, RD, CodeGenModule::TVK_ForRTTI);
689 CGM.setTypeVisibility(TypeName, RD, CodeGenModule::TVK_ForRTTIName);
691 Visibility TypeInfoVisibility = DefaultVisibility;
692 if (CGM.getCodeGenOpts().HiddenWeakVTables &&
693 Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
694 TypeInfoVisibility = HiddenVisibility;
696 // The type name should have the same visibility as the type itself.
697 Visibility ExplicitVisibility = Ty->getVisibility();
698 TypeName->setVisibility(CodeGenModule::
699 GetLLVMVisibility(ExplicitVisibility));
701 TypeInfoVisibility = minVisibility(TypeInfoVisibility, Ty->getVisibility());
702 GV->setVisibility(CodeGenModule::GetLLVMVisibility(TypeInfoVisibility));
705 GV->setUnnamedAddr(true);
707 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
710 /// ComputeQualifierFlags - Compute the pointer type info flags from the
712 static unsigned ComputeQualifierFlags(Qualifiers Quals) {
715 if (Quals.hasConst())
716 Flags |= RTTIBuilder::PTI_Const;
717 if (Quals.hasVolatile())
718 Flags |= RTTIBuilder::PTI_Volatile;
719 if (Quals.hasRestrict())
720 Flags |= RTTIBuilder::PTI_Restrict;
725 /// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
726 /// for the given Objective-C object type.
727 void RTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
729 const Type *T = OT->getBaseType().getTypePtr();
730 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
732 // The builtin types are abi::__class_type_infos and don't require
734 if (isa<BuiltinType>(T)) return;
736 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
737 ObjCInterfaceDecl *Super = Class->getSuperClass();
739 // Root classes are also __class_type_info.
742 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
744 // Everything else is single inheritance.
745 llvm::Constant *BaseTypeInfo = RTTIBuilder(CGM).BuildTypeInfo(SuperTy);
746 Fields.push_back(BaseTypeInfo);
749 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
750 /// inheritance, according to the Itanium C++ ABI, 2.95p6b.
751 void RTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
752 // Itanium C++ ABI 2.9.5p6b:
753 // It adds to abi::__class_type_info a single member pointing to the
754 // type_info structure for the base type,
755 llvm::Constant *BaseTypeInfo =
756 RTTIBuilder(CGM).BuildTypeInfo(RD->bases_begin()->getType());
757 Fields.push_back(BaseTypeInfo);
761 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
762 /// a class hierarchy.
764 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
765 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
769 /// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
770 /// abi::__vmi_class_type_info.
772 static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
777 const CXXRecordDecl *BaseDecl =
778 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
780 if (Base->isVirtual()) {
781 // Mark the virtual base as seen.
782 if (!Bases.VirtualBases.insert(BaseDecl)) {
783 // If this virtual base has been seen before, then the class is diamond
785 Flags |= RTTIBuilder::VMI_DiamondShaped;
787 if (Bases.NonVirtualBases.count(BaseDecl))
788 Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
791 // Mark the non-virtual base as seen.
792 if (!Bases.NonVirtualBases.insert(BaseDecl)) {
793 // If this non-virtual base has been seen before, then the class has non-
794 // diamond shaped repeated inheritance.
795 Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
797 if (Bases.VirtualBases.count(BaseDecl))
798 Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
803 for (CXXRecordDecl::base_class_const_iterator I = BaseDecl->bases_begin(),
804 E = BaseDecl->bases_end(); I != E; ++I)
805 Flags |= ComputeVMIClassTypeInfoFlags(I, Bases);
810 static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
815 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
816 E = RD->bases_end(); I != E; ++I)
817 Flags |= ComputeVMIClassTypeInfoFlags(I, Bases);
822 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
823 /// classes with bases that do not satisfy the abi::__si_class_type_info
824 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
825 void RTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
826 llvm::Type *UnsignedIntLTy =
827 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
829 // Itanium C++ ABI 2.9.5p6c:
830 // __flags is a word with flags describing details about the class
831 // structure, which may be referenced by using the __flags_masks
832 // enumeration. These flags refer to both direct and indirect bases.
833 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
834 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
836 // Itanium C++ ABI 2.9.5p6c:
837 // __base_count is a word with the number of direct proper base class
838 // descriptions that follow.
839 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
841 if (!RD->getNumBases())
844 llvm::Type *LongLTy =
845 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
847 // Now add the base class descriptions.
849 // Itanium C++ ABI 2.9.5p6c:
850 // __base_info[] is an array of base class descriptions -- one for every
851 // direct proper base. Each description is of the type:
853 // struct abi::__base_class_type_info {
855 // const __class_type_info *__base_type;
856 // long __offset_flags;
858 // enum __offset_flags_masks {
859 // __virtual_mask = 0x1,
860 // __public_mask = 0x2,
861 // __offset_shift = 8
864 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
865 E = RD->bases_end(); I != E; ++I) {
866 const CXXBaseSpecifier *Base = I;
868 // The __base_type member points to the RTTI for the base type.
869 Fields.push_back(RTTIBuilder(CGM).BuildTypeInfo(Base->getType()));
871 const CXXRecordDecl *BaseDecl =
872 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
874 int64_t OffsetFlags = 0;
876 // All but the lower 8 bits of __offset_flags are a signed offset.
877 // For a non-virtual base, this is the offset in the object of the base
878 // subobject. For a virtual base, this is the offset in the virtual table of
879 // the virtual base offset for the virtual base referenced (negative).
881 if (Base->isVirtual())
883 CGM.getVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
885 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
886 Offset = Layout.getBaseClassOffset(BaseDecl);
889 OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
891 // The low-order byte of __offset_flags contains flags, as given by the
892 // masks from the enumeration __offset_flags_masks.
893 if (Base->isVirtual())
894 OffsetFlags |= BCTI_Virtual;
895 if (Base->getAccessSpecifier() == AS_public)
896 OffsetFlags |= BCTI_Public;
898 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
902 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
903 /// used for pointer types.
904 void RTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
906 QualType UnqualifiedPointeeTy =
907 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
909 // Itanium C++ ABI 2.9.5p7:
910 // __flags is a flag word describing the cv-qualification and other
911 // attributes of the type pointed to
912 unsigned Flags = ComputeQualifierFlags(Quals);
914 // Itanium C++ ABI 2.9.5p7:
915 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
916 // incomplete class type, the incomplete target type flag is set.
917 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
918 Flags |= PTI_Incomplete;
920 llvm::Type *UnsignedIntLTy =
921 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
922 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
924 // Itanium C++ ABI 2.9.5p7:
925 // __pointee is a pointer to the std::type_info derivation for the
926 // unqualified type being pointed to.
927 llvm::Constant *PointeeTypeInfo =
928 RTTIBuilder(CGM).BuildTypeInfo(UnqualifiedPointeeTy);
929 Fields.push_back(PointeeTypeInfo);
932 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
933 /// struct, used for member pointer types.
934 void RTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
935 QualType PointeeTy = Ty->getPointeeType();
938 QualType UnqualifiedPointeeTy =
939 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
941 // Itanium C++ ABI 2.9.5p7:
942 // __flags is a flag word describing the cv-qualification and other
943 // attributes of the type pointed to.
944 unsigned Flags = ComputeQualifierFlags(Quals);
946 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
948 // Itanium C++ ABI 2.9.5p7:
949 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
950 // incomplete class type, the incomplete target type flag is set.
951 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
952 Flags |= PTI_Incomplete;
954 if (IsIncompleteClassType(ClassType))
955 Flags |= PTI_ContainingClassIncomplete;
957 llvm::Type *UnsignedIntLTy =
958 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
959 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
961 // Itanium C++ ABI 2.9.5p7:
962 // __pointee is a pointer to the std::type_info derivation for the
963 // unqualified type being pointed to.
964 llvm::Constant *PointeeTypeInfo =
965 RTTIBuilder(CGM).BuildTypeInfo(UnqualifiedPointeeTy);
966 Fields.push_back(PointeeTypeInfo);
968 // Itanium C++ ABI 2.9.5p9:
969 // __context is a pointer to an abi::__class_type_info corresponding to the
970 // class type containing the member pointed to
971 // (e.g., the "A" in "int A::*").
972 Fields.push_back(RTTIBuilder(CGM).BuildTypeInfo(QualType(ClassType, 0)));
975 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
977 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
978 // FIXME: should we even be calling this method if RTTI is disabled
979 // and it's not for EH?
980 if (!ForEH && !getLangOpts().RTTI)
981 return llvm::Constant::getNullValue(Int8PtrTy);
983 if (ForEH && Ty->isObjCObjectPointerType() &&
984 LangOpts.ObjCRuntime.isGNUFamily())
985 return ObjCRuntime->GetEHType(Ty);
987 return RTTIBuilder(*this).BuildTypeInfo(Ty);
990 void CodeGenModule::EmitFundamentalRTTIDescriptor(QualType Type) {
991 QualType PointerType = Context.getPointerType(Type);
992 QualType PointerTypeConst = Context.getPointerType(Type.withConst());
993 RTTIBuilder(*this).BuildTypeInfo(Type, true);
994 RTTIBuilder(*this).BuildTypeInfo(PointerType, true);
995 RTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
998 void CodeGenModule::EmitFundamentalRTTIDescriptors() {
999 QualType FundamentalTypes[] = { Context.VoidTy, Context.NullPtrTy,
1000 Context.BoolTy, Context.WCharTy,
1001 Context.CharTy, Context.UnsignedCharTy,
1002 Context.SignedCharTy, Context.ShortTy,
1003 Context.UnsignedShortTy, Context.IntTy,
1004 Context.UnsignedIntTy, Context.LongTy,
1005 Context.UnsignedLongTy, Context.LongLongTy,
1006 Context.UnsignedLongLongTy, Context.FloatTy,
1007 Context.DoubleTy, Context.LongDoubleTy,
1008 Context.Char16Ty, Context.Char32Ty };
1009 for (unsigned i = 0; i < sizeof(FundamentalTypes)/sizeof(QualType); ++i)
1010 EmitFundamentalRTTIDescriptor(FundamentalTypes[i]);