]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/CodeGen/CGRTTI.cpp
MFV r247580:
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / CodeGen / CGRTTI.cpp
1 //===--- CGCXXRTTI.cpp - Emit LLVM Code for C++ RTTI descriptors ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code dealing with C++ code generation of RTTI descriptors.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "CodeGenModule.h"
15 #include "CGCXXABI.h"
16 #include "clang/AST/RecordLayout.h"
17 #include "clang/AST/Type.h"
18 #include "clang/Frontend/CodeGenOptions.h"
19 #include "CGObjCRuntime.h"
20
21 using namespace clang;
22 using namespace CodeGen;
23
24 namespace {
25 class RTTIBuilder {
26   CodeGenModule &CGM;  // Per-module state.
27   llvm::LLVMContext &VMContext;
28   
29   /// Fields - The fields of the RTTI descriptor currently being built.
30   SmallVector<llvm::Constant *, 16> Fields;
31
32   /// GetAddrOfTypeName - Returns the mangled type name of the given type.
33   llvm::GlobalVariable *
34   GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
35
36   /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI 
37   /// descriptor of the given type.
38   llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
39   
40   /// BuildVTablePointer - Build the vtable pointer for the given type.
41   void BuildVTablePointer(const Type *Ty);
42   
43   /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
44   /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
45   void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
46   
47   /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
48   /// classes with bases that do not satisfy the abi::__si_class_type_info 
49   /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
50   void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
51   
52   /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
53   /// for pointer types.
54   void BuildPointerTypeInfo(QualType PointeeTy);
55
56   /// BuildObjCObjectTypeInfo - Build the appropriate kind of
57   /// type_info for an object type.
58   void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
59   
60   /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info 
61   /// struct, used for member pointer types.
62   void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
63   
64 public:
65   RTTIBuilder(CodeGenModule &CGM) : CGM(CGM), 
66     VMContext(CGM.getModule().getContext()) { }
67
68   // Pointer type info flags.
69   enum {
70     /// PTI_Const - Type has const qualifier.
71     PTI_Const = 0x1,
72     
73     /// PTI_Volatile - Type has volatile qualifier.
74     PTI_Volatile = 0x2,
75     
76     /// PTI_Restrict - Type has restrict qualifier.
77     PTI_Restrict = 0x4,
78     
79     /// PTI_Incomplete - Type is incomplete.
80     PTI_Incomplete = 0x8,
81     
82     /// PTI_ContainingClassIncomplete - Containing class is incomplete.
83     /// (in pointer to member).
84     PTI_ContainingClassIncomplete = 0x10
85   };
86   
87   // VMI type info flags.
88   enum {
89     /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
90     VMI_NonDiamondRepeat = 0x1,
91     
92     /// VMI_DiamondShaped - Class is diamond shaped.
93     VMI_DiamondShaped = 0x2
94   };
95   
96   // Base class type info flags.
97   enum {
98     /// BCTI_Virtual - Base class is virtual.
99     BCTI_Virtual = 0x1,
100     
101     /// BCTI_Public - Base class is public.
102     BCTI_Public = 0x2
103   };
104   
105   /// BuildTypeInfo - Build the RTTI type info struct for the given type.
106   ///
107   /// \param Force - true to force the creation of this RTTI value
108   llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
109 };
110 }
111
112 llvm::GlobalVariable *
113 RTTIBuilder::GetAddrOfTypeName(QualType Ty, 
114                                llvm::GlobalVariable::LinkageTypes Linkage) {
115   SmallString<256> OutName;
116   llvm::raw_svector_ostream Out(OutName);
117   CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
118   Out.flush();
119   StringRef Name = OutName.str();
120
121   // We know that the mangled name of the type starts at index 4 of the
122   // mangled name of the typename, so we can just index into it in order to
123   // get the mangled name of the type.
124   llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
125                                                             Name.substr(4));
126
127   llvm::GlobalVariable *GV = 
128     CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
129
130   GV->setInitializer(Init);
131
132   return GV;
133 }
134
135 llvm::Constant *RTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
136   // Mangle the RTTI name.
137   SmallString<256> OutName;
138   llvm::raw_svector_ostream Out(OutName);
139   CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
140   Out.flush();
141   StringRef Name = OutName.str();
142
143   // Look for an existing global.
144   llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
145   
146   if (!GV) {
147     // Create a new global variable.
148     GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
149                                   /*Constant=*/true,
150                                   llvm::GlobalValue::ExternalLinkage, 0, Name);
151   }
152   
153   return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
154 }
155
156 /// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
157 /// info for that type is defined in the standard library.
158 static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
159   // Itanium C++ ABI 2.9.2:
160   //   Basic type information (e.g. for "int", "bool", etc.) will be kept in
161   //   the run-time support library. Specifically, the run-time support
162   //   library should contain type_info objects for the types X, X* and 
163   //   X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
164   //   unsigned char, signed char, short, unsigned short, int, unsigned int,
165   //   long, unsigned long, long long, unsigned long long, float, double,
166   //   long double, char16_t, char32_t, and the IEEE 754r decimal and 
167   //   half-precision floating point types.
168   switch (Ty->getKind()) {
169     case BuiltinType::Void:
170     case BuiltinType::NullPtr:
171     case BuiltinType::Bool:
172     case BuiltinType::WChar_S:
173     case BuiltinType::WChar_U:
174     case BuiltinType::Char_U:
175     case BuiltinType::Char_S:
176     case BuiltinType::UChar:
177     case BuiltinType::SChar:
178     case BuiltinType::Short:
179     case BuiltinType::UShort:
180     case BuiltinType::Int:
181     case BuiltinType::UInt:
182     case BuiltinType::Long:
183     case BuiltinType::ULong:
184     case BuiltinType::LongLong:
185     case BuiltinType::ULongLong:
186     case BuiltinType::Half:
187     case BuiltinType::Float:
188     case BuiltinType::Double:
189     case BuiltinType::LongDouble:
190     case BuiltinType::Char16:
191     case BuiltinType::Char32:
192     case BuiltinType::Int128:
193     case BuiltinType::UInt128:
194       return true;
195       
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!");
202       
203     case BuiltinType::ObjCId:
204     case BuiltinType::ObjCClass:
205     case BuiltinType::ObjCSel:
206       llvm_unreachable("FIXME: Objective-C types are unsupported!");
207   }
208
209   llvm_unreachable("Invalid BuiltinType Kind!");
210 }
211
212 static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
213   QualType PointeeTy = PointerTy->getPointeeType();
214   const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
215   if (!BuiltinTy)
216     return false;
217     
218   // Check the qualifiers.
219   Qualifiers Quals = PointeeTy.getQualifiers();
220   Quals.removeConst();
221     
222   if (!Quals.empty())
223     return false;
224     
225   return TypeInfoIsInStandardLibrary(BuiltinTy);
226 }
227
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);
234   
235   // Type info for some pointer types to builtin types is defined in the
236   // standard library.
237   if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
238     return TypeInfoIsInStandardLibrary(PointerTy);
239
240   return false;
241 }
242
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();
249
250   // If RTTI is disabled, don't consider key functions.
251   if (!Context.getLangOpts().RTTI) return false;
252
253   if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
254     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
255     if (!RD->hasDefinition())
256       return false;
257
258     if (!RD->isDynamicClass())
259       return false;
260
261     return !CGM.getVTables().ShouldEmitVTableInThisTU(RD);
262   }
263   
264   return false;
265 }
266
267 /// IsIncompleteClassType - Returns whether the given record type is incomplete.
268 static bool IsIncompleteClassType(const RecordType *RecordTy) {
269   return !RecordTy->getDecl()->isCompleteDefinition();
270 }  
271
272 /// ContainsIncompleteClassType - Returns whether the given type contains an
273 /// incomplete class type. This is true if
274 ///
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
279 ///     class type.
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))
286       return true;
287   }
288   
289   if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
290     return ContainsIncompleteClassType(PointerTy->getPointeeType());
291   
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))
297       return true;
298     
299     return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
300   }
301   
302   return false;
303 }
304
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;
320   
321   switch (Ty->getLinkage()) {
322   case NoLinkage:
323   case InternalLinkage:
324   case UniqueExternalLinkage:
325     return llvm::GlobalValue::InternalLinkage;
326
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;
332     }
333
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);
340     }
341
342     return llvm::GlobalValue::LinkOnceODRLinkage;
343   }
344
345   llvm_unreachable("Invalid linkage!");
346 }
347
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)
354     return false;
355   
356   // Get the base.
357   CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
358   
359   // Check that the base is not virtual.
360   if (Base->isVirtual())
361     return false;
362   
363   // Check that the base is public.
364   if (Base->getAccessSpecifier() != AS_public)
365     return false;
366   
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())
372     return false;
373   
374   return true;
375 }
376
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";
387
388   const char *VTableName = 0;
389
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");
398
399   case Type::LValueReference:
400   case Type::RValueReference:
401     llvm_unreachable("References shouldn't get here");
402
403   case Type::Builtin:
404   // GCC treats vector and complex types as fundamental types.
405   case Type::Vector:
406   case Type::ExtVector:
407   case Type::Complex:
408   case Type::Atomic:
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";
413     break;
414
415   case Type::ConstantArray:
416   case Type::IncompleteArray:
417   case Type::VariableArray:
418     // abi::__array_type_info.
419     VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
420     break;
421
422   case Type::FunctionNoProto:
423   case Type::FunctionProto:
424     // abi::__function_type_info.
425     VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
426     break;
427
428   case Type::Enum:
429     // abi::__enum_type_info.
430     VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
431     break;
432
433   case Type::Record: {
434     const CXXRecordDecl *RD = 
435       cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
436     
437     if (!RD->hasDefinition() || !RD->getNumBases()) {
438       VTableName = ClassTypeInfo;
439     } else if (CanUseSingleInheritance(RD)) {
440       VTableName = SIClassTypeInfo;
441     } else {
442       VTableName = VMIClassTypeInfo;
443     }
444     
445     break;
446   }
447
448   case Type::ObjCObject:
449     // Ignore protocol qualifiers.
450     Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
451
452     // Handle id and Class.
453     if (isa<BuiltinType>(Ty)) {
454       VTableName = ClassTypeInfo;
455       break;
456     }
457
458     assert(isa<ObjCInterfaceType>(Ty));
459     // Fall through.
460
461   case Type::ObjCInterface:
462     if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
463       VTableName = SIClassTypeInfo;
464     } else {
465       VTableName = ClassTypeInfo;
466     }
467     break;
468
469   case Type::ObjCObjectPointer:
470   case Type::Pointer:
471     // abi::__pointer_type_info.
472     VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
473     break;
474
475   case Type::MemberPointer:
476     // abi::__pointer_to_member_type_info.
477     VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
478     break;
479   }
480
481   llvm::Constant *VTable = 
482     CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
483     
484   llvm::Type *PtrDiffTy = 
485     CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
486
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);
491
492   Fields.push_back(VTable);
493 }
494
495 // maybeUpdateRTTILinkage - Will update the linkage of the RTTI data structures
496 // from available_externally to the correct linkage if necessary. An example of
497 // this is:
498 //
499 //   struct A {
500 //     virtual void f();
501 //   };
502 //
503 //   const std::type_info &g() {
504 //     return typeid(A);
505 //   }
506 //
507 //   void A::f() { }
508 //
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.
515 static void 
516 maybeUpdateRTTILinkage(CodeGenModule &CGM, llvm::GlobalVariable *GV,
517                        QualType Ty) {
518   // We're only interested in globals with available_externally linkage.
519   if (!GV->hasAvailableExternallyLinkage())
520     return;
521
522   // Get the real linkage for the type.
523   llvm::GlobalVariable::LinkageTypes Linkage = getTypeInfoLinkage(CGM, Ty);
524
525   // If variable is supposed to have available_externally linkage, we don't
526   // need to do anything.
527   if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
528     return;
529
530   // Update the typeinfo linkage.
531   GV->setLinkage(Linkage);
532
533   // Get the typename global.
534   SmallString<256> OutName;
535   llvm::raw_svector_ostream Out(OutName);
536   CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
537   Out.flush();
538   StringRef Name = OutName.str();
539
540   llvm::GlobalVariable *TypeNameGV = CGM.getModule().getNamedGlobal(Name);
541
542   assert(TypeNameGV->hasAvailableExternallyLinkage() &&
543          "Type name has different linkage from type info!");
544
545   // And update its linkage.
546   TypeNameGV->setLinkage(Linkage);
547 }
548
549 llvm::Constant *RTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
550   // We want to operate on the canonical type.
551   Ty = CGM.getContext().getCanonicalType(Ty);
552
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);
557   Out.flush();
558   StringRef Name = OutName.str();
559
560   llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
561   if (OldGV && !OldGV->isDeclaration()) {
562     maybeUpdateRTTILinkage(CGM, OldGV, Ty);
563
564     return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
565   }
566
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);
571
572   // Emit the standard library with external linkage.
573   llvm::GlobalVariable::LinkageTypes Linkage;
574   if (IsStdLib)
575     Linkage = llvm::GlobalValue::ExternalLinkage;
576   else
577     Linkage = getTypeInfoLinkage(CGM, Ty);
578
579   // Add the vtable pointer.
580   BuildVTablePointer(cast<Type>(Ty));
581   
582   // And the name.
583   llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
584
585   Fields.push_back(llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy));
586
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");
595
596   // GCC treats vector types as fundamental types.
597   case Type::Builtin:
598   case Type::Vector:
599   case Type::ExtVector:
600   case Type::Complex:
601   case Type::BlockPointer:
602     // Itanium C++ ABI 2.9.5p4:
603     // abi::__fundamental_type_info adds no data members to std::type_info.
604     break;
605
606   case Type::LValueReference:
607   case Type::RValueReference:
608     llvm_unreachable("References shouldn't get here");
609
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.
615     break;
616
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.
621     break;
622
623   case Type::Enum:
624     // Itanium C++ ABI 2.9.5p5:
625     // abi::__enum_type_info adds no data members to std::type_info.
626     break;
627
628   case Type::Record: {
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.
633       break;
634     }
635     
636     if (CanUseSingleInheritance(RD))
637       BuildSIClassTypeInfo(RD);
638     else 
639       BuildVMIClassTypeInfo(RD);
640
641     break;
642   }
643
644   case Type::ObjCObject:
645   case Type::ObjCInterface:
646     BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
647     break;
648
649   case Type::ObjCObjectPointer:
650     BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
651     break; 
652       
653   case Type::Pointer:
654     BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
655     break;
656
657   case Type::MemberPointer:
658     BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
659     break;
660
661   case Type::Atomic:
662     // No fields, at least for the moment.
663     break;
664   }
665
666   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
667
668   llvm::GlobalVariable *GV = 
669     new llvm::GlobalVariable(CGM.getModule(), Init->getType(), 
670                              /*Constant=*/true, Linkage, Init, Name);
671   
672   // If there's already an old global variable, replace it with the new one.
673   if (OldGV) {
674     GV->takeName(OldGV);
675     llvm::Constant *NewPtr = 
676       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
677     OldGV->replaceAllUsesWith(NewPtr);
678     OldGV->eraseFromParent();
679   }
680
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
684   // compatibility.
685   if (const RecordType *RT = dyn_cast<RecordType>(Ty)) {
686     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
687
688     CGM.setTypeVisibility(GV, RD, CodeGenModule::TVK_ForRTTI);
689     CGM.setTypeVisibility(TypeName, RD, CodeGenModule::TVK_ForRTTIName);
690   } else {
691     Visibility TypeInfoVisibility = DefaultVisibility;
692     if (CGM.getCodeGenOpts().HiddenWeakVTables &&
693         Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
694       TypeInfoVisibility = HiddenVisibility;
695
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));
700   
701     TypeInfoVisibility = minVisibility(TypeInfoVisibility, Ty->getVisibility());
702     GV->setVisibility(CodeGenModule::GetLLVMVisibility(TypeInfoVisibility));
703   }
704
705   GV->setUnnamedAddr(true);
706
707   return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
708 }
709
710 /// ComputeQualifierFlags - Compute the pointer type info flags from the
711 /// given qualifier.
712 static unsigned ComputeQualifierFlags(Qualifiers Quals) {
713   unsigned Flags = 0;
714
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;
721
722   return Flags;
723 }
724
725 /// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
726 /// for the given Objective-C object type.
727 void RTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
728   // Drop qualifiers.
729   const Type *T = OT->getBaseType().getTypePtr();
730   assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
731
732   // The builtin types are abi::__class_type_infos and don't require
733   // extra fields.
734   if (isa<BuiltinType>(T)) return;
735
736   ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
737   ObjCInterfaceDecl *Super = Class->getSuperClass();
738
739   // Root classes are also __class_type_info.
740   if (!Super) return;
741
742   QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
743
744   // Everything else is single inheritance.
745   llvm::Constant *BaseTypeInfo = RTTIBuilder(CGM).BuildTypeInfo(SuperTy);
746   Fields.push_back(BaseTypeInfo);
747 }
748
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);
758 }
759
760 namespace {
761   /// SeenBases - Contains virtual and non-virtual bases seen when traversing
762   /// a class hierarchy.
763   struct SeenBases {
764     llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
765     llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
766   };
767 }
768
769 /// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
770 /// abi::__vmi_class_type_info.
771 ///
772 static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base, 
773                                              SeenBases &Bases) {
774   
775   unsigned Flags = 0;
776   
777   const CXXRecordDecl *BaseDecl = 
778     cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
779   
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
784       // shaped.
785       Flags |= RTTIBuilder::VMI_DiamondShaped;
786     } else {
787       if (Bases.NonVirtualBases.count(BaseDecl))
788         Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
789     }
790   } else {
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;
796     } else {
797       if (Bases.VirtualBases.count(BaseDecl))
798         Flags |= RTTIBuilder::VMI_NonDiamondRepeat;
799     }
800   }
801
802   // Walk all bases.
803   for (CXXRecordDecl::base_class_const_iterator I = BaseDecl->bases_begin(),
804        E = BaseDecl->bases_end(); I != E; ++I) 
805     Flags |= ComputeVMIClassTypeInfoFlags(I, Bases);
806   
807   return Flags;
808 }
809
810 static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
811   unsigned Flags = 0;
812   SeenBases Bases;
813   
814   // Walk all bases.
815   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
816        E = RD->bases_end(); I != E; ++I) 
817     Flags |= ComputeVMIClassTypeInfoFlags(I, Bases);
818   
819   return Flags;
820 }
821
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);
828   
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));
835
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()));
840   
841   if (!RD->getNumBases())
842     return;
843   
844   llvm::Type *LongLTy = 
845     CGM.getTypes().ConvertType(CGM.getContext().LongTy);
846
847   // Now add the base class descriptions.
848   
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:
852   //
853   //   struct abi::__base_class_type_info {
854   //   public:
855   //     const __class_type_info *__base_type;
856   //     long __offset_flags;
857   //
858   //     enum __offset_flags_masks {
859   //       __virtual_mask = 0x1,
860   //       __public_mask = 0x2,
861   //       __offset_shift = 8
862   //     };
863   //   };
864   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
865        E = RD->bases_end(); I != E; ++I) {
866     const CXXBaseSpecifier *Base = I;
867
868     // The __base_type member points to the RTTI for the base type.
869     Fields.push_back(RTTIBuilder(CGM).BuildTypeInfo(Base->getType()));
870
871     const CXXRecordDecl *BaseDecl = 
872       cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
873
874     int64_t OffsetFlags = 0;
875     
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).
880     CharUnits Offset;
881     if (Base->isVirtual())
882       Offset = 
883         CGM.getVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
884     else {
885       const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
886       Offset = Layout.getBaseClassOffset(BaseDecl);
887     };
888     
889     OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
890     
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;
897
898     Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
899   }
900 }
901
902 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
903 /// used for pointer types.
904 void RTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {  
905   Qualifiers Quals;
906   QualType UnqualifiedPointeeTy = 
907     CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
908   
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);
913
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;
919
920   llvm::Type *UnsignedIntLTy = 
921     CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
922   Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
923   
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);
930 }
931
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();
936   
937   Qualifiers Quals;
938   QualType UnqualifiedPointeeTy = 
939     CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
940   
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);
945
946   const RecordType *ClassType = cast<RecordType>(Ty->getClass());
947
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;
953
954   if (IsIncompleteClassType(ClassType))
955     Flags |= PTI_ContainingClassIncomplete;
956   
957   llvm::Type *UnsignedIntLTy = 
958     CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
959   Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
960   
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);
967
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)));
973 }
974
975 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
976                                                        bool ForEH) {
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);
982   
983   if (ForEH && Ty->isObjCObjectPointerType() &&
984       LangOpts.ObjCRuntime.isGNUFamily())
985     return ObjCRuntime->GetEHType(Ty);
986
987   return RTTIBuilder(*this).BuildTypeInfo(Ty);
988 }
989
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);
996 }
997
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]);
1011 }