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