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 llvm::Type *Int8PtrTy;
31 /// Fields - The fields of the RTTI descriptor currently being built.
32 SmallVector<llvm::Constant *, 16> Fields;
34 /// GetAddrOfTypeName - Returns the mangled type name of the given type.
35 llvm::GlobalVariable *
36 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
38 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
39 /// descriptor of the given type.
40 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
42 /// BuildVTablePointer - Build the vtable pointer for the given type.
43 void BuildVTablePointer(const Type *Ty);
45 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
46 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
47 void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
49 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
50 /// classes with bases that do not satisfy the abi::__si_class_type_info
51 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
52 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
54 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
55 /// for pointer types.
56 void BuildPointerTypeInfo(QualType PointeeTy);
58 /// BuildObjCObjectTypeInfo - Build the appropriate kind of
59 /// type_info for an object type.
60 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
62 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
63 /// struct, used for member pointer types.
64 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
67 RTTIBuilder(CodeGenModule &CGM) : CGM(CGM),
68 VMContext(CGM.getModule().getContext()),
69 Int8PtrTy(llvm::Type::getInt8PtrTy(VMContext)) { }
71 // Pointer type info flags.
73 /// PTI_Const - Type has const qualifier.
76 /// PTI_Volatile - Type has volatile qualifier.
79 /// PTI_Restrict - Type has restrict qualifier.
82 /// PTI_Incomplete - Type is incomplete.
85 /// PTI_ContainingClassIncomplete - Containing class is incomplete.
86 /// (in pointer to member).
87 PTI_ContainingClassIncomplete = 0x10
90 // VMI type info flags.
92 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
93 VMI_NonDiamondRepeat = 0x1,
95 /// VMI_DiamondShaped - Class is diamond shaped.
96 VMI_DiamondShaped = 0x2
99 // Base class type info flags.
101 /// BCTI_Virtual - Base class is virtual.
104 /// BCTI_Public - Base class is public.
108 /// BuildTypeInfo - Build the RTTI type info struct for the given type.
110 /// \param Force - true to force the creation of this RTTI value
111 /// \param ForEH - true if this is for exception handling
112 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
116 llvm::GlobalVariable *
117 RTTIBuilder::GetAddrOfTypeName(QualType Ty,
118 llvm::GlobalVariable::LinkageTypes Linkage) {
119 llvm::SmallString<256> OutName;
120 llvm::raw_svector_ostream Out(OutName);
121 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
123 StringRef Name = OutName.str();
125 // We know that the mangled name of the type starts at index 4 of the
126 // mangled name of the typename, so we can just index into it in order to
127 // get the mangled name of the type.
128 llvm::Constant *Init = llvm::ConstantArray::get(VMContext, Name.substr(4));
130 llvm::GlobalVariable *GV =
131 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
133 GV->setInitializer(Init);
138 llvm::Constant *RTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
139 // Mangle the RTTI name.
140 llvm::SmallString<256> OutName;
141 llvm::raw_svector_ostream Out(OutName);
142 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
144 StringRef Name = OutName.str();
146 // Look for an existing global.
147 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
150 // Create a new global variable.
151 GV = new llvm::GlobalVariable(CGM.getModule(), Int8PtrTy, /*Constant=*/true,
152 llvm::GlobalValue::ExternalLinkage, 0, Name);
155 return llvm::ConstantExpr::getBitCast(GV, Int8PtrTy);
158 /// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
159 /// info for that type is defined in the standard library.
160 static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
161 // Itanium C++ ABI 2.9.2:
162 // Basic type information (e.g. for "int", "bool", etc.) will be kept in
163 // the run-time support library. Specifically, the run-time support
164 // library should contain type_info objects for the types X, X* and
165 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
166 // unsigned char, signed char, short, unsigned short, int, unsigned int,
167 // long, unsigned long, long long, unsigned long long, float, double,
168 // long double, char16_t, char32_t, and the IEEE 754r decimal and
169 // half-precision floating point types.
170 switch (Ty->getKind()) {
171 case BuiltinType::Void:
172 case BuiltinType::NullPtr:
173 case BuiltinType::Bool:
174 case BuiltinType::WChar_S:
175 case BuiltinType::WChar_U:
176 case BuiltinType::Char_U:
177 case BuiltinType::Char_S:
178 case BuiltinType::UChar:
179 case BuiltinType::SChar:
180 case BuiltinType::Short:
181 case BuiltinType::UShort:
182 case BuiltinType::Int:
183 case BuiltinType::UInt:
184 case BuiltinType::Long:
185 case BuiltinType::ULong:
186 case BuiltinType::LongLong:
187 case BuiltinType::ULongLong:
188 case BuiltinType::Half:
189 case BuiltinType::Float:
190 case BuiltinType::Double:
191 case BuiltinType::LongDouble:
192 case BuiltinType::Char16:
193 case BuiltinType::Char32:
194 case BuiltinType::Int128:
195 case BuiltinType::UInt128:
198 case BuiltinType::Overload:
199 case BuiltinType::Dependent:
200 case BuiltinType::BoundMember:
201 case BuiltinType::UnknownAny:
202 llvm_unreachable("asking for RRTI for a placeholder type!");
204 case BuiltinType::ObjCId:
205 case BuiltinType::ObjCClass:
206 case BuiltinType::ObjCSel:
207 llvm_unreachable("FIXME: Objective-C types are unsupported!");
214 static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
215 QualType PointeeTy = PointerTy->getPointeeType();
216 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
220 // Check the qualifiers.
221 Qualifiers Quals = PointeeTy.getQualifiers();
227 return TypeInfoIsInStandardLibrary(BuiltinTy);
230 /// IsStandardLibraryRTTIDescriptor - Returns whether the type
231 /// information for the given type exists in the standard library.
232 static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
233 // Type info for builtin types is defined in the standard library.
234 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
235 return TypeInfoIsInStandardLibrary(BuiltinTy);
237 // Type info for some pointer types to builtin types is defined in the
239 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
240 return TypeInfoIsInStandardLibrary(PointerTy);
245 /// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
246 /// the given type exists somewhere else, and that we should not emit the type
247 /// information in this translation unit. Assumes that it is not a
248 /// standard-library type.
249 static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM, QualType Ty) {
250 ASTContext &Context = CGM.getContext();
252 // If RTTI is disabled, don't consider key functions.
253 if (!Context.getLangOptions().RTTI) return false;
255 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
256 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
257 if (!RD->hasDefinition())
260 if (!RD->isDynamicClass())
263 return !CGM.getVTables().ShouldEmitVTableInThisTU(RD);
269 /// IsIncompleteClassType - Returns whether the given record type is incomplete.
270 static bool IsIncompleteClassType(const RecordType *RecordTy) {
271 return !RecordTy->getDecl()->isCompleteDefinition();
274 /// ContainsIncompleteClassType - Returns whether the given type contains an
275 /// incomplete class type. This is true if
277 /// * The given type is an incomplete class type.
278 /// * The given type is a pointer type whose pointee type contains an
279 /// incomplete class type.
280 /// * The given type is a member pointer type whose class is an incomplete
282 /// * The given type is a member pointer type whoise pointee type contains an
283 /// incomplete class type.
284 /// is an indirect or direct pointer to an incomplete class type.
285 static bool ContainsIncompleteClassType(QualType Ty) {
286 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
287 if (IsIncompleteClassType(RecordTy))
291 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
292 return ContainsIncompleteClassType(PointerTy->getPointeeType());
294 if (const MemberPointerType *MemberPointerTy =
295 dyn_cast<MemberPointerType>(Ty)) {
296 // Check if the class type is incomplete.
297 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
298 if (IsIncompleteClassType(ClassType))
301 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
307 /// getTypeInfoLinkage - Return the linkage that the type info and type info
308 /// name constants should have for the given type.
309 static llvm::GlobalVariable::LinkageTypes
310 getTypeInfoLinkage(CodeGenModule &CGM, QualType Ty) {
311 // Itanium C++ ABI 2.9.5p7:
312 // In addition, it and all of the intermediate abi::__pointer_type_info
313 // structs in the chain down to the abi::__class_type_info for the
314 // incomplete class type must be prevented from resolving to the
315 // corresponding type_info structs for the complete class type, possibly
316 // by making them local static objects. Finally, a dummy class RTTI is
317 // generated for the incomplete type that will not resolve to the final
318 // complete class RTTI (because the latter need not exist), possibly by
319 // making it a local static object.
320 if (ContainsIncompleteClassType(Ty))
321 return llvm::GlobalValue::InternalLinkage;
323 switch (Ty->getLinkage()) {
325 case InternalLinkage:
326 case UniqueExternalLinkage:
327 return llvm::GlobalValue::InternalLinkage;
329 case ExternalLinkage:
330 if (!CGM.getLangOptions().RTTI) {
331 // RTTI is not enabled, which means that this type info struct is going
332 // to be used for exception handling. Give it linkonce_odr linkage.
333 return llvm::GlobalValue::LinkOnceODRLinkage;
336 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
337 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
338 if (RD->isDynamicClass())
339 return CGM.getVTableLinkage(RD);
342 return llvm::GlobalValue::LinkOnceODRLinkage;
345 return llvm::GlobalValue::LinkOnceODRLinkage;
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, 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, 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 llvm::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 llvm::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, 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 llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
586 Fields.push_back(llvm::ConstantExpr::getBitCast(TypeName, Int8PtrTy));
588 switch (Ty->getTypeClass()) {
589 #define TYPE(Class, Base)
590 #define ABSTRACT_TYPE(Class, Base)
591 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
592 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
593 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
594 #include "clang/AST/TypeNodes.def"
595 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
597 // GCC treats vector types as fundamental types.
600 case Type::ExtVector:
602 case Type::BlockPointer:
603 // Itanium C++ ABI 2.9.5p4:
604 // abi::__fundamental_type_info adds no data members to std::type_info.
607 case Type::LValueReference:
608 case Type::RValueReference:
609 llvm_unreachable("References shouldn't get here");
611 case Type::ConstantArray:
612 case Type::IncompleteArray:
613 case Type::VariableArray:
614 // Itanium C++ ABI 2.9.5p5:
615 // abi::__array_type_info adds no data members to std::type_info.
618 case Type::FunctionNoProto:
619 case Type::FunctionProto:
620 // Itanium C++ ABI 2.9.5p5:
621 // abi::__function_type_info adds no data members to std::type_info.
625 // Itanium C++ ABI 2.9.5p5:
626 // abi::__enum_type_info adds no data members to std::type_info.
630 const CXXRecordDecl *RD =
631 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
632 if (!RD->hasDefinition() || !RD->getNumBases()) {
633 // We don't need to emit any fields.
637 if (CanUseSingleInheritance(RD))
638 BuildSIClassTypeInfo(RD);
640 BuildVMIClassTypeInfo(RD);
645 case Type::ObjCObject:
646 case Type::ObjCInterface:
647 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
650 case Type::ObjCObjectPointer:
651 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
655 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
658 case Type::MemberPointer:
659 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
663 // No fields, at least for the moment.
667 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
669 llvm::GlobalVariable *GV =
670 new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
671 /*Constant=*/true, Linkage, Init, Name);
673 // If there's already an old global variable, replace it with the new one.
676 llvm::Constant *NewPtr =
677 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
678 OldGV->replaceAllUsesWith(NewPtr);
679 OldGV->eraseFromParent();
682 // GCC only relies on the uniqueness of the type names, not the
683 // type_infos themselves, so we can emit these as hidden symbols.
684 // But don't do this if we're worried about strict visibility
686 if (const RecordType *RT = dyn_cast<RecordType>(Ty)) {
687 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
689 CGM.setTypeVisibility(GV, RD, CodeGenModule::TVK_ForRTTI);
690 CGM.setTypeVisibility(TypeName, RD, CodeGenModule::TVK_ForRTTIName);
692 Visibility TypeInfoVisibility = DefaultVisibility;
693 if (CGM.getCodeGenOpts().HiddenWeakVTables &&
694 Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
695 TypeInfoVisibility = HiddenVisibility;
697 // The type name should have the same visibility as the type itself.
698 Visibility ExplicitVisibility = Ty->getVisibility();
699 TypeName->setVisibility(CodeGenModule::
700 GetLLVMVisibility(ExplicitVisibility));
702 TypeInfoVisibility = minVisibility(TypeInfoVisibility, Ty->getVisibility());
703 GV->setVisibility(CodeGenModule::GetLLVMVisibility(TypeInfoVisibility));
706 GV->setUnnamedAddr(true);
708 return llvm::ConstantExpr::getBitCast(GV, Int8PtrTy);
711 /// ComputeQualifierFlags - Compute the pointer type info flags from the
713 static unsigned ComputeQualifierFlags(Qualifiers Quals) {
716 if (Quals.hasConst())
717 Flags |= RTTIBuilder::PTI_Const;
718 if (Quals.hasVolatile())
719 Flags |= RTTIBuilder::PTI_Volatile;
720 if (Quals.hasRestrict())
721 Flags |= RTTIBuilder::PTI_Restrict;
726 /// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
727 /// for the given Objective-C object type.
728 void RTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
730 const Type *T = OT->getBaseType().getTypePtr();
731 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
733 // The builtin types are abi::__class_type_infos and don't require
735 if (isa<BuiltinType>(T)) return;
737 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
738 ObjCInterfaceDecl *Super = Class->getSuperClass();
740 // Root classes are also __class_type_info.
743 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
745 // Everything else is single inheritance.
746 llvm::Constant *BaseTypeInfo = RTTIBuilder(CGM).BuildTypeInfo(SuperTy);
747 Fields.push_back(BaseTypeInfo);
750 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
751 /// inheritance, according to the Itanium C++ ABI, 2.95p6b.
752 void RTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
753 // Itanium C++ ABI 2.9.5p6b:
754 // It adds to abi::__class_type_info a single member pointing to the
755 // type_info structure for the base type,
756 llvm::Constant *BaseTypeInfo =
757 RTTIBuilder(CGM).BuildTypeInfo(RD->bases_begin()->getType());
758 Fields.push_back(BaseTypeInfo);
762 /// SeenBases - Contains virtual and non-virtual bases seen when traversing
763 /// a class hierarchy.
765 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
766 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
770 /// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
771 /// abi::__vmi_class_type_info.
773 static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
778 const CXXRecordDecl *BaseDecl =
779 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
781 if (Base->isVirtual()) {
782 if (Bases.VirtualBases.count(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;
790 // Mark the virtual base as seen.
791 Bases.VirtualBases.insert(BaseDecl);
794 if (Bases.NonVirtualBases.count(BaseDecl)) {
795 // If this non-virtual base has been seen before, then the class has non-
796 // diamond shaped repeated inheritance.
797 Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
799 if (Bases.VirtualBases.count(BaseDecl))
800 Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
802 // Mark the non-virtual base as seen.
803 Bases.NonVirtualBases.insert(BaseDecl);
808 for (CXXRecordDecl::base_class_const_iterator I = BaseDecl->bases_begin(),
809 E = BaseDecl->bases_end(); I != E; ++I)
810 Flags |= ComputeVMIClassTypeInfoFlags(I, Bases);
815 static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
820 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
821 E = RD->bases_end(); I != E; ++I)
822 Flags |= ComputeVMIClassTypeInfoFlags(I, Bases);
827 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
828 /// classes with bases that do not satisfy the abi::__si_class_type_info
829 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
830 void RTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
831 llvm::Type *UnsignedIntLTy =
832 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
834 // Itanium C++ ABI 2.9.5p6c:
835 // __flags is a word with flags describing details about the class
836 // structure, which may be referenced by using the __flags_masks
837 // enumeration. These flags refer to both direct and indirect bases.
838 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
839 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
841 // Itanium C++ ABI 2.9.5p6c:
842 // __base_count is a word with the number of direct proper base class
843 // descriptions that follow.
844 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
846 if (!RD->getNumBases())
849 llvm::Type *LongLTy =
850 CGM.getTypes().ConvertType(CGM.getContext().LongTy);
852 // Now add the base class descriptions.
854 // Itanium C++ ABI 2.9.5p6c:
855 // __base_info[] is an array of base class descriptions -- one for every
856 // direct proper base. Each description is of the type:
858 // struct abi::__base_class_type_info {
860 // const __class_type_info *__base_type;
861 // long __offset_flags;
863 // enum __offset_flags_masks {
864 // __virtual_mask = 0x1,
865 // __public_mask = 0x2,
866 // __offset_shift = 8
869 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
870 E = RD->bases_end(); I != E; ++I) {
871 const CXXBaseSpecifier *Base = I;
873 // The __base_type member points to the RTTI for the base type.
874 Fields.push_back(RTTIBuilder(CGM).BuildTypeInfo(Base->getType()));
876 const CXXRecordDecl *BaseDecl =
877 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
879 int64_t OffsetFlags = 0;
881 // All but the lower 8 bits of __offset_flags are a signed offset.
882 // For a non-virtual base, this is the offset in the object of the base
883 // subobject. For a virtual base, this is the offset in the virtual table of
884 // the virtual base offset for the virtual base referenced (negative).
886 if (Base->isVirtual())
888 CGM.getVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
890 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
891 Offset = Layout.getBaseClassOffset(BaseDecl);
894 OffsetFlags = Offset.getQuantity() << 8;
896 // The low-order byte of __offset_flags contains flags, as given by the
897 // masks from the enumeration __offset_flags_masks.
898 if (Base->isVirtual())
899 OffsetFlags |= BCTI_Virtual;
900 if (Base->getAccessSpecifier() == AS_public)
901 OffsetFlags |= BCTI_Public;
903 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
907 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
908 /// used for pointer types.
909 void RTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
911 QualType UnqualifiedPointeeTy =
912 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
914 // Itanium C++ ABI 2.9.5p7:
915 // __flags is a flag word describing the cv-qualification and other
916 // attributes of the type pointed to
917 unsigned Flags = ComputeQualifierFlags(Quals);
919 // Itanium C++ ABI 2.9.5p7:
920 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
921 // incomplete class type, the incomplete target type flag is set.
922 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
923 Flags |= PTI_Incomplete;
925 llvm::Type *UnsignedIntLTy =
926 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
927 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
929 // Itanium C++ ABI 2.9.5p7:
930 // __pointee is a pointer to the std::type_info derivation for the
931 // unqualified type being pointed to.
932 llvm::Constant *PointeeTypeInfo =
933 RTTIBuilder(CGM).BuildTypeInfo(UnqualifiedPointeeTy);
934 Fields.push_back(PointeeTypeInfo);
937 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
938 /// struct, used for member pointer types.
939 void RTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
940 QualType PointeeTy = Ty->getPointeeType();
943 QualType UnqualifiedPointeeTy =
944 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
946 // Itanium C++ ABI 2.9.5p7:
947 // __flags is a flag word describing the cv-qualification and other
948 // attributes of the type pointed to.
949 unsigned Flags = ComputeQualifierFlags(Quals);
951 const RecordType *ClassType = cast<RecordType>(Ty->getClass());
953 // Itanium C++ ABI 2.9.5p7:
954 // When the abi::__pbase_type_info is for a direct or indirect pointer to an
955 // incomplete class type, the incomplete target type flag is set.
956 if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
957 Flags |= PTI_Incomplete;
959 if (IsIncompleteClassType(ClassType))
960 Flags |= PTI_ContainingClassIncomplete;
962 llvm::Type *UnsignedIntLTy =
963 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
964 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
966 // Itanium C++ ABI 2.9.5p7:
967 // __pointee is a pointer to the std::type_info derivation for the
968 // unqualified type being pointed to.
969 llvm::Constant *PointeeTypeInfo =
970 RTTIBuilder(CGM).BuildTypeInfo(UnqualifiedPointeeTy);
971 Fields.push_back(PointeeTypeInfo);
973 // Itanium C++ ABI 2.9.5p9:
974 // __context is a pointer to an abi::__class_type_info corresponding to the
975 // class type containing the member pointed to
976 // (e.g., the "A" in "int A::*").
977 Fields.push_back(RTTIBuilder(CGM).BuildTypeInfo(QualType(ClassType, 0)));
980 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
982 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
983 // FIXME: should we even be calling this method if RTTI is disabled
984 // and it's not for EH?
985 if (!ForEH && !getContext().getLangOptions().RTTI) {
986 llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
987 return llvm::Constant::getNullValue(Int8PtrTy);
990 if (ForEH && Ty->isObjCObjectPointerType() && !Features.NeXTRuntime) {
991 return ObjCRuntime->GetEHType(Ty);
994 return RTTIBuilder(*this).BuildTypeInfo(Ty);
997 void CodeGenModule::EmitFundamentalRTTIDescriptor(QualType Type) {
998 QualType PointerType = Context.getPointerType(Type);
999 QualType PointerTypeConst = Context.getPointerType(Type.withConst());
1000 RTTIBuilder(*this).BuildTypeInfo(Type, true);
1001 RTTIBuilder(*this).BuildTypeInfo(PointerType, true);
1002 RTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
1005 void CodeGenModule::EmitFundamentalRTTIDescriptors() {
1006 QualType FundamentalTypes[] = { Context.VoidTy, Context.NullPtrTy,
1007 Context.BoolTy, Context.WCharTy,
1008 Context.CharTy, Context.UnsignedCharTy,
1009 Context.SignedCharTy, Context.ShortTy,
1010 Context.UnsignedShortTy, Context.IntTy,
1011 Context.UnsignedIntTy, Context.LongTy,
1012 Context.UnsignedLongTy, Context.LongLongTy,
1013 Context.UnsignedLongLongTy, Context.FloatTy,
1014 Context.DoubleTy, Context.LongDoubleTy,
1015 Context.Char16Ty, Context.Char32Ty };
1016 for (unsigned i = 0; i < sizeof(FundamentalTypes)/sizeof(QualType); ++i)
1017 EmitFundamentalRTTIDescriptor(FundamentalTypes[i]);