CGObjCMac.cpp revision 653f1b1bf293a9bd96fd4dd6372e779cc7af1597
1//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===// 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 provides Objective-C code generation targetting the Apple runtime. 11// 12//===----------------------------------------------------------------------===// 13 14#include "CGObjCRuntime.h" 15 16#include "CodeGenModule.h" 17#include "CodeGenFunction.h" 18#include "clang/AST/ASTContext.h" 19#include "clang/AST/Decl.h" 20#include "clang/AST/DeclObjC.h" 21#include "clang/Basic/LangOptions.h" 22 23#include "llvm/Intrinsics.h" 24#include "llvm/Module.h" 25#include "llvm/ADT/DenseSet.h" 26#include "llvm/Target/TargetData.h" 27#include <sstream> 28 29using namespace clang; 30using namespace CodeGen; 31 32// Common CGObjCRuntime functions, these don't belong here, but they 33// don't belong in CGObjCRuntime either so we will live with it for 34// now. 35 36const llvm::StructType * 37CGObjCRuntime::GetConcreteClassStruct(CodeGen::CodeGenModule &CGM, 38 const ObjCInterfaceDecl *OID) { 39 assert(!OID->isForwardDecl() && "Invalid interface decl!"); 40 const RecordDecl *RD = CGM.getContext().addRecordToClass(OID); 41 return cast<llvm::StructType>(CGM.getTypes().ConvertTagDeclType(RD)); 42} 43 44 45/// LookupFieldDeclForIvar - looks up a field decl in the laid out 46/// storage which matches this 'ivar'. 47/// 48static const FieldDecl *LookupFieldDeclForIvar(ASTContext &Context, 49 const ObjCInterfaceDecl *OID, 50 const ObjCIvarDecl *OIVD, 51 const ObjCInterfaceDecl *&Found) { 52 assert(!OID->isForwardDecl() && "Invalid interface decl!"); 53 const RecordDecl *RecordForDecl = Context.addRecordToClass(OID); 54 assert(RecordForDecl && "lookupFieldDeclForIvar no storage for class"); 55 DeclContext::lookup_const_result Lookup = 56 RecordForDecl->lookup(Context, OIVD->getDeclName()); 57 58 if (Lookup.first != Lookup.second) { 59 Found = OID; 60 return cast<FieldDecl>(*Lookup.first); 61 } 62 63 // If lookup failed, try the superclass. 64 // 65 // FIXME: This is slow, we shouldn't need to do this. 66 const ObjCInterfaceDecl *Super = OID->getSuperClass(); 67 assert(OID && "field decl not found!"); 68 return LookupFieldDeclForIvar(Context, Super, OIVD, Found); 69} 70 71uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM, 72 const ObjCInterfaceDecl *OID, 73 const ObjCIvarDecl *Ivar) { 74 assert(!OID->isForwardDecl() && "Invalid interface decl!"); 75 const ObjCInterfaceDecl *Container; 76 const FieldDecl *Field = 77 LookupFieldDeclForIvar(CGM.getContext(), OID, Ivar, Container); 78 QualType T = CGM.getContext().getObjCInterfaceType(Container); 79 const llvm::StructType *STy = GetConcreteClassStruct(CGM, Container); 80 const llvm::StructLayout *Layout = 81 CGM.getTargetData().getStructLayout(STy); 82 if (!Field->isBitField()) 83 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field)); 84 85 // FIXME. Must be a better way of getting a bitfield base offset. 86 CodeGenTypes::BitFieldInfo BFI = CGM.getTypes().getBitFieldInfo(Field); 87 // FIXME: The "field no" for bitfields is something completely 88 // different; it is the offset in multiples of the base type size! 89 uint64_t Offset = CGM.getTypes().getLLVMFieldNo(Field); 90 const llvm::Type *Ty = 91 CGM.getTypes().ConvertTypeForMemRecursive(Field->getType()); 92 Offset *= CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty); 93 return (Offset + BFI.Begin) / 8; 94} 95 96LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF, 97 const ObjCInterfaceDecl *OID, 98 llvm::Value *BaseValue, 99 const ObjCIvarDecl *Ivar, 100 unsigned CVRQualifiers, 101 llvm::Value *Offset) { 102 // Force generation of the codegen information for this structure. 103 // 104 // FIXME: Remove once we don't use the bit-field lookup map. 105 (void) GetConcreteClassStruct(CGF.CGM, OID); 106 107 // FIXME: For now, we use an implementation based on just computing 108 // the offset and calculating things directly. For optimization 109 // purposes, it would be cleaner to use a GEP on the proper type 110 // since the structure layout is fixed; however for that we need to 111 // be able to walk the class chain for an Ivar. 112 const ObjCInterfaceDecl *Container; 113 const FieldDecl *Field = 114 LookupFieldDeclForIvar(CGF.CGM.getContext(), OID, Ivar, Container); 115 116 // (char *) BaseValue 117 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 118 llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, I8Ptr); 119 // (char*)BaseValue + Offset_symbol 120 V = CGF.Builder.CreateGEP(V, Offset, "add.ptr"); 121 // (type *)((char*)BaseValue + Offset_symbol) 122 const llvm::Type *IvarTy = 123 CGF.CGM.getTypes().ConvertTypeForMem(Ivar->getType()); 124 llvm::Type *ptrIvarTy = llvm::PointerType::getUnqual(IvarTy); 125 V = CGF.Builder.CreateBitCast(V, ptrIvarTy); 126 127 if (Ivar->isBitField()) { 128 QualType FieldTy = Field->getType(); 129 CodeGenTypes::BitFieldInfo bitFieldInfo = 130 CGF.CGM.getTypes().getBitFieldInfo(Field); 131 return LValue::MakeBitfield(V, bitFieldInfo.Begin % 8, bitFieldInfo.Size, 132 FieldTy->isSignedIntegerType(), 133 FieldTy.getCVRQualifiers()|CVRQualifiers); 134 } 135 136 LValue LV = LValue::MakeAddr(V, 137 Ivar->getType().getCVRQualifiers()|CVRQualifiers, 138 CGF.CGM.getContext().getObjCGCAttrKind(Ivar->getType())); 139 LValue::SetObjCIvar(LV, true); 140 return LV; 141} 142 143/// 144 145namespace { 146 147 typedef std::vector<llvm::Constant*> ConstantVector; 148 149 // FIXME: We should find a nicer way to make the labels for 150 // metadata, string concatenation is lame. 151 152class ObjCCommonTypesHelper { 153protected: 154 CodeGen::CodeGenModule &CGM; 155 156public: 157 const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy; 158 const llvm::Type *Int8PtrTy; 159 160 /// ObjectPtrTy - LLVM type for object handles (typeof(id)) 161 const llvm::Type *ObjectPtrTy; 162 163 /// PtrObjectPtrTy - LLVM type for id * 164 const llvm::Type *PtrObjectPtrTy; 165 166 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL)) 167 const llvm::Type *SelectorPtrTy; 168 /// ProtocolPtrTy - LLVM type for external protocol handles 169 /// (typeof(Protocol)) 170 const llvm::Type *ExternalProtocolPtrTy; 171 172 // SuperCTy - clang type for struct objc_super. 173 QualType SuperCTy; 174 // SuperPtrCTy - clang type for struct objc_super *. 175 QualType SuperPtrCTy; 176 177 /// SuperTy - LLVM type for struct objc_super. 178 const llvm::StructType *SuperTy; 179 /// SuperPtrTy - LLVM type for struct objc_super *. 180 const llvm::Type *SuperPtrTy; 181 182 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t 183 /// in GCC parlance). 184 const llvm::StructType *PropertyTy; 185 186 /// PropertyListTy - LLVM type for struct objc_property_list 187 /// (_prop_list_t in GCC parlance). 188 const llvm::StructType *PropertyListTy; 189 /// PropertyListPtrTy - LLVM type for struct objc_property_list*. 190 const llvm::Type *PropertyListPtrTy; 191 192 // MethodTy - LLVM type for struct objc_method. 193 const llvm::StructType *MethodTy; 194 195 /// CacheTy - LLVM type for struct objc_cache. 196 const llvm::Type *CacheTy; 197 /// CachePtrTy - LLVM type for struct objc_cache *. 198 const llvm::Type *CachePtrTy; 199 200 llvm::Constant *getGetPropertyFn() { 201 CodeGen::CodeGenTypes &Types = CGM.getTypes(); 202 ASTContext &Ctx = CGM.getContext(); 203 // id objc_getProperty (id, SEL, ptrdiff_t, bool) 204 llvm::SmallVector<QualType,16> Params; 205 QualType IdType = Ctx.getObjCIdType(); 206 QualType SelType = Ctx.getObjCSelType(); 207 Params.push_back(IdType); 208 Params.push_back(SelType); 209 Params.push_back(Ctx.LongTy); 210 Params.push_back(Ctx.BoolTy); 211 const llvm::FunctionType *FTy = 212 Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false); 213 return CGM.CreateRuntimeFunction(FTy, "objc_getProperty"); 214 } 215 216 llvm::Constant *getSetPropertyFn() { 217 CodeGen::CodeGenTypes &Types = CGM.getTypes(); 218 ASTContext &Ctx = CGM.getContext(); 219 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool) 220 llvm::SmallVector<QualType,16> Params; 221 QualType IdType = Ctx.getObjCIdType(); 222 QualType SelType = Ctx.getObjCSelType(); 223 Params.push_back(IdType); 224 Params.push_back(SelType); 225 Params.push_back(Ctx.LongTy); 226 Params.push_back(IdType); 227 Params.push_back(Ctx.BoolTy); 228 Params.push_back(Ctx.BoolTy); 229 const llvm::FunctionType *FTy = 230 Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false); 231 return CGM.CreateRuntimeFunction(FTy, "objc_setProperty"); 232 } 233 234 llvm::Constant *getEnumerationMutationFn() { 235 // void objc_enumerationMutation (id) 236 std::vector<const llvm::Type*> Args; 237 Args.push_back(ObjectPtrTy); 238 llvm::FunctionType *FTy = 239 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false); 240 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation"); 241 } 242 243 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function. 244 llvm::Constant *getGcReadWeakFn() { 245 // id objc_read_weak (id *) 246 std::vector<const llvm::Type*> Args; 247 Args.push_back(ObjectPtrTy->getPointerTo()); 248 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false); 249 return CGM.CreateRuntimeFunction(FTy, "objc_read_weak"); 250 } 251 252 /// GcAssignWeakFn -- LLVM objc_assign_weak function. 253 llvm::Constant *getGcAssignWeakFn() { 254 // id objc_assign_weak (id, id *) 255 std::vector<const llvm::Type*> Args(1, ObjectPtrTy); 256 Args.push_back(ObjectPtrTy->getPointerTo()); 257 llvm::FunctionType *FTy = 258 llvm::FunctionType::get(ObjectPtrTy, Args, false); 259 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak"); 260 } 261 262 /// GcAssignGlobalFn -- LLVM objc_assign_global function. 263 llvm::Constant *getGcAssignGlobalFn() { 264 // id objc_assign_global(id, id *) 265 std::vector<const llvm::Type*> Args(1, ObjectPtrTy); 266 Args.push_back(ObjectPtrTy->getPointerTo()); 267 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false); 268 return CGM.CreateRuntimeFunction(FTy, "objc_assign_global"); 269 } 270 271 /// GcAssignIvarFn -- LLVM objc_assign_ivar function. 272 llvm::Constant *getGcAssignIvarFn() { 273 // id objc_assign_ivar(id, id *) 274 std::vector<const llvm::Type*> Args(1, ObjectPtrTy); 275 Args.push_back(ObjectPtrTy->getPointerTo()); 276 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false); 277 return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar"); 278 } 279 280 /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function. 281 llvm::Constant *getGcAssignStrongCastFn() { 282 // id objc_assign_global(id, id *) 283 std::vector<const llvm::Type*> Args(1, ObjectPtrTy); 284 Args.push_back(ObjectPtrTy->getPointerTo()); 285 llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false); 286 return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast"); 287 } 288 289 /// ExceptionThrowFn - LLVM objc_exception_throw function. 290 llvm::Constant *getExceptionThrowFn() { 291 // void objc_exception_throw(id) 292 std::vector<const llvm::Type*> Args(1, ObjectPtrTy); 293 llvm::FunctionType *FTy = 294 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false); 295 return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw"); 296 } 297 298 /// SyncEnterFn - LLVM object_sync_enter function. 299 llvm::Constant *getSyncEnterFn() { 300 // void objc_sync_enter (id) 301 std::vector<const llvm::Type*> Args(1, ObjectPtrTy); 302 llvm::FunctionType *FTy = 303 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false); 304 return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter"); 305 } 306 307 /// SyncExitFn - LLVM object_sync_exit function. 308 llvm::Constant *getSyncExitFn() { 309 // void objc_sync_exit (id) 310 std::vector<const llvm::Type*> Args(1, ObjectPtrTy); 311 llvm::FunctionType *FTy = 312 llvm::FunctionType::get(llvm::Type::VoidTy, Args, false); 313 return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit"); 314 } 315 316 ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm); 317 ~ObjCCommonTypesHelper(){} 318}; 319 320/// ObjCTypesHelper - Helper class that encapsulates lazy 321/// construction of varies types used during ObjC generation. 322class ObjCTypesHelper : public ObjCCommonTypesHelper { 323private: 324 325 llvm::Constant *getMessageSendFn() { 326 // id objc_msgSend (id, SEL, ...) 327 std::vector<const llvm::Type*> Params; 328 Params.push_back(ObjectPtrTy); 329 Params.push_back(SelectorPtrTy); 330 return 331 CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 332 Params, true), 333 "objc_msgSend"); 334 } 335 336 llvm::Constant *getMessageSendStretFn() { 337 // id objc_msgSend_stret (id, SEL, ...) 338 std::vector<const llvm::Type*> Params; 339 Params.push_back(ObjectPtrTy); 340 Params.push_back(SelectorPtrTy); 341 return 342 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 343 Params, true), 344 "objc_msgSend_stret"); 345 346 } 347 348 llvm::Constant *getMessageSendFpretFn() { 349 // FIXME: This should be long double on x86_64? 350 // [double | long double] objc_msgSend_fpret(id self, SEL op, ...) 351 std::vector<const llvm::Type*> Params; 352 Params.push_back(ObjectPtrTy); 353 Params.push_back(SelectorPtrTy); 354 return 355 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy, 356 Params, 357 true), 358 "objc_msgSend_fpret"); 359 360 } 361 362 llvm::Constant *getMessageSendSuperFn() { 363 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...) 364 std::vector<const llvm::Type*> Params; 365 Params.push_back(SuperPtrTy); 366 Params.push_back(SelectorPtrTy); 367 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 368 Params, true), 369 "objc_msgSendSuper"); 370 } 371 llvm::Constant *getMessageSendSuperStretFn() { 372 // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super, 373 // SEL op, ...) 374 std::vector<const llvm::Type*> Params; 375 Params.push_back(Int8PtrTy); 376 Params.push_back(SuperPtrTy); 377 Params.push_back(SelectorPtrTy); 378 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 379 Params, true), 380 "objc_msgSendSuper_stret"); 381 } 382 383 llvm::Constant *getMessageSendSuperFpretFn() { 384 // There is no objc_msgSendSuper_fpret? How can that work? 385 return getMessageSendSuperFn(); 386 } 387 388public: 389 /// SymtabTy - LLVM type for struct objc_symtab. 390 const llvm::StructType *SymtabTy; 391 /// SymtabPtrTy - LLVM type for struct objc_symtab *. 392 const llvm::Type *SymtabPtrTy; 393 /// ModuleTy - LLVM type for struct objc_module. 394 const llvm::StructType *ModuleTy; 395 396 /// ProtocolTy - LLVM type for struct objc_protocol. 397 const llvm::StructType *ProtocolTy; 398 /// ProtocolPtrTy - LLVM type for struct objc_protocol *. 399 const llvm::Type *ProtocolPtrTy; 400 /// ProtocolExtensionTy - LLVM type for struct 401 /// objc_protocol_extension. 402 const llvm::StructType *ProtocolExtensionTy; 403 /// ProtocolExtensionTy - LLVM type for struct 404 /// objc_protocol_extension *. 405 const llvm::Type *ProtocolExtensionPtrTy; 406 /// MethodDescriptionTy - LLVM type for struct 407 /// objc_method_description. 408 const llvm::StructType *MethodDescriptionTy; 409 /// MethodDescriptionListTy - LLVM type for struct 410 /// objc_method_description_list. 411 const llvm::StructType *MethodDescriptionListTy; 412 /// MethodDescriptionListPtrTy - LLVM type for struct 413 /// objc_method_description_list *. 414 const llvm::Type *MethodDescriptionListPtrTy; 415 /// ProtocolListTy - LLVM type for struct objc_property_list. 416 const llvm::Type *ProtocolListTy; 417 /// ProtocolListPtrTy - LLVM type for struct objc_property_list*. 418 const llvm::Type *ProtocolListPtrTy; 419 /// CategoryTy - LLVM type for struct objc_category. 420 const llvm::StructType *CategoryTy; 421 /// ClassTy - LLVM type for struct objc_class. 422 const llvm::StructType *ClassTy; 423 /// ClassPtrTy - LLVM type for struct objc_class *. 424 const llvm::Type *ClassPtrTy; 425 /// ClassExtensionTy - LLVM type for struct objc_class_ext. 426 const llvm::StructType *ClassExtensionTy; 427 /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *. 428 const llvm::Type *ClassExtensionPtrTy; 429 // IvarTy - LLVM type for struct objc_ivar. 430 const llvm::StructType *IvarTy; 431 /// IvarListTy - LLVM type for struct objc_ivar_list. 432 const llvm::Type *IvarListTy; 433 /// IvarListPtrTy - LLVM type for struct objc_ivar_list *. 434 const llvm::Type *IvarListPtrTy; 435 /// MethodListTy - LLVM type for struct objc_method_list. 436 const llvm::Type *MethodListTy; 437 /// MethodListPtrTy - LLVM type for struct objc_method_list *. 438 const llvm::Type *MethodListPtrTy; 439 440 /// ExceptionDataTy - LLVM type for struct _objc_exception_data. 441 const llvm::Type *ExceptionDataTy; 442 443 /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function. 444 llvm::Constant *getExceptionTryEnterFn() { 445 std::vector<const llvm::Type*> Params; 446 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy)); 447 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 448 Params, false), 449 "objc_exception_try_enter"); 450 } 451 452 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function. 453 llvm::Constant *getExceptionTryExitFn() { 454 std::vector<const llvm::Type*> Params; 455 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy)); 456 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 457 Params, false), 458 "objc_exception_try_exit"); 459 } 460 461 /// ExceptionExtractFn - LLVM objc_exception_extract function. 462 llvm::Constant *getExceptionExtractFn() { 463 std::vector<const llvm::Type*> Params; 464 Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy)); 465 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 466 Params, false), 467 "objc_exception_extract"); 468 469 } 470 471 /// ExceptionMatchFn - LLVM objc_exception_match function. 472 llvm::Constant *getExceptionMatchFn() { 473 std::vector<const llvm::Type*> Params; 474 Params.push_back(ClassPtrTy); 475 Params.push_back(ObjectPtrTy); 476 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty, 477 Params, false), 478 "objc_exception_match"); 479 480 } 481 482 /// SetJmpFn - LLVM _setjmp function. 483 llvm::Constant *getSetJmpFn() { 484 std::vector<const llvm::Type*> Params; 485 Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty)); 486 return 487 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty, 488 Params, false), 489 "_setjmp"); 490 491 } 492 493public: 494 ObjCTypesHelper(CodeGen::CodeGenModule &cgm); 495 ~ObjCTypesHelper() {} 496 497 498 llvm::Constant *getSendFn(bool IsSuper) { 499 return IsSuper ? getMessageSendSuperFn() : getMessageSendFn(); 500 } 501 502 llvm::Constant *getSendStretFn(bool IsSuper) { 503 return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn(); 504 } 505 506 llvm::Constant *getSendFpretFn(bool IsSuper) { 507 return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn(); 508 } 509}; 510 511/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's 512/// modern abi 513class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper { 514public: 515 516 // MethodListnfABITy - LLVM for struct _method_list_t 517 const llvm::StructType *MethodListnfABITy; 518 519 // MethodListnfABIPtrTy - LLVM for struct _method_list_t* 520 const llvm::Type *MethodListnfABIPtrTy; 521 522 // ProtocolnfABITy = LLVM for struct _protocol_t 523 const llvm::StructType *ProtocolnfABITy; 524 525 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t* 526 const llvm::Type *ProtocolnfABIPtrTy; 527 528 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list 529 const llvm::StructType *ProtocolListnfABITy; 530 531 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list* 532 const llvm::Type *ProtocolListnfABIPtrTy; 533 534 // ClassnfABITy - LLVM for struct _class_t 535 const llvm::StructType *ClassnfABITy; 536 537 // ClassnfABIPtrTy - LLVM for struct _class_t* 538 const llvm::Type *ClassnfABIPtrTy; 539 540 // IvarnfABITy - LLVM for struct _ivar_t 541 const llvm::StructType *IvarnfABITy; 542 543 // IvarListnfABITy - LLVM for struct _ivar_list_t 544 const llvm::StructType *IvarListnfABITy; 545 546 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t* 547 const llvm::Type *IvarListnfABIPtrTy; 548 549 // ClassRonfABITy - LLVM for struct _class_ro_t 550 const llvm::StructType *ClassRonfABITy; 551 552 // ImpnfABITy - LLVM for id (*)(id, SEL, ...) 553 const llvm::Type *ImpnfABITy; 554 555 // CategorynfABITy - LLVM for struct _category_t 556 const llvm::StructType *CategorynfABITy; 557 558 // New types for nonfragile abi messaging. 559 560 // MessageRefTy - LLVM for: 561 // struct _message_ref_t { 562 // IMP messenger; 563 // SEL name; 564 // }; 565 const llvm::StructType *MessageRefTy; 566 // MessageRefCTy - clang type for struct _message_ref_t 567 QualType MessageRefCTy; 568 569 // MessageRefPtrTy - LLVM for struct _message_ref_t* 570 const llvm::Type *MessageRefPtrTy; 571 // MessageRefCPtrTy - clang type for struct _message_ref_t* 572 QualType MessageRefCPtrTy; 573 574 // MessengerTy - Type of the messenger (shown as IMP above) 575 const llvm::FunctionType *MessengerTy; 576 577 // SuperMessageRefTy - LLVM for: 578 // struct _super_message_ref_t { 579 // SUPER_IMP messenger; 580 // SEL name; 581 // }; 582 const llvm::StructType *SuperMessageRefTy; 583 584 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t* 585 const llvm::Type *SuperMessageRefPtrTy; 586 587 llvm::Constant *getMessageSendFixupFn() { 588 // id objc_msgSend_fixup(id, struct message_ref_t*, ...) 589 std::vector<const llvm::Type*> Params; 590 Params.push_back(ObjectPtrTy); 591 Params.push_back(MessageRefPtrTy); 592 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 593 Params, true), 594 "objc_msgSend_fixup"); 595 } 596 597 llvm::Constant *getMessageSendFpretFixupFn() { 598 // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...) 599 std::vector<const llvm::Type*> Params; 600 Params.push_back(ObjectPtrTy); 601 Params.push_back(MessageRefPtrTy); 602 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 603 Params, true), 604 "objc_msgSend_fpret_fixup"); 605 } 606 607 llvm::Constant *getMessageSendStretFixupFn() { 608 // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...) 609 std::vector<const llvm::Type*> Params; 610 Params.push_back(ObjectPtrTy); 611 Params.push_back(MessageRefPtrTy); 612 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 613 Params, true), 614 "objc_msgSend_stret_fixup"); 615 } 616 617 llvm::Constant *getMessageSendIdFixupFn() { 618 // id objc_msgSendId_fixup(id, struct message_ref_t*, ...) 619 std::vector<const llvm::Type*> Params; 620 Params.push_back(ObjectPtrTy); 621 Params.push_back(MessageRefPtrTy); 622 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 623 Params, true), 624 "objc_msgSendId_fixup"); 625 } 626 627 llvm::Constant *getMessageSendIdStretFixupFn() { 628 // id objc_msgSendId_stret_fixup(id, struct message_ref_t*, ...) 629 std::vector<const llvm::Type*> Params; 630 Params.push_back(ObjectPtrTy); 631 Params.push_back(MessageRefPtrTy); 632 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 633 Params, true), 634 "objc_msgSendId_stret_fixup"); 635 } 636 llvm::Constant *getMessageSendSuper2FixupFn() { 637 // id objc_msgSendSuper2_fixup (struct objc_super *, 638 // struct _super_message_ref_t*, ...) 639 std::vector<const llvm::Type*> Params; 640 Params.push_back(SuperPtrTy); 641 Params.push_back(SuperMessageRefPtrTy); 642 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 643 Params, true), 644 "objc_msgSendSuper2_fixup"); 645 } 646 647 llvm::Constant *getMessageSendSuper2StretFixupFn() { 648 // id objc_msgSendSuper2_stret_fixup(struct objc_super *, 649 // struct _super_message_ref_t*, ...) 650 std::vector<const llvm::Type*> Params; 651 Params.push_back(SuperPtrTy); 652 Params.push_back(SuperMessageRefPtrTy); 653 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, 654 Params, true), 655 "objc_msgSendSuper2_stret_fixup"); 656 } 657 658 659 660 /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C 661 /// exception personality function. 662 llvm::Value *getEHPersonalityPtr() { 663 llvm::Constant *Personality = 664 CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty, 665 std::vector<const llvm::Type*>(), 666 true), 667 "__objc_personality_v0"); 668 return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy); 669 } 670 671 llvm::Constant *getUnwindResumeOrRethrowFn() { 672 std::vector<const llvm::Type*> Params; 673 Params.push_back(Int8PtrTy); 674 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 675 Params, false), 676 "_Unwind_Resume_or_Rethrow"); 677 } 678 679 llvm::Constant *getObjCEndCatchFn() { 680 std::vector<const llvm::Type*> Params; 681 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy, 682 Params, false), 683 "objc_end_catch"); 684 685 } 686 687 llvm::Constant *getObjCBeginCatchFn() { 688 std::vector<const llvm::Type*> Params; 689 Params.push_back(Int8PtrTy); 690 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy, 691 Params, false), 692 "objc_begin_catch"); 693 } 694 695 const llvm::StructType *EHTypeTy; 696 const llvm::Type *EHTypePtrTy; 697 698 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm); 699 ~ObjCNonFragileABITypesHelper(){} 700}; 701 702class CGObjCCommonMac : public CodeGen::CGObjCRuntime { 703public: 704 // FIXME - accessibility 705 class GC_IVAR { 706 public: 707 unsigned int ivar_bytepos; 708 unsigned int ivar_size; 709 GC_IVAR() : ivar_bytepos(0), ivar_size(0) {} 710 }; 711 712 class SKIP_SCAN { 713 public: 714 unsigned int skip; 715 unsigned int scan; 716 SKIP_SCAN() : skip(0), scan(0) {} 717 }; 718 719protected: 720 CodeGen::CodeGenModule &CGM; 721 // FIXME! May not be needing this after all. 722 unsigned ObjCABI; 723 724 // gc ivar layout bitmap calculation helper caches. 725 llvm::SmallVector<GC_IVAR, 16> SkipIvars; 726 llvm::SmallVector<GC_IVAR, 16> IvarsInfo; 727 llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars; 728 729 /// LazySymbols - Symbols to generate a lazy reference for. See 730 /// DefinedSymbols and FinishModule(). 731 std::set<IdentifierInfo*> LazySymbols; 732 733 /// DefinedSymbols - External symbols which are defined by this 734 /// module. The symbols in this list and LazySymbols are used to add 735 /// special linker symbols which ensure that Objective-C modules are 736 /// linked properly. 737 std::set<IdentifierInfo*> DefinedSymbols; 738 739 /// ClassNames - uniqued class names. 740 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames; 741 742 /// MethodVarNames - uniqued method variable names. 743 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames; 744 745 /// MethodVarTypes - uniqued method type signatures. We have to use 746 /// a StringMap here because have no other unique reference. 747 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes; 748 749 /// MethodDefinitions - map of methods which have been defined in 750 /// this translation unit. 751 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions; 752 753 /// PropertyNames - uniqued method variable names. 754 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames; 755 756 /// ClassReferences - uniqued class references. 757 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences; 758 759 /// SelectorReferences - uniqued selector references. 760 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences; 761 762 /// Protocols - Protocols for which an objc_protocol structure has 763 /// been emitted. Forward declarations are handled by creating an 764 /// empty structure whose initializer is filled in when/if defined. 765 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols; 766 767 /// DefinedProtocols - Protocols which have actually been 768 /// defined. We should not need this, see FIXME in GenerateProtocol. 769 llvm::DenseSet<IdentifierInfo*> DefinedProtocols; 770 771 /// DefinedClasses - List of defined classes. 772 std::vector<llvm::GlobalValue*> DefinedClasses; 773 774 /// DefinedCategories - List of defined categories. 775 std::vector<llvm::GlobalValue*> DefinedCategories; 776 777 /// UsedGlobals - List of globals to pack into the llvm.used metadata 778 /// to prevent them from being clobbered. 779 std::vector<llvm::GlobalVariable*> UsedGlobals; 780 781 /// GetNameForMethod - Return a name for the given method. 782 /// \param[out] NameOut - The return value. 783 void GetNameForMethod(const ObjCMethodDecl *OMD, 784 const ObjCContainerDecl *CD, 785 std::string &NameOut); 786 787 /// GetMethodVarName - Return a unique constant for the given 788 /// selector's name. The return value has type char *. 789 llvm::Constant *GetMethodVarName(Selector Sel); 790 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident); 791 llvm::Constant *GetMethodVarName(const std::string &Name); 792 793 /// GetMethodVarType - Return a unique constant for the given 794 /// selector's name. The return value has type char *. 795 796 // FIXME: This is a horrible name. 797 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D); 798 llvm::Constant *GetMethodVarType(const FieldDecl *D); 799 800 /// GetPropertyName - Return a unique constant for the given 801 /// name. The return value has type char *. 802 llvm::Constant *GetPropertyName(IdentifierInfo *Ident); 803 804 // FIXME: This can be dropped once string functions are unified. 805 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD, 806 const Decl *Container); 807 808 /// GetClassName - Return a unique constant for the given selector's 809 /// name. The return value has type char *. 810 llvm::Constant *GetClassName(IdentifierInfo *Ident); 811 812 /// BuildIvarLayout - Builds ivar layout bitmap for the class 813 /// implementation for the __strong or __weak case. 814 /// 815 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI, 816 bool ForStrongLayout); 817 818 void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI, 819 const llvm::StructLayout *Layout, 820 const RecordDecl *RD, 821 const llvm::SmallVectorImpl<FieldDecl*> &RecFields, 822 unsigned int BytePos, bool ForStrongLayout, 823 int &Index, int &SkIndex, bool &HasUnion); 824 825 /// GetIvarLayoutName - Returns a unique constant for the given 826 /// ivar layout bitmap. 827 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident, 828 const ObjCCommonTypesHelper &ObjCTypes); 829 830 /// EmitPropertyList - Emit the given property list. The return 831 /// value has type PropertyListPtrTy. 832 llvm::Constant *EmitPropertyList(const std::string &Name, 833 const Decl *Container, 834 const ObjCContainerDecl *OCD, 835 const ObjCCommonTypesHelper &ObjCTypes); 836 837 /// GetProtocolRef - Return a reference to the internal protocol 838 /// description, creating an empty one if it has not been 839 /// defined. The return value has type ProtocolPtrTy. 840 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD); 841 842 /// GetFieldBaseOffset - return's field byte offset. 843 uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI, 844 const llvm::StructLayout *Layout, 845 const FieldDecl *Field); 846 847 /// CreateMetadataVar - Create a global variable with internal 848 /// linkage for use by the Objective-C runtime. 849 /// 850 /// This is a convenience wrapper which not only creates the 851 /// variable, but also sets the section and alignment and adds the 852 /// global to the UsedGlobals list. 853 /// 854 /// \param Name - The variable name. 855 /// \param Init - The variable initializer; this is also used to 856 /// define the type of the variable. 857 /// \param Section - The section the variable should go into, or 0. 858 /// \param Align - The alignment for the variable, or 0. 859 /// \param AddToUsed - Whether the variable should be added to 860 /// "llvm.used". 861 llvm::GlobalVariable *CreateMetadataVar(const std::string &Name, 862 llvm::Constant *Init, 863 const char *Section, 864 unsigned Align, 865 bool AddToUsed); 866 867 /// GetNamedIvarList - Return the list of ivars in the interface 868 /// itself (not including super classes and not including unnamed 869 /// bitfields). 870 /// 871 /// For the non-fragile ABI, this also includes synthesized property 872 /// ivars. 873 void GetNamedIvarList(const ObjCInterfaceDecl *OID, 874 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const; 875 876public: 877 CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm) 878 { } 879 880 virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL); 881 882 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD, 883 const ObjCContainerDecl *CD=0); 884 885 virtual void GenerateProtocol(const ObjCProtocolDecl *PD); 886 887 /// GetOrEmitProtocol - Get the protocol object for the given 888 /// declaration, emitting it if necessary. The return value has type 889 /// ProtocolPtrTy. 890 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0; 891 892 /// GetOrEmitProtocolRef - Get a forward reference to the protocol 893 /// object for the given declaration, emitting it if needed. These 894 /// forward references will be filled in with empty bodies if no 895 /// definition is seen. The return value has type ProtocolPtrTy. 896 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0; 897}; 898 899class CGObjCMac : public CGObjCCommonMac { 900private: 901 ObjCTypesHelper ObjCTypes; 902 /// EmitImageInfo - Emit the image info marker used to encode some module 903 /// level information. 904 void EmitImageInfo(); 905 906 /// EmitModuleInfo - Another marker encoding module level 907 /// information. 908 void EmitModuleInfo(); 909 910 /// EmitModuleSymols - Emit module symbols, the list of defined 911 /// classes and categories. The result has type SymtabPtrTy. 912 llvm::Constant *EmitModuleSymbols(); 913 914 /// FinishModule - Write out global data structures at the end of 915 /// processing a translation unit. 916 void FinishModule(); 917 918 /// EmitClassExtension - Generate the class extension structure used 919 /// to store the weak ivar layout and properties. The return value 920 /// has type ClassExtensionPtrTy. 921 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID); 922 923 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy, 924 /// for the given class. 925 llvm::Value *EmitClassRef(CGBuilderTy &Builder, 926 const ObjCInterfaceDecl *ID); 927 928 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF, 929 QualType ResultType, 930 Selector Sel, 931 llvm::Value *Arg0, 932 QualType Arg0Ty, 933 bool IsSuper, 934 const CallArgList &CallArgs); 935 936 /// EmitIvarList - Emit the ivar list for the given 937 /// implementation. If ForClass is true the list of class ivars 938 /// (i.e. metaclass ivars) is emitted, otherwise the list of 939 /// interface ivars will be emitted. The return value has type 940 /// IvarListPtrTy. 941 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID, 942 bool ForClass); 943 944 /// EmitMetaClass - Emit a forward reference to the class structure 945 /// for the metaclass of the given interface. The return value has 946 /// type ClassPtrTy. 947 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID); 948 949 /// EmitMetaClass - Emit a class structure for the metaclass of the 950 /// given implementation. The return value has type ClassPtrTy. 951 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID, 952 llvm::Constant *Protocols, 953 const llvm::Type *InterfaceTy, 954 const ConstantVector &Methods); 955 956 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD); 957 958 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD); 959 960 /// EmitMethodList - Emit the method list for the given 961 /// implementation. The return value has type MethodListPtrTy. 962 llvm::Constant *EmitMethodList(const std::string &Name, 963 const char *Section, 964 const ConstantVector &Methods); 965 966 /// EmitMethodDescList - Emit a method description list for a list of 967 /// method declarations. 968 /// - TypeName: The name for the type containing the methods. 969 /// - IsProtocol: True iff these methods are for a protocol. 970 /// - ClassMethds: True iff these are class methods. 971 /// - Required: When true, only "required" methods are 972 /// listed. Similarly, when false only "optional" methods are 973 /// listed. For classes this should always be true. 974 /// - begin, end: The method list to output. 975 /// 976 /// The return value has type MethodDescriptionListPtrTy. 977 llvm::Constant *EmitMethodDescList(const std::string &Name, 978 const char *Section, 979 const ConstantVector &Methods); 980 981 /// GetOrEmitProtocol - Get the protocol object for the given 982 /// declaration, emitting it if necessary. The return value has type 983 /// ProtocolPtrTy. 984 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD); 985 986 /// GetOrEmitProtocolRef - Get a forward reference to the protocol 987 /// object for the given declaration, emitting it if needed. These 988 /// forward references will be filled in with empty bodies if no 989 /// definition is seen. The return value has type ProtocolPtrTy. 990 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD); 991 992 /// EmitProtocolExtension - Generate the protocol extension 993 /// structure used to store optional instance and class methods, and 994 /// protocol properties. The return value has type 995 /// ProtocolExtensionPtrTy. 996 llvm::Constant * 997 EmitProtocolExtension(const ObjCProtocolDecl *PD, 998 const ConstantVector &OptInstanceMethods, 999 const ConstantVector &OptClassMethods); 1000 1001 /// EmitProtocolList - Generate the list of referenced 1002 /// protocols. The return value has type ProtocolListPtrTy. 1003 llvm::Constant *EmitProtocolList(const std::string &Name, 1004 ObjCProtocolDecl::protocol_iterator begin, 1005 ObjCProtocolDecl::protocol_iterator end); 1006 1007 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy, 1008 /// for the given selector. 1009 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel); 1010 1011 public: 1012 CGObjCMac(CodeGen::CodeGenModule &cgm); 1013 1014 virtual llvm::Function *ModuleInitFunction(); 1015 1016 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF, 1017 QualType ResultType, 1018 Selector Sel, 1019 llvm::Value *Receiver, 1020 bool IsClassMessage, 1021 const CallArgList &CallArgs); 1022 1023 virtual CodeGen::RValue 1024 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, 1025 QualType ResultType, 1026 Selector Sel, 1027 const ObjCInterfaceDecl *Class, 1028 bool isCategoryImpl, 1029 llvm::Value *Receiver, 1030 bool IsClassMessage, 1031 const CallArgList &CallArgs); 1032 1033 virtual llvm::Value *GetClass(CGBuilderTy &Builder, 1034 const ObjCInterfaceDecl *ID); 1035 1036 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel); 1037 1038 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD); 1039 1040 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl); 1041 1042 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder, 1043 const ObjCProtocolDecl *PD); 1044 1045 virtual llvm::Constant *GetPropertyGetFunction(); 1046 virtual llvm::Constant *GetPropertySetFunction(); 1047 virtual llvm::Constant *EnumerationMutationFunction(); 1048 1049 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, 1050 const Stmt &S); 1051 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, 1052 const ObjCAtThrowStmt &S); 1053 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, 1054 llvm::Value *AddrWeakObj); 1055 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, 1056 llvm::Value *src, llvm::Value *dst); 1057 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, 1058 llvm::Value *src, llvm::Value *dest); 1059 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, 1060 llvm::Value *src, llvm::Value *dest); 1061 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, 1062 llvm::Value *src, llvm::Value *dest); 1063 1064 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, 1065 QualType ObjectTy, 1066 llvm::Value *BaseValue, 1067 const ObjCIvarDecl *Ivar, 1068 unsigned CVRQualifiers); 1069 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF, 1070 const ObjCInterfaceDecl *Interface, 1071 const ObjCIvarDecl *Ivar); 1072}; 1073 1074class CGObjCNonFragileABIMac : public CGObjCCommonMac { 1075private: 1076 ObjCNonFragileABITypesHelper ObjCTypes; 1077 llvm::GlobalVariable* ObjCEmptyCacheVar; 1078 llvm::GlobalVariable* ObjCEmptyVtableVar; 1079 1080 /// SuperClassReferences - uniqued super class references. 1081 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences; 1082 1083 /// MetaClassReferences - uniqued meta class references. 1084 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences; 1085 1086 /// EHTypeReferences - uniqued class ehtype references. 1087 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences; 1088 1089 /// FinishNonFragileABIModule - Write out global data structures at the end of 1090 /// processing a translation unit. 1091 void FinishNonFragileABIModule(); 1092 1093 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags, 1094 unsigned InstanceStart, 1095 unsigned InstanceSize, 1096 const ObjCImplementationDecl *ID); 1097 llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName, 1098 llvm::Constant *IsAGV, 1099 llvm::Constant *SuperClassGV, 1100 llvm::Constant *ClassRoGV, 1101 bool HiddenVisibility); 1102 1103 llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD); 1104 1105 llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD); 1106 1107 /// EmitMethodList - Emit the method list for the given 1108 /// implementation. The return value has type MethodListnfABITy. 1109 llvm::Constant *EmitMethodList(const std::string &Name, 1110 const char *Section, 1111 const ConstantVector &Methods); 1112 /// EmitIvarList - Emit the ivar list for the given 1113 /// implementation. If ForClass is true the list of class ivars 1114 /// (i.e. metaclass ivars) is emitted, otherwise the list of 1115 /// interface ivars will be emitted. The return value has type 1116 /// IvarListnfABIPtrTy. 1117 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID); 1118 1119 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID, 1120 const ObjCIvarDecl *Ivar, 1121 unsigned long int offset); 1122 1123 /// GetOrEmitProtocol - Get the protocol object for the given 1124 /// declaration, emitting it if necessary. The return value has type 1125 /// ProtocolPtrTy. 1126 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD); 1127 1128 /// GetOrEmitProtocolRef - Get a forward reference to the protocol 1129 /// object for the given declaration, emitting it if needed. These 1130 /// forward references will be filled in with empty bodies if no 1131 /// definition is seen. The return value has type ProtocolPtrTy. 1132 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD); 1133 1134 /// EmitProtocolList - Generate the list of referenced 1135 /// protocols. The return value has type ProtocolListPtrTy. 1136 llvm::Constant *EmitProtocolList(const std::string &Name, 1137 ObjCProtocolDecl::protocol_iterator begin, 1138 ObjCProtocolDecl::protocol_iterator end); 1139 1140 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF, 1141 QualType ResultType, 1142 Selector Sel, 1143 llvm::Value *Receiver, 1144 QualType Arg0Ty, 1145 bool IsSuper, 1146 const CallArgList &CallArgs); 1147 1148 /// GetClassGlobal - Return the global variable for the Objective-C 1149 /// class of the given name. 1150 llvm::GlobalVariable *GetClassGlobal(const std::string &Name); 1151 1152 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy, 1153 /// for the given class reference. 1154 llvm::Value *EmitClassRef(CGBuilderTy &Builder, 1155 const ObjCInterfaceDecl *ID); 1156 1157 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy, 1158 /// for the given super class reference. 1159 llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder, 1160 const ObjCInterfaceDecl *ID); 1161 1162 /// EmitMetaClassRef - Return a Value * of the address of _class_t 1163 /// meta-data 1164 llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder, 1165 const ObjCInterfaceDecl *ID); 1166 1167 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for 1168 /// the given ivar. 1169 /// 1170 llvm::GlobalVariable * ObjCIvarOffsetVariable( 1171 const ObjCInterfaceDecl *ID, 1172 const ObjCIvarDecl *Ivar); 1173 1174 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy, 1175 /// for the given selector. 1176 llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel); 1177 1178 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C 1179 /// interface. The return value has type EHTypePtrTy. 1180 llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID, 1181 bool ForDefinition); 1182 1183 const char *getMetaclassSymbolPrefix() const { 1184 return "OBJC_METACLASS_$_"; 1185 } 1186 1187 const char *getClassSymbolPrefix() const { 1188 return "OBJC_CLASS_$_"; 1189 } 1190 1191 void GetClassSizeInfo(const ObjCInterfaceDecl *OID, 1192 uint32_t &InstanceStart, 1193 uint32_t &InstanceSize); 1194 1195public: 1196 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm); 1197 // FIXME. All stubs for now! 1198 virtual llvm::Function *ModuleInitFunction(); 1199 1200 virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF, 1201 QualType ResultType, 1202 Selector Sel, 1203 llvm::Value *Receiver, 1204 bool IsClassMessage, 1205 const CallArgList &CallArgs); 1206 1207 virtual CodeGen::RValue 1208 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, 1209 QualType ResultType, 1210 Selector Sel, 1211 const ObjCInterfaceDecl *Class, 1212 bool isCategoryImpl, 1213 llvm::Value *Receiver, 1214 bool IsClassMessage, 1215 const CallArgList &CallArgs); 1216 1217 virtual llvm::Value *GetClass(CGBuilderTy &Builder, 1218 const ObjCInterfaceDecl *ID); 1219 1220 virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel) 1221 { return EmitSelector(Builder, Sel); } 1222 1223 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD); 1224 1225 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl); 1226 virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder, 1227 const ObjCProtocolDecl *PD); 1228 1229 virtual llvm::Constant *GetPropertyGetFunction() { 1230 return ObjCTypes.getGetPropertyFn(); 1231 } 1232 virtual llvm::Constant *GetPropertySetFunction() { 1233 return ObjCTypes.getSetPropertyFn(); 1234 } 1235 virtual llvm::Constant *EnumerationMutationFunction() { 1236 return ObjCTypes.getEnumerationMutationFn(); 1237 } 1238 1239 virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, 1240 const Stmt &S); 1241 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, 1242 const ObjCAtThrowStmt &S); 1243 virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, 1244 llvm::Value *AddrWeakObj); 1245 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, 1246 llvm::Value *src, llvm::Value *dst); 1247 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, 1248 llvm::Value *src, llvm::Value *dest); 1249 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, 1250 llvm::Value *src, llvm::Value *dest); 1251 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, 1252 llvm::Value *src, llvm::Value *dest); 1253 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, 1254 QualType ObjectTy, 1255 llvm::Value *BaseValue, 1256 const ObjCIvarDecl *Ivar, 1257 unsigned CVRQualifiers); 1258 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF, 1259 const ObjCInterfaceDecl *Interface, 1260 const ObjCIvarDecl *Ivar); 1261}; 1262 1263} // end anonymous namespace 1264 1265/* *** Helper Functions *** */ 1266 1267/// getConstantGEP() - Help routine to construct simple GEPs. 1268static llvm::Constant *getConstantGEP(llvm::Constant *C, 1269 unsigned idx0, 1270 unsigned idx1) { 1271 llvm::Value *Idxs[] = { 1272 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0), 1273 llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1) 1274 }; 1275 return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2); 1276} 1277 1278/// hasObjCExceptionAttribute - Return true if this class or any super 1279/// class has the __objc_exception__ attribute. 1280static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) { 1281 if (OID->hasAttr<ObjCExceptionAttr>()) 1282 return true; 1283 if (const ObjCInterfaceDecl *Super = OID->getSuperClass()) 1284 return hasObjCExceptionAttribute(Super); 1285 return false; 1286} 1287 1288/* *** CGObjCMac Public Interface *** */ 1289 1290CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm), 1291 ObjCTypes(cgm) 1292{ 1293 ObjCABI = 1; 1294 EmitImageInfo(); 1295} 1296 1297/// GetClass - Return a reference to the class for the given interface 1298/// decl. 1299llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder, 1300 const ObjCInterfaceDecl *ID) { 1301 return EmitClassRef(Builder, ID); 1302} 1303 1304/// GetSelector - Return the pointer to the unique'd string for this selector. 1305llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) { 1306 return EmitSelector(Builder, Sel); 1307} 1308 1309/// Generate a constant CFString object. 1310/* 1311 struct __builtin_CFString { 1312 const int *isa; // point to __CFConstantStringClassReference 1313 int flags; 1314 const char *str; 1315 long length; 1316 }; 1317*/ 1318 1319llvm::Constant *CGObjCCommonMac::GenerateConstantString( 1320 const ObjCStringLiteral *SL) { 1321 return CGM.GetAddrOfConstantCFString(SL->getString()); 1322} 1323 1324/// Generates a message send where the super is the receiver. This is 1325/// a message send to self with special delivery semantics indicating 1326/// which class's method should be called. 1327CodeGen::RValue 1328CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, 1329 QualType ResultType, 1330 Selector Sel, 1331 const ObjCInterfaceDecl *Class, 1332 bool isCategoryImpl, 1333 llvm::Value *Receiver, 1334 bool IsClassMessage, 1335 const CodeGen::CallArgList &CallArgs) { 1336 // Create and init a super structure; this is a (receiver, class) 1337 // pair we will pass to objc_msgSendSuper. 1338 llvm::Value *ObjCSuper = 1339 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super"); 1340 llvm::Value *ReceiverAsObject = 1341 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy); 1342 CGF.Builder.CreateStore(ReceiverAsObject, 1343 CGF.Builder.CreateStructGEP(ObjCSuper, 0)); 1344 1345 // If this is a class message the metaclass is passed as the target. 1346 llvm::Value *Target; 1347 if (IsClassMessage) { 1348 if (isCategoryImpl) { 1349 // Message sent to 'super' in a class method defined in a category 1350 // implementation requires an odd treatment. 1351 // If we are in a class method, we must retrieve the 1352 // _metaclass_ for the current class, pointed at by 1353 // the class's "isa" pointer. The following assumes that 1354 // isa" is the first ivar in a class (which it must be). 1355 Target = EmitClassRef(CGF.Builder, Class->getSuperClass()); 1356 Target = CGF.Builder.CreateStructGEP(Target, 0); 1357 Target = CGF.Builder.CreateLoad(Target); 1358 } 1359 else { 1360 llvm::Value *MetaClassPtr = EmitMetaClassRef(Class); 1361 llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1); 1362 llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr); 1363 Target = Super; 1364 } 1365 } else { 1366 Target = EmitClassRef(CGF.Builder, Class->getSuperClass()); 1367 } 1368 // FIXME: We shouldn't need to do this cast, rectify the ASTContext 1369 // and ObjCTypes types. 1370 const llvm::Type *ClassTy = 1371 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType()); 1372 Target = CGF.Builder.CreateBitCast(Target, ClassTy); 1373 CGF.Builder.CreateStore(Target, 1374 CGF.Builder.CreateStructGEP(ObjCSuper, 1)); 1375 1376 return EmitMessageSend(CGF, ResultType, Sel, 1377 ObjCSuper, ObjCTypes.SuperPtrCTy, 1378 true, CallArgs); 1379} 1380 1381/// Generate code for a message send expression. 1382CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF, 1383 QualType ResultType, 1384 Selector Sel, 1385 llvm::Value *Receiver, 1386 bool IsClassMessage, 1387 const CallArgList &CallArgs) { 1388 llvm::Value *Arg0 = 1389 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp"); 1390 return EmitMessageSend(CGF, ResultType, Sel, 1391 Arg0, CGF.getContext().getObjCIdType(), 1392 false, CallArgs); 1393} 1394 1395CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF, 1396 QualType ResultType, 1397 Selector Sel, 1398 llvm::Value *Arg0, 1399 QualType Arg0Ty, 1400 bool IsSuper, 1401 const CallArgList &CallArgs) { 1402 CallArgList ActualArgs; 1403 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty)); 1404 ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder, 1405 Sel)), 1406 CGF.getContext().getObjCSelType())); 1407 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end()); 1408 1409 CodeGenTypes &Types = CGM.getTypes(); 1410 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs); 1411 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false); 1412 1413 llvm::Constant *Fn; 1414 if (CGM.ReturnTypeUsesSret(FnInfo)) { 1415 Fn = ObjCTypes.getSendStretFn(IsSuper); 1416 } else if (ResultType->isFloatingType()) { 1417 // FIXME: Sadly, this is wrong. This actually depends on the 1418 // architecture. This happens to be right for x86-32 though. 1419 Fn = ObjCTypes.getSendFpretFn(IsSuper); 1420 } else { 1421 Fn = ObjCTypes.getSendFn(IsSuper); 1422 } 1423 Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy)); 1424 return CGF.EmitCall(FnInfo, Fn, ActualArgs); 1425} 1426 1427llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder, 1428 const ObjCProtocolDecl *PD) { 1429 // FIXME: I don't understand why gcc generates this, or where it is 1430 // resolved. Investigate. Its also wasteful to look this up over and 1431 // over. 1432 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol")); 1433 1434 return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD), 1435 ObjCTypes.ExternalProtocolPtrTy); 1436} 1437 1438void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) { 1439 // FIXME: We shouldn't need this, the protocol decl should contain 1440 // enough information to tell us whether this was a declaration or a 1441 // definition. 1442 DefinedProtocols.insert(PD->getIdentifier()); 1443 1444 // If we have generated a forward reference to this protocol, emit 1445 // it now. Otherwise do nothing, the protocol objects are lazily 1446 // emitted. 1447 if (Protocols.count(PD->getIdentifier())) 1448 GetOrEmitProtocol(PD); 1449} 1450 1451llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) { 1452 if (DefinedProtocols.count(PD->getIdentifier())) 1453 return GetOrEmitProtocol(PD); 1454 return GetOrEmitProtocolRef(PD); 1455} 1456 1457/* 1458 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions 1459 struct _objc_protocol { 1460 struct _objc_protocol_extension *isa; 1461 char *protocol_name; 1462 struct _objc_protocol_list *protocol_list; 1463 struct _objc__method_prototype_list *instance_methods; 1464 struct _objc__method_prototype_list *class_methods 1465 }; 1466 1467 See EmitProtocolExtension(). 1468*/ 1469llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) { 1470 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()]; 1471 1472 // Early exit if a defining object has already been generated. 1473 if (Entry && Entry->hasInitializer()) 1474 return Entry; 1475 1476 // FIXME: I don't understand why gcc generates this, or where it is 1477 // resolved. Investigate. Its also wasteful to look this up over and 1478 // over. 1479 LazySymbols.insert(&CGM.getContext().Idents.get("Protocol")); 1480 1481 const char *ProtocolName = PD->getNameAsCString(); 1482 1483 // Construct method lists. 1484 std::vector<llvm::Constant*> InstanceMethods, ClassMethods; 1485 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods; 1486 for (ObjCProtocolDecl::instmeth_iterator 1487 i = PD->instmeth_begin(CGM.getContext()), 1488 e = PD->instmeth_end(CGM.getContext()); i != e; ++i) { 1489 ObjCMethodDecl *MD = *i; 1490 llvm::Constant *C = GetMethodDescriptionConstant(MD); 1491 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { 1492 OptInstanceMethods.push_back(C); 1493 } else { 1494 InstanceMethods.push_back(C); 1495 } 1496 } 1497 1498 for (ObjCProtocolDecl::classmeth_iterator 1499 i = PD->classmeth_begin(CGM.getContext()), 1500 e = PD->classmeth_end(CGM.getContext()); i != e; ++i) { 1501 ObjCMethodDecl *MD = *i; 1502 llvm::Constant *C = GetMethodDescriptionConstant(MD); 1503 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { 1504 OptClassMethods.push_back(C); 1505 } else { 1506 ClassMethods.push_back(C); 1507 } 1508 } 1509 1510 std::vector<llvm::Constant*> Values(5); 1511 Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods); 1512 Values[1] = GetClassName(PD->getIdentifier()); 1513 Values[2] = 1514 EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(), 1515 PD->protocol_begin(), 1516 PD->protocol_end()); 1517 Values[3] = 1518 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_" 1519 + PD->getNameAsString(), 1520 "__OBJC,__cat_inst_meth,regular,no_dead_strip", 1521 InstanceMethods); 1522 Values[4] = 1523 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_" 1524 + PD->getNameAsString(), 1525 "__OBJC,__cat_cls_meth,regular,no_dead_strip", 1526 ClassMethods); 1527 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy, 1528 Values); 1529 1530 if (Entry) { 1531 // Already created, fix the linkage and update the initializer. 1532 Entry->setLinkage(llvm::GlobalValue::InternalLinkage); 1533 Entry->setInitializer(Init); 1534 } else { 1535 Entry = 1536 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false, 1537 llvm::GlobalValue::InternalLinkage, 1538 Init, 1539 std::string("\01L_OBJC_PROTOCOL_")+ProtocolName, 1540 &CGM.getModule()); 1541 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip"); 1542 Entry->setAlignment(4); 1543 UsedGlobals.push_back(Entry); 1544 // FIXME: Is this necessary? Why only for protocol? 1545 Entry->setAlignment(4); 1546 } 1547 1548 return Entry; 1549} 1550 1551llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) { 1552 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()]; 1553 1554 if (!Entry) { 1555 // We use the initializer as a marker of whether this is a forward 1556 // reference or not. At module finalization we add the empty 1557 // contents for protocols which were referenced but never defined. 1558 Entry = 1559 new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false, 1560 llvm::GlobalValue::ExternalLinkage, 1561 0, 1562 "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(), 1563 &CGM.getModule()); 1564 Entry->setSection("__OBJC,__protocol,regular,no_dead_strip"); 1565 Entry->setAlignment(4); 1566 UsedGlobals.push_back(Entry); 1567 // FIXME: Is this necessary? Why only for protocol? 1568 Entry->setAlignment(4); 1569 } 1570 1571 return Entry; 1572} 1573 1574/* 1575 struct _objc_protocol_extension { 1576 uint32_t size; 1577 struct objc_method_description_list *optional_instance_methods; 1578 struct objc_method_description_list *optional_class_methods; 1579 struct objc_property_list *instance_properties; 1580 }; 1581*/ 1582llvm::Constant * 1583CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD, 1584 const ConstantVector &OptInstanceMethods, 1585 const ConstantVector &OptClassMethods) { 1586 uint64_t Size = 1587 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy); 1588 std::vector<llvm::Constant*> Values(4); 1589 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 1590 Values[1] = 1591 EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_" 1592 + PD->getNameAsString(), 1593 "__OBJC,__cat_inst_meth,regular,no_dead_strip", 1594 OptInstanceMethods); 1595 Values[2] = 1596 EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_" 1597 + PD->getNameAsString(), 1598 "__OBJC,__cat_cls_meth,regular,no_dead_strip", 1599 OptClassMethods); 1600 Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" + 1601 PD->getNameAsString(), 1602 0, PD, ObjCTypes); 1603 1604 // Return null if no extension bits are used. 1605 if (Values[1]->isNullValue() && Values[2]->isNullValue() && 1606 Values[3]->isNullValue()) 1607 return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy); 1608 1609 llvm::Constant *Init = 1610 llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values); 1611 1612 // No special section, but goes in llvm.used 1613 return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(), 1614 Init, 1615 0, 0, true); 1616} 1617 1618/* 1619 struct objc_protocol_list { 1620 struct objc_protocol_list *next; 1621 long count; 1622 Protocol *list[]; 1623 }; 1624*/ 1625llvm::Constant * 1626CGObjCMac::EmitProtocolList(const std::string &Name, 1627 ObjCProtocolDecl::protocol_iterator begin, 1628 ObjCProtocolDecl::protocol_iterator end) { 1629 std::vector<llvm::Constant*> ProtocolRefs; 1630 1631 for (; begin != end; ++begin) 1632 ProtocolRefs.push_back(GetProtocolRef(*begin)); 1633 1634 // Just return null for empty protocol lists 1635 if (ProtocolRefs.empty()) 1636 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); 1637 1638 // This list is null terminated. 1639 ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy)); 1640 1641 std::vector<llvm::Constant*> Values(3); 1642 // This field is only used by the runtime. 1643 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); 1644 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1); 1645 Values[2] = 1646 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy, 1647 ProtocolRefs.size()), 1648 ProtocolRefs); 1649 1650 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 1651 llvm::GlobalVariable *GV = 1652 CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip", 1653 4, false); 1654 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy); 1655} 1656 1657/* 1658 struct _objc_property { 1659 const char * const name; 1660 const char * const attributes; 1661 }; 1662 1663 struct _objc_property_list { 1664 uint32_t entsize; // sizeof (struct _objc_property) 1665 uint32_t prop_count; 1666 struct _objc_property[prop_count]; 1667 }; 1668*/ 1669llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name, 1670 const Decl *Container, 1671 const ObjCContainerDecl *OCD, 1672 const ObjCCommonTypesHelper &ObjCTypes) { 1673 std::vector<llvm::Constant*> Properties, Prop(2); 1674 for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()), 1675 E = OCD->prop_end(CGM.getContext()); I != E; ++I) { 1676 const ObjCPropertyDecl *PD = *I; 1677 Prop[0] = GetPropertyName(PD->getIdentifier()); 1678 Prop[1] = GetPropertyTypeString(PD, Container); 1679 Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy, 1680 Prop)); 1681 } 1682 1683 // Return null for empty list. 1684 if (Properties.empty()) 1685 return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); 1686 1687 unsigned PropertySize = 1688 CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy); 1689 std::vector<llvm::Constant*> Values(3); 1690 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize); 1691 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size()); 1692 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy, 1693 Properties.size()); 1694 Values[2] = llvm::ConstantArray::get(AT, Properties); 1695 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 1696 1697 llvm::GlobalVariable *GV = 1698 CreateMetadataVar(Name, Init, 1699 (ObjCABI == 2) ? "__DATA, __objc_const" : 1700 "__OBJC,__property,regular,no_dead_strip", 1701 (ObjCABI == 2) ? 8 : 4, 1702 true); 1703 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy); 1704} 1705 1706/* 1707 struct objc_method_description_list { 1708 int count; 1709 struct objc_method_description list[]; 1710 }; 1711*/ 1712llvm::Constant * 1713CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) { 1714 std::vector<llvm::Constant*> Desc(2); 1715 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()), 1716 ObjCTypes.SelectorPtrTy); 1717 Desc[1] = GetMethodVarType(MD); 1718 return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy, 1719 Desc); 1720} 1721 1722llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name, 1723 const char *Section, 1724 const ConstantVector &Methods) { 1725 // Return null for empty list. 1726 if (Methods.empty()) 1727 return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy); 1728 1729 std::vector<llvm::Constant*> Values(2); 1730 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size()); 1731 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy, 1732 Methods.size()); 1733 Values[1] = llvm::ConstantArray::get(AT, Methods); 1734 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 1735 1736 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true); 1737 return llvm::ConstantExpr::getBitCast(GV, 1738 ObjCTypes.MethodDescriptionListPtrTy); 1739} 1740 1741/* 1742 struct _objc_category { 1743 char *category_name; 1744 char *class_name; 1745 struct _objc_method_list *instance_methods; 1746 struct _objc_method_list *class_methods; 1747 struct _objc_protocol_list *protocols; 1748 uint32_t size; // <rdar://4585769> 1749 struct _objc_property_list *instance_properties; 1750 }; 1751 */ 1752void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) { 1753 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy); 1754 1755 // FIXME: This is poor design, the OCD should have a pointer to the 1756 // category decl. Additionally, note that Category can be null for 1757 // the @implementation w/o an @interface case. Sema should just 1758 // create one for us as it does for @implementation so everyone else 1759 // can live life under a clear blue sky. 1760 const ObjCInterfaceDecl *Interface = OCD->getClassInterface(); 1761 const ObjCCategoryDecl *Category = 1762 Interface->FindCategoryDeclaration(OCD->getIdentifier()); 1763 std::string ExtName(Interface->getNameAsString() + "_" + 1764 OCD->getNameAsString()); 1765 1766 std::vector<llvm::Constant*> InstanceMethods, ClassMethods; 1767 for (ObjCCategoryImplDecl::instmeth_iterator 1768 i = OCD->instmeth_begin(CGM.getContext()), 1769 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) { 1770 // Instance methods should always be defined. 1771 InstanceMethods.push_back(GetMethodConstant(*i)); 1772 } 1773 for (ObjCCategoryImplDecl::classmeth_iterator 1774 i = OCD->classmeth_begin(CGM.getContext()), 1775 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) { 1776 // Class methods should always be defined. 1777 ClassMethods.push_back(GetMethodConstant(*i)); 1778 } 1779 1780 std::vector<llvm::Constant*> Values(7); 1781 Values[0] = GetClassName(OCD->getIdentifier()); 1782 Values[1] = GetClassName(Interface->getIdentifier()); 1783 Values[2] = 1784 EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") + 1785 ExtName, 1786 "__OBJC,__cat_inst_meth,regular,no_dead_strip", 1787 InstanceMethods); 1788 Values[3] = 1789 EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName, 1790 "__OBJC,__cat_cls_meth,regular,no_dead_strip", 1791 ClassMethods); 1792 if (Category) { 1793 Values[4] = 1794 EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName, 1795 Category->protocol_begin(), 1796 Category->protocol_end()); 1797 } else { 1798 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); 1799 } 1800 Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 1801 1802 // If there is no category @interface then there can be no properties. 1803 if (Category) { 1804 Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName, 1805 OCD, Category, ObjCTypes); 1806 } else { 1807 Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); 1808 } 1809 1810 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy, 1811 Values); 1812 1813 llvm::GlobalVariable *GV = 1814 CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init, 1815 "__OBJC,__category,regular,no_dead_strip", 1816 4, true); 1817 DefinedCategories.push_back(GV); 1818} 1819 1820// FIXME: Get from somewhere? 1821enum ClassFlags { 1822 eClassFlags_Factory = 0x00001, 1823 eClassFlags_Meta = 0x00002, 1824 // <rdr://5142207> 1825 eClassFlags_HasCXXStructors = 0x02000, 1826 eClassFlags_Hidden = 0x20000, 1827 eClassFlags_ABI2_Hidden = 0x00010, 1828 eClassFlags_ABI2_HasCXXStructors = 0x00004 // <rdr://4923634> 1829}; 1830 1831/* 1832 struct _objc_class { 1833 Class isa; 1834 Class super_class; 1835 const char *name; 1836 long version; 1837 long info; 1838 long instance_size; 1839 struct _objc_ivar_list *ivars; 1840 struct _objc_method_list *methods; 1841 struct _objc_cache *cache; 1842 struct _objc_protocol_list *protocols; 1843 // Objective-C 1.0 extensions (<rdr://4585769>) 1844 const char *ivar_layout; 1845 struct _objc_class_ext *ext; 1846 }; 1847 1848 See EmitClassExtension(); 1849 */ 1850void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) { 1851 DefinedSymbols.insert(ID->getIdentifier()); 1852 1853 std::string ClassName = ID->getNameAsString(); 1854 // FIXME: Gross 1855 ObjCInterfaceDecl *Interface = 1856 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface()); 1857 llvm::Constant *Protocols = 1858 EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(), 1859 Interface->protocol_begin(), 1860 Interface->protocol_end()); 1861 const llvm::Type *InterfaceTy = GetConcreteClassStruct(CGM, Interface); 1862 unsigned Flags = eClassFlags_Factory; 1863 unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy); 1864 1865 // FIXME: Set CXX-structors flag. 1866 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden) 1867 Flags |= eClassFlags_Hidden; 1868 1869 std::vector<llvm::Constant*> InstanceMethods, ClassMethods; 1870 for (ObjCImplementationDecl::instmeth_iterator 1871 i = ID->instmeth_begin(CGM.getContext()), 1872 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) { 1873 // Instance methods should always be defined. 1874 InstanceMethods.push_back(GetMethodConstant(*i)); 1875 } 1876 for (ObjCImplementationDecl::classmeth_iterator 1877 i = ID->classmeth_begin(CGM.getContext()), 1878 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) { 1879 // Class methods should always be defined. 1880 ClassMethods.push_back(GetMethodConstant(*i)); 1881 } 1882 1883 for (ObjCImplementationDecl::propimpl_iterator 1884 i = ID->propimpl_begin(CGM.getContext()), 1885 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) { 1886 ObjCPropertyImplDecl *PID = *i; 1887 1888 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 1889 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 1890 1891 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl()) 1892 if (llvm::Constant *C = GetMethodConstant(MD)) 1893 InstanceMethods.push_back(C); 1894 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl()) 1895 if (llvm::Constant *C = GetMethodConstant(MD)) 1896 InstanceMethods.push_back(C); 1897 } 1898 } 1899 1900 std::vector<llvm::Constant*> Values(12); 1901 Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods); 1902 if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) { 1903 // Record a reference to the super class. 1904 LazySymbols.insert(Super->getIdentifier()); 1905 1906 Values[ 1] = 1907 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()), 1908 ObjCTypes.ClassPtrTy); 1909 } else { 1910 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy); 1911 } 1912 Values[ 2] = GetClassName(ID->getIdentifier()); 1913 // Version is always 0. 1914 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0); 1915 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags); 1916 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size); 1917 Values[ 6] = EmitIvarList(ID, false); 1918 Values[ 7] = 1919 EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(), 1920 "__OBJC,__inst_meth,regular,no_dead_strip", 1921 InstanceMethods); 1922 // cache is always NULL. 1923 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy); 1924 Values[ 9] = Protocols; 1925 // FIXME: Set ivar_layout 1926 Values[10] = BuildIvarLayout(ID, true); 1927 // Values[10] = GetIvarLayoutName(0, ObjCTypes); 1928 Values[11] = EmitClassExtension(ID); 1929 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy, 1930 Values); 1931 1932 llvm::GlobalVariable *GV = 1933 CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init, 1934 "__OBJC,__class,regular,no_dead_strip", 1935 4, true); 1936 DefinedClasses.push_back(GV); 1937} 1938 1939llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID, 1940 llvm::Constant *Protocols, 1941 const llvm::Type *InterfaceTy, 1942 const ConstantVector &Methods) { 1943 unsigned Flags = eClassFlags_Meta; 1944 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy); 1945 1946 if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden) 1947 Flags |= eClassFlags_Hidden; 1948 1949 std::vector<llvm::Constant*> Values(12); 1950 // The isa for the metaclass is the root of the hierarchy. 1951 const ObjCInterfaceDecl *Root = ID->getClassInterface(); 1952 while (const ObjCInterfaceDecl *Super = Root->getSuperClass()) 1953 Root = Super; 1954 Values[ 0] = 1955 llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()), 1956 ObjCTypes.ClassPtrTy); 1957 // The super class for the metaclass is emitted as the name of the 1958 // super class. The runtime fixes this up to point to the 1959 // *metaclass* for the super class. 1960 if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) { 1961 Values[ 1] = 1962 llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()), 1963 ObjCTypes.ClassPtrTy); 1964 } else { 1965 Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy); 1966 } 1967 Values[ 2] = GetClassName(ID->getIdentifier()); 1968 // Version is always 0. 1969 Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0); 1970 Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags); 1971 Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size); 1972 Values[ 6] = EmitIvarList(ID, true); 1973 Values[ 7] = 1974 EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(), 1975 "__OBJC,__cls_meth,regular,no_dead_strip", 1976 Methods); 1977 // cache is always NULL. 1978 Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy); 1979 Values[ 9] = Protocols; 1980 // ivar_layout for metaclass is always NULL. 1981 Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 1982 // The class extension is always unused for metaclasses. 1983 Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy); 1984 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy, 1985 Values); 1986 1987 std::string Name("\01L_OBJC_METACLASS_"); 1988 Name += ID->getNameAsCString(); 1989 1990 // Check for a forward reference. 1991 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name); 1992 if (GV) { 1993 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy && 1994 "Forward metaclass reference has incorrect type."); 1995 GV->setLinkage(llvm::GlobalValue::InternalLinkage); 1996 GV->setInitializer(Init); 1997 } else { 1998 GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false, 1999 llvm::GlobalValue::InternalLinkage, 2000 Init, Name, 2001 &CGM.getModule()); 2002 } 2003 GV->setSection("__OBJC,__meta_class,regular,no_dead_strip"); 2004 GV->setAlignment(4); 2005 UsedGlobals.push_back(GV); 2006 2007 return GV; 2008} 2009 2010llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) { 2011 std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString(); 2012 2013 // FIXME: Should we look these up somewhere other than the 2014 // module. Its a bit silly since we only generate these while 2015 // processing an implementation, so exactly one pointer would work 2016 // if know when we entered/exitted an implementation block. 2017 2018 // Check for an existing forward reference. 2019 // Previously, metaclass with internal linkage may have been defined. 2020 // pass 'true' as 2nd argument so it is returned. 2021 if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) { 2022 assert(GV->getType()->getElementType() == ObjCTypes.ClassTy && 2023 "Forward metaclass reference has incorrect type."); 2024 return GV; 2025 } else { 2026 // Generate as an external reference to keep a consistent 2027 // module. This will be patched up when we emit the metaclass. 2028 return new llvm::GlobalVariable(ObjCTypes.ClassTy, false, 2029 llvm::GlobalValue::ExternalLinkage, 2030 0, 2031 Name, 2032 &CGM.getModule()); 2033 } 2034} 2035 2036/* 2037 struct objc_class_ext { 2038 uint32_t size; 2039 const char *weak_ivar_layout; 2040 struct _objc_property_list *properties; 2041 }; 2042*/ 2043llvm::Constant * 2044CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) { 2045 uint64_t Size = 2046 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy); 2047 2048 std::vector<llvm::Constant*> Values(3); 2049 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 2050 // FIXME: Output weak_ivar_layout string. 2051 Values[1] = BuildIvarLayout(ID, false); 2052 // Values[1] = GetIvarLayoutName(0, ObjCTypes); 2053 Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(), 2054 ID, ID->getClassInterface(), ObjCTypes); 2055 2056 // Return null if no extension bits are used. 2057 if (Values[1]->isNullValue() && Values[2]->isNullValue()) 2058 return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy); 2059 2060 llvm::Constant *Init = 2061 llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values); 2062 return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(), 2063 Init, "__OBJC,__class_ext,regular,no_dead_strip", 2064 4, true); 2065} 2066 2067/// getInterfaceDeclForIvar - Get the interface declaration node where 2068/// this ivar is declared in. 2069/// FIXME. Ideally, this info should be in the ivar node. But currently 2070/// it is not and prevailing wisdom is that ASTs should not have more 2071/// info than is absolutely needed, even though this info reflects the 2072/// source language. 2073/// 2074static const ObjCInterfaceDecl *getInterfaceDeclForIvar( 2075 const ObjCInterfaceDecl *OI, 2076 const ObjCIvarDecl *IVD, 2077 ASTContext &Context) { 2078 if (!OI) 2079 return 0; 2080 assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface"); 2081 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(), 2082 E = OI->ivar_end(); I != E; ++I) 2083 if ((*I)->getIdentifier() == IVD->getIdentifier()) 2084 return OI; 2085 // look into properties. 2086 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context), 2087 E = OI->prop_end(Context); I != E; ++I) { 2088 ObjCPropertyDecl *PDecl = (*I); 2089 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) 2090 if (IV->getIdentifier() == IVD->getIdentifier()) 2091 return OI; 2092 } 2093 return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context); 2094} 2095 2096/* 2097 struct objc_ivar { 2098 char *ivar_name; 2099 char *ivar_type; 2100 int ivar_offset; 2101 }; 2102 2103 struct objc_ivar_list { 2104 int ivar_count; 2105 struct objc_ivar list[count]; 2106 }; 2107 */ 2108llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID, 2109 bool ForClass) { 2110 std::vector<llvm::Constant*> Ivars, Ivar(3); 2111 2112 // When emitting the root class GCC emits ivar entries for the 2113 // actual class structure. It is not clear if we need to follow this 2114 // behavior; for now lets try and get away with not doing it. If so, 2115 // the cleanest solution would be to make up an ObjCInterfaceDecl 2116 // for the class. 2117 if (ForClass) 2118 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy); 2119 2120 ObjCInterfaceDecl *OID = 2121 const_cast<ObjCInterfaceDecl*>(ID->getClassInterface()); 2122 2123 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars; 2124 GetNamedIvarList(OID, OIvars); 2125 2126 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) { 2127 ObjCIvarDecl *IVD = OIvars[i]; 2128 Ivar[0] = GetMethodVarName(IVD->getIdentifier()); 2129 Ivar[1] = GetMethodVarType(IVD); 2130 Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, 2131 ComputeIvarBaseOffset(CGM, OID, IVD)); 2132 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar)); 2133 } 2134 2135 // Return null for empty list. 2136 if (Ivars.empty()) 2137 return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy); 2138 2139 std::vector<llvm::Constant*> Values(2); 2140 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size()); 2141 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy, 2142 Ivars.size()); 2143 Values[1] = llvm::ConstantArray::get(AT, Ivars); 2144 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 2145 2146 llvm::GlobalVariable *GV; 2147 if (ForClass) 2148 GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(), 2149 Init, "__OBJC,__class_vars,regular,no_dead_strip", 2150 4, true); 2151 else 2152 GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_" 2153 + ID->getNameAsString(), 2154 Init, "__OBJC,__instance_vars,regular,no_dead_strip", 2155 4, true); 2156 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy); 2157} 2158 2159/* 2160 struct objc_method { 2161 SEL method_name; 2162 char *method_types; 2163 void *method; 2164 }; 2165 2166 struct objc_method_list { 2167 struct objc_method_list *obsolete; 2168 int count; 2169 struct objc_method methods_list[count]; 2170 }; 2171*/ 2172 2173/// GetMethodConstant - Return a struct objc_method constant for the 2174/// given method if it has been defined. The result is null if the 2175/// method has not been defined. The return value has type MethodPtrTy. 2176llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) { 2177 // FIXME: Use DenseMap::lookup 2178 llvm::Function *Fn = MethodDefinitions[MD]; 2179 if (!Fn) 2180 return 0; 2181 2182 std::vector<llvm::Constant*> Method(3); 2183 Method[0] = 2184 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()), 2185 ObjCTypes.SelectorPtrTy); 2186 Method[1] = GetMethodVarType(MD); 2187 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy); 2188 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method); 2189} 2190 2191llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name, 2192 const char *Section, 2193 const ConstantVector &Methods) { 2194 // Return null for empty list. 2195 if (Methods.empty()) 2196 return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy); 2197 2198 std::vector<llvm::Constant*> Values(3); 2199 Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 2200 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size()); 2201 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy, 2202 Methods.size()); 2203 Values[2] = llvm::ConstantArray::get(AT, Methods); 2204 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 2205 2206 llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true); 2207 return llvm::ConstantExpr::getBitCast(GV, 2208 ObjCTypes.MethodListPtrTy); 2209} 2210 2211llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD, 2212 const ObjCContainerDecl *CD) { 2213 std::string Name; 2214 GetNameForMethod(OMD, CD, Name); 2215 2216 CodeGenTypes &Types = CGM.getTypes(); 2217 const llvm::FunctionType *MethodTy = 2218 Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic()); 2219 llvm::Function *Method = 2220 llvm::Function::Create(MethodTy, 2221 llvm::GlobalValue::InternalLinkage, 2222 Name, 2223 &CGM.getModule()); 2224 MethodDefinitions.insert(std::make_pair(OMD, Method)); 2225 2226 return Method; 2227} 2228 2229/// GetFieldBaseOffset - return the field's byte offset. 2230uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI, 2231 const llvm::StructLayout *Layout, 2232 const FieldDecl *Field) { 2233 // Is this a C struct? 2234 if (!OI) 2235 return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field)); 2236 return ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field)); 2237} 2238 2239llvm::GlobalVariable * 2240CGObjCCommonMac::CreateMetadataVar(const std::string &Name, 2241 llvm::Constant *Init, 2242 const char *Section, 2243 unsigned Align, 2244 bool AddToUsed) { 2245 const llvm::Type *Ty = Init->getType(); 2246 llvm::GlobalVariable *GV = 2247 new llvm::GlobalVariable(Ty, false, 2248 llvm::GlobalValue::InternalLinkage, 2249 Init, 2250 Name, 2251 &CGM.getModule()); 2252 if (Section) 2253 GV->setSection(Section); 2254 if (Align) 2255 GV->setAlignment(Align); 2256 if (AddToUsed) 2257 UsedGlobals.push_back(GV); 2258 return GV; 2259} 2260 2261llvm::Function *CGObjCMac::ModuleInitFunction() { 2262 // Abuse this interface function as a place to finalize. 2263 FinishModule(); 2264 2265 return NULL; 2266} 2267 2268llvm::Constant *CGObjCMac::GetPropertyGetFunction() { 2269 return ObjCTypes.getGetPropertyFn(); 2270} 2271 2272llvm::Constant *CGObjCMac::GetPropertySetFunction() { 2273 return ObjCTypes.getSetPropertyFn(); 2274} 2275 2276llvm::Constant *CGObjCMac::EnumerationMutationFunction() { 2277 return ObjCTypes.getEnumerationMutationFn(); 2278} 2279 2280/* 2281 2282Objective-C setjmp-longjmp (sjlj) Exception Handling 2283-- 2284 2285The basic framework for a @try-catch-finally is as follows: 2286{ 2287 objc_exception_data d; 2288 id _rethrow = null; 2289 bool _call_try_exit = true; 2290 2291 objc_exception_try_enter(&d); 2292 if (!setjmp(d.jmp_buf)) { 2293 ... try body ... 2294 } else { 2295 // exception path 2296 id _caught = objc_exception_extract(&d); 2297 2298 // enter new try scope for handlers 2299 if (!setjmp(d.jmp_buf)) { 2300 ... match exception and execute catch blocks ... 2301 2302 // fell off end, rethrow. 2303 _rethrow = _caught; 2304 ... jump-through-finally to finally_rethrow ... 2305 } else { 2306 // exception in catch block 2307 _rethrow = objc_exception_extract(&d); 2308 _call_try_exit = false; 2309 ... jump-through-finally to finally_rethrow ... 2310 } 2311 } 2312 ... jump-through-finally to finally_end ... 2313 2314finally: 2315 if (_call_try_exit) 2316 objc_exception_try_exit(&d); 2317 2318 ... finally block .... 2319 ... dispatch to finally destination ... 2320 2321finally_rethrow: 2322 objc_exception_throw(_rethrow); 2323 2324finally_end: 2325} 2326 2327This framework differs slightly from the one gcc uses, in that gcc 2328uses _rethrow to determine if objc_exception_try_exit should be called 2329and if the object should be rethrown. This breaks in the face of 2330throwing nil and introduces unnecessary branches. 2331 2332We specialize this framework for a few particular circumstances: 2333 2334 - If there are no catch blocks, then we avoid emitting the second 2335 exception handling context. 2336 2337 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id 2338 e)) we avoid emitting the code to rethrow an uncaught exception. 2339 2340 - FIXME: If there is no @finally block we can do a few more 2341 simplifications. 2342 2343Rethrows and Jumps-Through-Finally 2344-- 2345 2346Support for implicit rethrows and jumping through the finally block is 2347handled by storing the current exception-handling context in 2348ObjCEHStack. 2349 2350In order to implement proper @finally semantics, we support one basic 2351mechanism for jumping through the finally block to an arbitrary 2352destination. Constructs which generate exits from a @try or @catch 2353block use this mechanism to implement the proper semantics by chaining 2354jumps, as necessary. 2355 2356This mechanism works like the one used for indirect goto: we 2357arbitrarily assign an ID to each destination and store the ID for the 2358destination in a variable prior to entering the finally block. At the 2359end of the finally block we simply create a switch to the proper 2360destination. 2361 2362Code gen for @synchronized(expr) stmt; 2363Effectively generating code for: 2364objc_sync_enter(expr); 2365@try stmt @finally { objc_sync_exit(expr); } 2366*/ 2367 2368void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, 2369 const Stmt &S) { 2370 bool isTry = isa<ObjCAtTryStmt>(S); 2371 // Create various blocks we refer to for handling @finally. 2372 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally"); 2373 llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit"); 2374 llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit"); 2375 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw"); 2376 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end"); 2377 2378 // For @synchronized, call objc_sync_enter(sync.expr). The 2379 // evaluation of the expression must occur before we enter the 2380 // @synchronized. We can safely avoid a temp here because jumps into 2381 // @synchronized are illegal & this will dominate uses. 2382 llvm::Value *SyncArg = 0; 2383 if (!isTry) { 2384 SyncArg = 2385 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr()); 2386 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy); 2387 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg); 2388 } 2389 2390 // Push an EH context entry, used for handling rethrows and jumps 2391 // through finally. 2392 CGF.PushCleanupBlock(FinallyBlock); 2393 2394 CGF.ObjCEHValueStack.push_back(0); 2395 2396 // Allocate memory for the exception data and rethrow pointer. 2397 llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy, 2398 "exceptiondata.ptr"); 2399 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy, 2400 "_rethrow"); 2401 llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty, 2402 "_call_try_exit"); 2403 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr); 2404 2405 // Enter a new try block and call setjmp. 2406 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData); 2407 llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0, 2408 "jmpbufarray"); 2409 JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp"); 2410 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(), 2411 JmpBufPtr, "result"); 2412 2413 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try"); 2414 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler"); 2415 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"), 2416 TryHandler, TryBlock); 2417 2418 // Emit the @try block. 2419 CGF.EmitBlock(TryBlock); 2420 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody() 2421 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody()); 2422 CGF.EmitBranchThroughCleanup(FinallyEnd); 2423 2424 // Emit the "exception in @try" block. 2425 CGF.EmitBlock(TryHandler); 2426 2427 // Retrieve the exception object. We may emit multiple blocks but 2428 // nothing can cross this so the value is already in SSA form. 2429 llvm::Value *Caught = 2430 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(), 2431 ExceptionData, "caught"); 2432 CGF.ObjCEHValueStack.back() = Caught; 2433 if (!isTry) 2434 { 2435 CGF.Builder.CreateStore(Caught, RethrowPtr); 2436 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr); 2437 CGF.EmitBranchThroughCleanup(FinallyRethrow); 2438 } 2439 else if (const ObjCAtCatchStmt* CatchStmt = 2440 cast<ObjCAtTryStmt>(S).getCatchStmts()) 2441 { 2442 // Enter a new exception try block (in case a @catch block throws 2443 // an exception). 2444 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData); 2445 2446 llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(), 2447 JmpBufPtr, "result"); 2448 llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"); 2449 2450 llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch"); 2451 llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler"); 2452 CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock); 2453 2454 CGF.EmitBlock(CatchBlock); 2455 2456 // Handle catch list. As a special case we check if everything is 2457 // matched and avoid generating code for falling off the end if 2458 // so. 2459 bool AllMatched = false; 2460 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) { 2461 llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch"); 2462 2463 const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl(); 2464 const PointerType *PT = 0; 2465 2466 // catch(...) always matches. 2467 if (!CatchParam) { 2468 AllMatched = true; 2469 } else { 2470 PT = CatchParam->getType()->getAsPointerType(); 2471 2472 // catch(id e) always matches. 2473 // FIXME: For the time being we also match id<X>; this should 2474 // be rejected by Sema instead. 2475 if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) || 2476 CatchParam->getType()->isObjCQualifiedIdType()) 2477 AllMatched = true; 2478 } 2479 2480 if (AllMatched) { 2481 if (CatchParam) { 2482 CGF.EmitLocalBlockVarDecl(*CatchParam); 2483 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?"); 2484 CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam)); 2485 } 2486 2487 CGF.EmitStmt(CatchStmt->getCatchBody()); 2488 CGF.EmitBranchThroughCleanup(FinallyEnd); 2489 break; 2490 } 2491 2492 assert(PT && "Unexpected non-pointer type in @catch"); 2493 QualType T = PT->getPointeeType(); 2494 const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType(); 2495 assert(ObjCType && "Catch parameter must have Objective-C type!"); 2496 2497 // Check if the @catch block matches the exception object. 2498 llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl()); 2499 2500 llvm::Value *Match = 2501 CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(), 2502 Class, Caught, "match"); 2503 2504 llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched"); 2505 2506 CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"), 2507 MatchedBlock, NextCatchBlock); 2508 2509 // Emit the @catch block. 2510 CGF.EmitBlock(MatchedBlock); 2511 CGF.EmitLocalBlockVarDecl(*CatchParam); 2512 assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?"); 2513 2514 llvm::Value *Tmp = 2515 CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()), 2516 "tmp"); 2517 CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam)); 2518 2519 CGF.EmitStmt(CatchStmt->getCatchBody()); 2520 CGF.EmitBranchThroughCleanup(FinallyEnd); 2521 2522 CGF.EmitBlock(NextCatchBlock); 2523 } 2524 2525 if (!AllMatched) { 2526 // None of the handlers caught the exception, so store it to be 2527 // rethrown at the end of the @finally block. 2528 CGF.Builder.CreateStore(Caught, RethrowPtr); 2529 CGF.EmitBranchThroughCleanup(FinallyRethrow); 2530 } 2531 2532 // Emit the exception handler for the @catch blocks. 2533 CGF.EmitBlock(CatchHandler); 2534 CGF.Builder.CreateStore( 2535 CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(), 2536 ExceptionData), 2537 RethrowPtr); 2538 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr); 2539 CGF.EmitBranchThroughCleanup(FinallyRethrow); 2540 } else { 2541 CGF.Builder.CreateStore(Caught, RethrowPtr); 2542 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr); 2543 CGF.EmitBranchThroughCleanup(FinallyRethrow); 2544 } 2545 2546 // Pop the exception-handling stack entry. It is important to do 2547 // this now, because the code in the @finally block is not in this 2548 // context. 2549 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock(); 2550 2551 CGF.ObjCEHValueStack.pop_back(); 2552 2553 // Emit the @finally block. 2554 CGF.EmitBlock(FinallyBlock); 2555 llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp"); 2556 2557 CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit); 2558 2559 CGF.EmitBlock(FinallyExit); 2560 CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData); 2561 2562 CGF.EmitBlock(FinallyNoExit); 2563 if (isTry) { 2564 if (const ObjCAtFinallyStmt* FinallyStmt = 2565 cast<ObjCAtTryStmt>(S).getFinallyStmt()) 2566 CGF.EmitStmt(FinallyStmt->getFinallyBody()); 2567 } else { 2568 // Emit objc_sync_exit(expr); as finally's sole statement for 2569 // @synchronized. 2570 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg); 2571 } 2572 2573 // Emit the switch block 2574 if (Info.SwitchBlock) 2575 CGF.EmitBlock(Info.SwitchBlock); 2576 if (Info.EndBlock) 2577 CGF.EmitBlock(Info.EndBlock); 2578 2579 CGF.EmitBlock(FinallyRethrow); 2580 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), 2581 CGF.Builder.CreateLoad(RethrowPtr)); 2582 CGF.Builder.CreateUnreachable(); 2583 2584 CGF.EmitBlock(FinallyEnd); 2585} 2586 2587void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF, 2588 const ObjCAtThrowStmt &S) { 2589 llvm::Value *ExceptionAsObject; 2590 2591 if (const Expr *ThrowExpr = S.getThrowExpr()) { 2592 llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr); 2593 ExceptionAsObject = 2594 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp"); 2595 } else { 2596 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) && 2597 "Unexpected rethrow outside @catch block."); 2598 ExceptionAsObject = CGF.ObjCEHValueStack.back(); 2599 } 2600 2601 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject); 2602 CGF.Builder.CreateUnreachable(); 2603 2604 // Clear the insertion point to indicate we are in unreachable code. 2605 CGF.Builder.ClearInsertionPoint(); 2606} 2607 2608/// EmitObjCWeakRead - Code gen for loading value of a __weak 2609/// object: objc_read_weak (id *src) 2610/// 2611llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, 2612 llvm::Value *AddrWeakObj) 2613{ 2614 const llvm::Type* DestTy = 2615 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType(); 2616 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy); 2617 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(), 2618 AddrWeakObj, "weakread"); 2619 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy); 2620 return read_weak; 2621} 2622 2623/// EmitObjCWeakAssign - Code gen for assigning to a __weak object. 2624/// objc_assign_weak (id src, id *dst) 2625/// 2626void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, 2627 llvm::Value *src, llvm::Value *dst) 2628{ 2629 const llvm::Type * SrcTy = src->getType(); 2630 if (!isa<llvm::PointerType>(SrcTy)) { 2631 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy); 2632 assert(Size <= 8 && "does not support size > 8"); 2633 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) 2634 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy); 2635 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); 2636 } 2637 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 2638 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 2639 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(), 2640 src, dst, "weakassign"); 2641 return; 2642} 2643 2644/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object. 2645/// objc_assign_global (id src, id *dst) 2646/// 2647void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, 2648 llvm::Value *src, llvm::Value *dst) 2649{ 2650 const llvm::Type * SrcTy = src->getType(); 2651 if (!isa<llvm::PointerType>(SrcTy)) { 2652 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy); 2653 assert(Size <= 8 && "does not support size > 8"); 2654 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) 2655 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy); 2656 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); 2657 } 2658 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 2659 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 2660 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(), 2661 src, dst, "globalassign"); 2662 return; 2663} 2664 2665/// EmitObjCIvarAssign - Code gen for assigning to a __strong object. 2666/// objc_assign_ivar (id src, id *dst) 2667/// 2668void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, 2669 llvm::Value *src, llvm::Value *dst) 2670{ 2671 const llvm::Type * SrcTy = src->getType(); 2672 if (!isa<llvm::PointerType>(SrcTy)) { 2673 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy); 2674 assert(Size <= 8 && "does not support size > 8"); 2675 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) 2676 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy); 2677 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); 2678 } 2679 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 2680 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 2681 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(), 2682 src, dst, "assignivar"); 2683 return; 2684} 2685 2686/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object. 2687/// objc_assign_strongCast (id src, id *dst) 2688/// 2689void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, 2690 llvm::Value *src, llvm::Value *dst) 2691{ 2692 const llvm::Type * SrcTy = src->getType(); 2693 if (!isa<llvm::PointerType>(SrcTy)) { 2694 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy); 2695 assert(Size <= 8 && "does not support size > 8"); 2696 src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) 2697 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy); 2698 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); 2699 } 2700 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 2701 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 2702 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(), 2703 src, dst, "weakassign"); 2704 return; 2705} 2706 2707/// EmitObjCValueForIvar - Code Gen for ivar reference. 2708/// 2709LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, 2710 QualType ObjectTy, 2711 llvm::Value *BaseValue, 2712 const ObjCIvarDecl *Ivar, 2713 unsigned CVRQualifiers) { 2714 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl(); 2715 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers, 2716 EmitIvarOffset(CGF, ID, Ivar)); 2717} 2718 2719llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF, 2720 const ObjCInterfaceDecl *Interface, 2721 const ObjCIvarDecl *Ivar) { 2722 uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar); 2723 return llvm::ConstantInt::get( 2724 CGM.getTypes().ConvertType(CGM.getContext().LongTy), 2725 Offset); 2726} 2727 2728/* *** Private Interface *** */ 2729 2730/// EmitImageInfo - Emit the image info marker used to encode some module 2731/// level information. 2732/// 2733/// See: <rdr://4810609&4810587&4810587> 2734/// struct IMAGE_INFO { 2735/// unsigned version; 2736/// unsigned flags; 2737/// }; 2738enum ImageInfoFlags { 2739 eImageInfo_FixAndContinue = (1 << 0), // FIXME: Not sure what 2740 // this implies. 2741 eImageInfo_GarbageCollected = (1 << 1), 2742 eImageInfo_GCOnly = (1 << 2), 2743 eImageInfo_OptimizedByDyld = (1 << 3), // FIXME: When is this set. 2744 2745 // A flag indicating that the module has no instances of an 2746 // @synthesize of a superclass variable. <rdar://problem/6803242> 2747 eImageInfo_CorrectedSynthesize = (1 << 4) 2748}; 2749 2750void CGObjCMac::EmitImageInfo() { 2751 unsigned version = 0; // Version is unused? 2752 unsigned flags = 0; 2753 2754 // FIXME: Fix and continue? 2755 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) 2756 flags |= eImageInfo_GarbageCollected; 2757 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly) 2758 flags |= eImageInfo_GCOnly; 2759 2760 // We never allow @synthesize of a superclass property. 2761 flags |= eImageInfo_CorrectedSynthesize; 2762 2763 // Emitted as int[2]; 2764 llvm::Constant *values[2] = { 2765 llvm::ConstantInt::get(llvm::Type::Int32Ty, version), 2766 llvm::ConstantInt::get(llvm::Type::Int32Ty, flags) 2767 }; 2768 llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2); 2769 2770 const char *Section; 2771 if (ObjCABI == 1) 2772 Section = "__OBJC, __image_info,regular"; 2773 else 2774 Section = "__DATA, __objc_imageinfo, regular, no_dead_strip"; 2775 llvm::GlobalVariable *GV = 2776 CreateMetadataVar("\01L_OBJC_IMAGE_INFO", 2777 llvm::ConstantArray::get(AT, values, 2), 2778 Section, 2779 0, 2780 true); 2781 GV->setConstant(true); 2782} 2783 2784 2785// struct objc_module { 2786// unsigned long version; 2787// unsigned long size; 2788// const char *name; 2789// Symtab symtab; 2790// }; 2791 2792// FIXME: Get from somewhere 2793static const int ModuleVersion = 7; 2794 2795void CGObjCMac::EmitModuleInfo() { 2796 uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy); 2797 2798 std::vector<llvm::Constant*> Values(4); 2799 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion); 2800 Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size); 2801 // This used to be the filename, now it is unused. <rdr://4327263> 2802 Values[2] = GetClassName(&CGM.getContext().Idents.get("")); 2803 Values[3] = EmitModuleSymbols(); 2804 CreateMetadataVar("\01L_OBJC_MODULES", 2805 llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values), 2806 "__OBJC,__module_info,regular,no_dead_strip", 2807 4, true); 2808} 2809 2810llvm::Constant *CGObjCMac::EmitModuleSymbols() { 2811 unsigned NumClasses = DefinedClasses.size(); 2812 unsigned NumCategories = DefinedCategories.size(); 2813 2814 // Return null if no symbols were defined. 2815 if (!NumClasses && !NumCategories) 2816 return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy); 2817 2818 std::vector<llvm::Constant*> Values(5); 2819 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0); 2820 Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy); 2821 Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses); 2822 Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories); 2823 2824 // The runtime expects exactly the list of defined classes followed 2825 // by the list of defined categories, in a single array. 2826 std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories); 2827 for (unsigned i=0; i<NumClasses; i++) 2828 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i], 2829 ObjCTypes.Int8PtrTy); 2830 for (unsigned i=0; i<NumCategories; i++) 2831 Symbols[NumClasses + i] = 2832 llvm::ConstantExpr::getBitCast(DefinedCategories[i], 2833 ObjCTypes.Int8PtrTy); 2834 2835 Values[4] = 2836 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy, 2837 NumClasses + NumCategories), 2838 Symbols); 2839 2840 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 2841 2842 llvm::GlobalVariable *GV = 2843 CreateMetadataVar("\01L_OBJC_SYMBOLS", Init, 2844 "__OBJC,__symbols,regular,no_dead_strip", 2845 4, true); 2846 return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy); 2847} 2848 2849llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder, 2850 const ObjCInterfaceDecl *ID) { 2851 LazySymbols.insert(ID->getIdentifier()); 2852 2853 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()]; 2854 2855 if (!Entry) { 2856 llvm::Constant *Casted = 2857 llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()), 2858 ObjCTypes.ClassPtrTy); 2859 Entry = 2860 CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted, 2861 "__OBJC,__cls_refs,literal_pointers,no_dead_strip", 2862 4, true); 2863 } 2864 2865 return Builder.CreateLoad(Entry, false, "tmp"); 2866} 2867 2868llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) { 2869 llvm::GlobalVariable *&Entry = SelectorReferences[Sel]; 2870 2871 if (!Entry) { 2872 llvm::Constant *Casted = 2873 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel), 2874 ObjCTypes.SelectorPtrTy); 2875 Entry = 2876 CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted, 2877 "__OBJC,__message_refs,literal_pointers,no_dead_strip", 2878 4, true); 2879 } 2880 2881 return Builder.CreateLoad(Entry, false, "tmp"); 2882} 2883 2884llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) { 2885 llvm::GlobalVariable *&Entry = ClassNames[Ident]; 2886 2887 if (!Entry) 2888 Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_", 2889 llvm::ConstantArray::get(Ident->getName()), 2890 "__TEXT,__cstring,cstring_literals", 2891 1, true); 2892 2893 return getConstantGEP(Entry, 0, 0); 2894} 2895 2896/// GetIvarLayoutName - Returns a unique constant for the given 2897/// ivar layout bitmap. 2898llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident, 2899 const ObjCCommonTypesHelper &ObjCTypes) { 2900 return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 2901} 2902 2903void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI, 2904 const llvm::StructLayout *Layout, 2905 const RecordDecl *RD, 2906 const llvm::SmallVectorImpl<FieldDecl*> &RecFields, 2907 unsigned int BytePos, bool ForStrongLayout, 2908 int &Index, int &SkIndex, bool &HasUnion) { 2909 bool IsUnion = (RD && RD->isUnion()); 2910 uint64_t MaxUnionIvarSize = 0; 2911 uint64_t MaxSkippedUnionIvarSize = 0; 2912 FieldDecl *MaxField = 0; 2913 FieldDecl *MaxSkippedField = 0; 2914 FieldDecl *LastFieldBitfield = 0; 2915 2916 unsigned base = 0; 2917 if (RecFields.empty()) 2918 return; 2919 if (IsUnion) 2920 base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]); 2921 unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0); 2922 unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth(); 2923 2924 llvm::SmallVector<FieldDecl*, 16> TmpRecFields; 2925 2926 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 2927 FieldDecl *Field = RecFields[i]; 2928 // Skip over unnamed or bitfields 2929 if (!Field->getIdentifier() || Field->isBitField()) { 2930 LastFieldBitfield = Field; 2931 continue; 2932 } 2933 LastFieldBitfield = 0; 2934 QualType FQT = Field->getType(); 2935 if (FQT->isRecordType() || FQT->isUnionType()) { 2936 if (FQT->isUnionType()) 2937 HasUnion = true; 2938 else 2939 assert(FQT->isRecordType() && 2940 "only union/record is supported for ivar layout bitmap"); 2941 2942 const RecordType *RT = FQT->getAsRecordType(); 2943 const RecordDecl *RD = RT->getDecl(); 2944 // FIXME - Find a more efficient way of passing records down. 2945 TmpRecFields.append(RD->field_begin(CGM.getContext()), 2946 RD->field_end(CGM.getContext())); 2947 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT); 2948 const llvm::StructLayout *RecLayout = 2949 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty)); 2950 2951 BuildAggrIvarLayout(0, RecLayout, RD, TmpRecFields, 2952 BytePos + GetFieldBaseOffset(OI, Layout, Field), 2953 ForStrongLayout, Index, SkIndex, 2954 HasUnion); 2955 TmpRecFields.clear(); 2956 continue; 2957 } 2958 2959 if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) { 2960 const ConstantArrayType *CArray = 2961 dyn_cast_or_null<ConstantArrayType>(Array); 2962 uint64_t ElCount = CArray->getSize().getZExtValue(); 2963 assert(CArray && "only array with know element size is supported"); 2964 FQT = CArray->getElementType(); 2965 while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) { 2966 const ConstantArrayType *CArray = 2967 dyn_cast_or_null<ConstantArrayType>(Array); 2968 ElCount *= CArray->getSize().getZExtValue(); 2969 FQT = CArray->getElementType(); 2970 } 2971 2972 assert(!FQT->isUnionType() && 2973 "layout for array of unions not supported"); 2974 if (FQT->isRecordType()) { 2975 int OldIndex = Index; 2976 int OldSkIndex = SkIndex; 2977 2978 // FIXME - Use a common routine with the above! 2979 const RecordType *RT = FQT->getAsRecordType(); 2980 const RecordDecl *RD = RT->getDecl(); 2981 // FIXME - Find a more efficiant way of passing records down. 2982 TmpRecFields.append(RD->field_begin(CGM.getContext()), 2983 RD->field_end(CGM.getContext())); 2984 const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT); 2985 const llvm::StructLayout *RecLayout = 2986 CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty)); 2987 2988 BuildAggrIvarLayout(0, RecLayout, RD, 2989 TmpRecFields, 2990 BytePos + GetFieldBaseOffset(OI, Layout, Field), 2991 ForStrongLayout, Index, SkIndex, 2992 HasUnion); 2993 TmpRecFields.clear(); 2994 2995 // Replicate layout information for each array element. Note that 2996 // one element is already done. 2997 uint64_t ElIx = 1; 2998 for (int FirstIndex = Index, FirstSkIndex = SkIndex; 2999 ElIx < ElCount; ElIx++) { 3000 uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits; 3001 for (int i = OldIndex+1; i <= FirstIndex; ++i) 3002 { 3003 GC_IVAR gcivar; 3004 gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx; 3005 gcivar.ivar_size = IvarsInfo[i].ivar_size; 3006 IvarsInfo.push_back(gcivar); ++Index; 3007 } 3008 3009 for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) { 3010 GC_IVAR skivar; 3011 skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx; 3012 skivar.ivar_size = SkipIvars[i].ivar_size; 3013 SkipIvars.push_back(skivar); ++SkIndex; 3014 } 3015 } 3016 continue; 3017 } 3018 } 3019 // At this point, we are done with Record/Union and array there of. 3020 // For other arrays we are down to its element type. 3021 QualType::GCAttrTypes GCAttr = QualType::GCNone; 3022 do { 3023 if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) { 3024 GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak; 3025 break; 3026 } 3027 else if (CGM.getContext().isObjCObjectPointerType(FQT)) { 3028 GCAttr = QualType::Strong; 3029 break; 3030 } 3031 else if (const PointerType *PT = FQT->getAsPointerType()) { 3032 FQT = PT->getPointeeType(); 3033 } 3034 else { 3035 break; 3036 } 3037 } while (true); 3038 3039 if ((ForStrongLayout && GCAttr == QualType::Strong) 3040 || (!ForStrongLayout && GCAttr == QualType::Weak)) { 3041 if (IsUnion) 3042 { 3043 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType()) 3044 / WordSizeInBits; 3045 if (UnionIvarSize > MaxUnionIvarSize) 3046 { 3047 MaxUnionIvarSize = UnionIvarSize; 3048 MaxField = Field; 3049 } 3050 } 3051 else 3052 { 3053 GC_IVAR gcivar; 3054 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field); 3055 gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) / 3056 WordSizeInBits; 3057 IvarsInfo.push_back(gcivar); ++Index; 3058 } 3059 } 3060 else if ((ForStrongLayout && 3061 (GCAttr == QualType::GCNone || GCAttr == QualType::Weak)) 3062 || (!ForStrongLayout && GCAttr != QualType::Weak)) { 3063 if (IsUnion) 3064 { 3065 uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType()); 3066 if (UnionIvarSize > MaxSkippedUnionIvarSize) 3067 { 3068 MaxSkippedUnionIvarSize = UnionIvarSize; 3069 MaxSkippedField = Field; 3070 } 3071 } 3072 else 3073 { 3074 GC_IVAR skivar; 3075 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field); 3076 skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) / 3077 ByteSizeInBits; 3078 SkipIvars.push_back(skivar); ++SkIndex; 3079 } 3080 } 3081 } 3082 if (LastFieldBitfield) { 3083 // Last field was a bitfield. Must update skip info. 3084 GC_IVAR skivar; 3085 skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, 3086 LastFieldBitfield); 3087 Expr *BitWidth = LastFieldBitfield->getBitWidth(); 3088 uint64_t BitFieldSize = 3089 BitWidth->getIntegerConstantExprValue(CGM.getContext()).getZExtValue(); 3090 skivar.ivar_size = (BitFieldSize / ByteSizeInBits) 3091 + ((BitFieldSize % ByteSizeInBits) != 0); 3092 SkipIvars.push_back(skivar); ++SkIndex; 3093 } 3094 3095 if (MaxField) { 3096 GC_IVAR gcivar; 3097 gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField); 3098 gcivar.ivar_size = MaxUnionIvarSize; 3099 IvarsInfo.push_back(gcivar); ++Index; 3100 } 3101 3102 if (MaxSkippedField) { 3103 GC_IVAR skivar; 3104 skivar.ivar_bytepos = BytePos + 3105 GetFieldBaseOffset(OI, Layout, MaxSkippedField); 3106 skivar.ivar_size = MaxSkippedUnionIvarSize; 3107 SkipIvars.push_back(skivar); ++SkIndex; 3108 } 3109} 3110 3111static int 3112IvarBytePosCompare(const void *a, const void *b) 3113{ 3114 unsigned int sa = ((CGObjCCommonMac::GC_IVAR *)a)->ivar_bytepos; 3115 unsigned int sb = ((CGObjCCommonMac::GC_IVAR *)b)->ivar_bytepos; 3116 3117 if (sa < sb) 3118 return -1; 3119 if (sa > sb) 3120 return 1; 3121 return 0; 3122} 3123 3124/// BuildIvarLayout - Builds ivar layout bitmap for the class 3125/// implementation for the __strong or __weak case. 3126/// The layout map displays which words in ivar list must be skipped 3127/// and which must be scanned by GC (see below). String is built of bytes. 3128/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count 3129/// of words to skip and right nibble is count of words to scan. So, each 3130/// nibble represents up to 15 workds to skip or scan. Skipping the rest is 3131/// represented by a 0x00 byte which also ends the string. 3132/// 1. when ForStrongLayout is true, following ivars are scanned: 3133/// - id, Class 3134/// - object * 3135/// - __strong anything 3136/// 3137/// 2. When ForStrongLayout is false, following ivars are scanned: 3138/// - __weak anything 3139/// 3140llvm::Constant *CGObjCCommonMac::BuildIvarLayout( 3141 const ObjCImplementationDecl *OMD, 3142 bool ForStrongLayout) { 3143 int Index = -1; 3144 int SkIndex = -1; 3145 bool hasUnion = false; 3146 int SkipScan; 3147 unsigned int WordsToScan, WordsToSkip; 3148 const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 3149 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC) 3150 return llvm::Constant::getNullValue(PtrTy); 3151 3152 llvm::SmallVector<FieldDecl*, 32> RecFields; 3153 const ObjCInterfaceDecl *OI = OMD->getClassInterface(); 3154 CGM.getContext().CollectObjCIvars(OI, RecFields); 3155 if (RecFields.empty()) 3156 return llvm::Constant::getNullValue(PtrTy); 3157 3158 SkipIvars.clear(); 3159 IvarsInfo.clear(); 3160 3161 const llvm::StructLayout *Layout = 3162 CGM.getTargetData().getStructLayout(GetConcreteClassStruct(CGM, OI)); 3163 BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout, 3164 Index, SkIndex, hasUnion); 3165 if (Index == -1) 3166 return llvm::Constant::getNullValue(PtrTy); 3167 3168 // Sort on byte position in case we encounterred a union nested in 3169 // the ivar list. 3170 if (hasUnion && !IvarsInfo.empty()) 3171 qsort(&IvarsInfo[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare); 3172 if (hasUnion && !SkipIvars.empty()) 3173 qsort(&SkipIvars[0], Index+1, sizeof(GC_IVAR), IvarBytePosCompare); 3174 3175 // Build the string of skip/scan nibbles 3176 SkipScan = -1; 3177 SkipScanIvars.clear(); 3178 unsigned int WordSize = 3179 CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy); 3180 if (IvarsInfo[0].ivar_bytepos == 0) { 3181 WordsToSkip = 0; 3182 WordsToScan = IvarsInfo[0].ivar_size; 3183 } 3184 else { 3185 WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize; 3186 WordsToScan = IvarsInfo[0].ivar_size; 3187 } 3188 for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++) 3189 { 3190 unsigned int TailPrevGCObjC = 3191 IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize; 3192 if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC) 3193 { 3194 // consecutive 'scanned' object pointers. 3195 WordsToScan += IvarsInfo[i].ivar_size; 3196 } 3197 else 3198 { 3199 // Skip over 'gc'able object pointer which lay over each other. 3200 if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos) 3201 continue; 3202 // Must skip over 1 or more words. We save current skip/scan values 3203 // and start a new pair. 3204 SKIP_SCAN SkScan; 3205 SkScan.skip = WordsToSkip; 3206 SkScan.scan = WordsToScan; 3207 SkipScanIvars.push_back(SkScan); ++SkipScan; 3208 3209 // Skip the hole. 3210 SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize; 3211 SkScan.scan = 0; 3212 SkipScanIvars.push_back(SkScan); ++SkipScan; 3213 WordsToSkip = 0; 3214 WordsToScan = IvarsInfo[i].ivar_size; 3215 } 3216 } 3217 if (WordsToScan > 0) 3218 { 3219 SKIP_SCAN SkScan; 3220 SkScan.skip = WordsToSkip; 3221 SkScan.scan = WordsToScan; 3222 SkipScanIvars.push_back(SkScan); ++SkipScan; 3223 } 3224 3225 bool BytesSkipped = false; 3226 if (!SkipIvars.empty()) 3227 { 3228 int LastByteSkipped = 3229 SkipIvars[SkIndex].ivar_bytepos + SkipIvars[SkIndex].ivar_size; 3230 int LastByteScanned = 3231 IvarsInfo[Index].ivar_bytepos + IvarsInfo[Index].ivar_size * WordSize; 3232 BytesSkipped = (LastByteSkipped > LastByteScanned); 3233 // Compute number of bytes to skip at the tail end of the last ivar scanned. 3234 if (BytesSkipped) 3235 { 3236 unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize; 3237 SKIP_SCAN SkScan; 3238 SkScan.skip = TotalWords - (LastByteScanned/WordSize); 3239 SkScan.scan = 0; 3240 SkipScanIvars.push_back(SkScan); ++SkipScan; 3241 } 3242 } 3243 // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced 3244 // as 0xMN. 3245 for (int i = 0; i <= SkipScan; i++) 3246 { 3247 if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0 3248 && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) { 3249 // 0xM0 followed by 0x0N detected. 3250 SkipScanIvars[i].scan = SkipScanIvars[i+1].scan; 3251 for (int j = i+1; j < SkipScan; j++) 3252 SkipScanIvars[j] = SkipScanIvars[j+1]; 3253 --SkipScan; 3254 } 3255 } 3256 3257 // Generate the string. 3258 std::string BitMap; 3259 for (int i = 0; i <= SkipScan; i++) 3260 { 3261 unsigned char byte; 3262 unsigned int skip_small = SkipScanIvars[i].skip % 0xf; 3263 unsigned int scan_small = SkipScanIvars[i].scan % 0xf; 3264 unsigned int skip_big = SkipScanIvars[i].skip / 0xf; 3265 unsigned int scan_big = SkipScanIvars[i].scan / 0xf; 3266 3267 if (skip_small > 0 || skip_big > 0) 3268 BytesSkipped = true; 3269 // first skip big. 3270 for (unsigned int ix = 0; ix < skip_big; ix++) 3271 BitMap += (unsigned char)(0xf0); 3272 3273 // next (skip small, scan) 3274 if (skip_small) 3275 { 3276 byte = skip_small << 4; 3277 if (scan_big > 0) 3278 { 3279 byte |= 0xf; 3280 --scan_big; 3281 } 3282 else if (scan_small) 3283 { 3284 byte |= scan_small; 3285 scan_small = 0; 3286 } 3287 BitMap += byte; 3288 } 3289 // next scan big 3290 for (unsigned int ix = 0; ix < scan_big; ix++) 3291 BitMap += (unsigned char)(0x0f); 3292 // last scan small 3293 if (scan_small) 3294 { 3295 byte = scan_small; 3296 BitMap += byte; 3297 } 3298 } 3299 // null terminate string. 3300 unsigned char zero = 0; 3301 BitMap += zero; 3302 3303 if (CGM.getLangOptions().ObjCGCBitmapPrint) { 3304 printf("\n%s ivar layout for class '%s': ", 3305 ForStrongLayout ? "strong" : "weak", 3306 OMD->getClassInterface()->getNameAsCString()); 3307 const unsigned char *s = (unsigned char*)BitMap.c_str(); 3308 for (unsigned i = 0; i < BitMap.size(); i++) 3309 if (!(s[i] & 0xf0)) 3310 printf("0x0%x%s", s[i], s[i] != 0 ? ", " : ""); 3311 else 3312 printf("0x%x%s", s[i], s[i] != 0 ? ", " : ""); 3313 printf("\n"); 3314 } 3315 3316 // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as 3317 // final layout. 3318 if (ForStrongLayout && !BytesSkipped) 3319 return llvm::Constant::getNullValue(PtrTy); 3320 llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_", 3321 llvm::ConstantArray::get(BitMap.c_str()), 3322 "__TEXT,__cstring,cstring_literals", 3323 1, true); 3324 return getConstantGEP(Entry, 0, 0); 3325} 3326 3327llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) { 3328 llvm::GlobalVariable *&Entry = MethodVarNames[Sel]; 3329 3330 // FIXME: Avoid std::string copying. 3331 if (!Entry) 3332 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_", 3333 llvm::ConstantArray::get(Sel.getAsString()), 3334 "__TEXT,__cstring,cstring_literals", 3335 1, true); 3336 3337 return getConstantGEP(Entry, 0, 0); 3338} 3339 3340// FIXME: Merge into a single cstring creation function. 3341llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) { 3342 return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID)); 3343} 3344 3345// FIXME: Merge into a single cstring creation function. 3346llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) { 3347 return GetMethodVarName(&CGM.getContext().Idents.get(Name)); 3348} 3349 3350llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) { 3351 std::string TypeStr; 3352 CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field); 3353 3354 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr]; 3355 3356 if (!Entry) 3357 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_", 3358 llvm::ConstantArray::get(TypeStr), 3359 "__TEXT,__cstring,cstring_literals", 3360 1, true); 3361 3362 return getConstantGEP(Entry, 0, 0); 3363} 3364 3365llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) { 3366 std::string TypeStr; 3367 CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D), 3368 TypeStr); 3369 3370 llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr]; 3371 3372 if (!Entry) 3373 Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_", 3374 llvm::ConstantArray::get(TypeStr), 3375 "__TEXT,__cstring,cstring_literals", 3376 1, true); 3377 3378 return getConstantGEP(Entry, 0, 0); 3379} 3380 3381// FIXME: Merge into a single cstring creation function. 3382llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) { 3383 llvm::GlobalVariable *&Entry = PropertyNames[Ident]; 3384 3385 if (!Entry) 3386 Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_", 3387 llvm::ConstantArray::get(Ident->getName()), 3388 "__TEXT,__cstring,cstring_literals", 3389 1, true); 3390 3391 return getConstantGEP(Entry, 0, 0); 3392} 3393 3394// FIXME: Merge into a single cstring creation function. 3395// FIXME: This Decl should be more precise. 3396llvm::Constant * 3397 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD, 3398 const Decl *Container) { 3399 std::string TypeStr; 3400 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr); 3401 return GetPropertyName(&CGM.getContext().Idents.get(TypeStr)); 3402} 3403 3404void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D, 3405 const ObjCContainerDecl *CD, 3406 std::string &NameOut) { 3407 NameOut = '\01'; 3408 NameOut += (D->isInstanceMethod() ? '-' : '+'); 3409 NameOut += '['; 3410 assert (CD && "Missing container decl in GetNameForMethod"); 3411 NameOut += CD->getNameAsString(); 3412 if (const ObjCCategoryImplDecl *CID = 3413 dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) { 3414 NameOut += '('; 3415 NameOut += CID->getNameAsString(); 3416 NameOut+= ')'; 3417 } 3418 NameOut += ' '; 3419 NameOut += D->getSelector().getAsString(); 3420 NameOut += ']'; 3421} 3422 3423void CGObjCMac::FinishModule() { 3424 EmitModuleInfo(); 3425 3426 // Emit the dummy bodies for any protocols which were referenced but 3427 // never defined. 3428 for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator 3429 i = Protocols.begin(), e = Protocols.end(); i != e; ++i) { 3430 if (i->second->hasInitializer()) 3431 continue; 3432 3433 std::vector<llvm::Constant*> Values(5); 3434 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy); 3435 Values[1] = GetClassName(i->first); 3436 Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); 3437 Values[3] = Values[4] = 3438 llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy); 3439 i->second->setLinkage(llvm::GlobalValue::InternalLinkage); 3440 i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy, 3441 Values)); 3442 } 3443 3444 std::vector<llvm::Constant*> Used; 3445 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(), 3446 e = UsedGlobals.end(); i != e; ++i) { 3447 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy)); 3448 } 3449 3450 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size()); 3451 llvm::GlobalValue *GV = 3452 new llvm::GlobalVariable(AT, false, 3453 llvm::GlobalValue::AppendingLinkage, 3454 llvm::ConstantArray::get(AT, Used), 3455 "llvm.used", 3456 &CGM.getModule()); 3457 3458 GV->setSection("llvm.metadata"); 3459 3460 // Add assembler directives to add lazy undefined symbol references 3461 // for classes which are referenced but not defined. This is 3462 // important for correct linker interaction. 3463 3464 // FIXME: Uh, this isn't particularly portable. 3465 std::stringstream s; 3466 3467 if (!CGM.getModule().getModuleInlineAsm().empty()) 3468 s << "\n"; 3469 3470 for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(), 3471 e = LazySymbols.end(); i != e; ++i) { 3472 s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n"; 3473 } 3474 for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(), 3475 e = DefinedSymbols.end(); i != e; ++i) { 3476 s << "\t.objc_class_name_" << (*i)->getName() << "=0\n" 3477 << "\t.globl .objc_class_name_" << (*i)->getName() << "\n"; 3478 } 3479 3480 CGM.getModule().appendModuleInlineAsm(s.str()); 3481} 3482 3483CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm) 3484 : CGObjCCommonMac(cgm), 3485 ObjCTypes(cgm) 3486{ 3487 ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL; 3488 ObjCABI = 2; 3489} 3490 3491/* *** */ 3492 3493ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm) 3494: CGM(cgm) 3495{ 3496 CodeGen::CodeGenTypes &Types = CGM.getTypes(); 3497 ASTContext &Ctx = CGM.getContext(); 3498 3499 ShortTy = Types.ConvertType(Ctx.ShortTy); 3500 IntTy = Types.ConvertType(Ctx.IntTy); 3501 LongTy = Types.ConvertType(Ctx.LongTy); 3502 LongLongTy = Types.ConvertType(Ctx.LongLongTy); 3503 Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 3504 3505 ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType()); 3506 PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy); 3507 SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType()); 3508 3509 // FIXME: It would be nice to unify this with the opaque type, so 3510 // that the IR comes out a bit cleaner. 3511 const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType()); 3512 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T); 3513 3514 // I'm not sure I like this. The implicit coordination is a bit 3515 // gross. We should solve this in a reasonable fashion because this 3516 // is a pretty common task (match some runtime data structure with 3517 // an LLVM data structure). 3518 3519 // FIXME: This is leaked. 3520 // FIXME: Merge with rewriter code? 3521 3522 // struct _objc_super { 3523 // id self; 3524 // Class cls; 3525 // } 3526 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0, 3527 SourceLocation(), 3528 &Ctx.Idents.get("_objc_super")); 3529 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0, 3530 Ctx.getObjCIdType(), 0, false)); 3531 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0, 3532 Ctx.getObjCClassType(), 0, false)); 3533 RD->completeDefinition(Ctx); 3534 3535 SuperCTy = Ctx.getTagDeclType(RD); 3536 SuperPtrCTy = Ctx.getPointerType(SuperCTy); 3537 3538 SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy)); 3539 SuperPtrTy = llvm::PointerType::getUnqual(SuperTy); 3540 3541 // struct _prop_t { 3542 // char *name; 3543 // char *attributes; 3544 // } 3545 PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL); 3546 CGM.getModule().addTypeName("struct._prop_t", 3547 PropertyTy); 3548 3549 // struct _prop_list_t { 3550 // uint32_t entsize; // sizeof(struct _prop_t) 3551 // uint32_t count_of_properties; 3552 // struct _prop_t prop_list[count_of_properties]; 3553 // } 3554 PropertyListTy = llvm::StructType::get(IntTy, 3555 IntTy, 3556 llvm::ArrayType::get(PropertyTy, 0), 3557 NULL); 3558 CGM.getModule().addTypeName("struct._prop_list_t", 3559 PropertyListTy); 3560 // struct _prop_list_t * 3561 PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy); 3562 3563 // struct _objc_method { 3564 // SEL _cmd; 3565 // char *method_type; 3566 // char *_imp; 3567 // } 3568 MethodTy = llvm::StructType::get(SelectorPtrTy, 3569 Int8PtrTy, 3570 Int8PtrTy, 3571 NULL); 3572 CGM.getModule().addTypeName("struct._objc_method", MethodTy); 3573 3574 // struct _objc_cache * 3575 CacheTy = llvm::OpaqueType::get(); 3576 CGM.getModule().addTypeName("struct._objc_cache", CacheTy); 3577 CachePtrTy = llvm::PointerType::getUnqual(CacheTy); 3578} 3579 3580ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm) 3581 : ObjCCommonTypesHelper(cgm) 3582{ 3583 // struct _objc_method_description { 3584 // SEL name; 3585 // char *types; 3586 // } 3587 MethodDescriptionTy = 3588 llvm::StructType::get(SelectorPtrTy, 3589 Int8PtrTy, 3590 NULL); 3591 CGM.getModule().addTypeName("struct._objc_method_description", 3592 MethodDescriptionTy); 3593 3594 // struct _objc_method_description_list { 3595 // int count; 3596 // struct _objc_method_description[1]; 3597 // } 3598 MethodDescriptionListTy = 3599 llvm::StructType::get(IntTy, 3600 llvm::ArrayType::get(MethodDescriptionTy, 0), 3601 NULL); 3602 CGM.getModule().addTypeName("struct._objc_method_description_list", 3603 MethodDescriptionListTy); 3604 3605 // struct _objc_method_description_list * 3606 MethodDescriptionListPtrTy = 3607 llvm::PointerType::getUnqual(MethodDescriptionListTy); 3608 3609 // Protocol description structures 3610 3611 // struct _objc_protocol_extension { 3612 // uint32_t size; // sizeof(struct _objc_protocol_extension) 3613 // struct _objc_method_description_list *optional_instance_methods; 3614 // struct _objc_method_description_list *optional_class_methods; 3615 // struct _objc_property_list *instance_properties; 3616 // } 3617 ProtocolExtensionTy = 3618 llvm::StructType::get(IntTy, 3619 MethodDescriptionListPtrTy, 3620 MethodDescriptionListPtrTy, 3621 PropertyListPtrTy, 3622 NULL); 3623 CGM.getModule().addTypeName("struct._objc_protocol_extension", 3624 ProtocolExtensionTy); 3625 3626 // struct _objc_protocol_extension * 3627 ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy); 3628 3629 // Handle recursive construction of Protocol and ProtocolList types 3630 3631 llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get(); 3632 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get(); 3633 3634 const llvm::Type *T = 3635 llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder), 3636 LongTy, 3637 llvm::ArrayType::get(ProtocolTyHolder, 0), 3638 NULL); 3639 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T); 3640 3641 // struct _objc_protocol { 3642 // struct _objc_protocol_extension *isa; 3643 // char *protocol_name; 3644 // struct _objc_protocol **_objc_protocol_list; 3645 // struct _objc_method_description_list *instance_methods; 3646 // struct _objc_method_description_list *class_methods; 3647 // } 3648 T = llvm::StructType::get(ProtocolExtensionPtrTy, 3649 Int8PtrTy, 3650 llvm::PointerType::getUnqual(ProtocolListTyHolder), 3651 MethodDescriptionListPtrTy, 3652 MethodDescriptionListPtrTy, 3653 NULL); 3654 cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T); 3655 3656 ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get()); 3657 CGM.getModule().addTypeName("struct._objc_protocol_list", 3658 ProtocolListTy); 3659 // struct _objc_protocol_list * 3660 ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy); 3661 3662 ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get()); 3663 CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy); 3664 ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy); 3665 3666 // Class description structures 3667 3668 // struct _objc_ivar { 3669 // char *ivar_name; 3670 // char *ivar_type; 3671 // int ivar_offset; 3672 // } 3673 IvarTy = llvm::StructType::get(Int8PtrTy, 3674 Int8PtrTy, 3675 IntTy, 3676 NULL); 3677 CGM.getModule().addTypeName("struct._objc_ivar", IvarTy); 3678 3679 // struct _objc_ivar_list * 3680 IvarListTy = llvm::OpaqueType::get(); 3681 CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy); 3682 IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy); 3683 3684 // struct _objc_method_list * 3685 MethodListTy = llvm::OpaqueType::get(); 3686 CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy); 3687 MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy); 3688 3689 // struct _objc_class_extension * 3690 ClassExtensionTy = 3691 llvm::StructType::get(IntTy, 3692 Int8PtrTy, 3693 PropertyListPtrTy, 3694 NULL); 3695 CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy); 3696 ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy); 3697 3698 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get(); 3699 3700 // struct _objc_class { 3701 // Class isa; 3702 // Class super_class; 3703 // char *name; 3704 // long version; 3705 // long info; 3706 // long instance_size; 3707 // struct _objc_ivar_list *ivars; 3708 // struct _objc_method_list *methods; 3709 // struct _objc_cache *cache; 3710 // struct _objc_protocol_list *protocols; 3711 // char *ivar_layout; 3712 // struct _objc_class_ext *ext; 3713 // }; 3714 T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder), 3715 llvm::PointerType::getUnqual(ClassTyHolder), 3716 Int8PtrTy, 3717 LongTy, 3718 LongTy, 3719 LongTy, 3720 IvarListPtrTy, 3721 MethodListPtrTy, 3722 CachePtrTy, 3723 ProtocolListPtrTy, 3724 Int8PtrTy, 3725 ClassExtensionPtrTy, 3726 NULL); 3727 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T); 3728 3729 ClassTy = cast<llvm::StructType>(ClassTyHolder.get()); 3730 CGM.getModule().addTypeName("struct._objc_class", ClassTy); 3731 ClassPtrTy = llvm::PointerType::getUnqual(ClassTy); 3732 3733 // struct _objc_category { 3734 // char *category_name; 3735 // char *class_name; 3736 // struct _objc_method_list *instance_method; 3737 // struct _objc_method_list *class_method; 3738 // uint32_t size; // sizeof(struct _objc_category) 3739 // struct _objc_property_list *instance_properties;// category's @property 3740 // } 3741 CategoryTy = llvm::StructType::get(Int8PtrTy, 3742 Int8PtrTy, 3743 MethodListPtrTy, 3744 MethodListPtrTy, 3745 ProtocolListPtrTy, 3746 IntTy, 3747 PropertyListPtrTy, 3748 NULL); 3749 CGM.getModule().addTypeName("struct._objc_category", CategoryTy); 3750 3751 // Global metadata structures 3752 3753 // struct _objc_symtab { 3754 // long sel_ref_cnt; 3755 // SEL *refs; 3756 // short cls_def_cnt; 3757 // short cat_def_cnt; 3758 // char *defs[cls_def_cnt + cat_def_cnt]; 3759 // } 3760 SymtabTy = llvm::StructType::get(LongTy, 3761 SelectorPtrTy, 3762 ShortTy, 3763 ShortTy, 3764 llvm::ArrayType::get(Int8PtrTy, 0), 3765 NULL); 3766 CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy); 3767 SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy); 3768 3769 // struct _objc_module { 3770 // long version; 3771 // long size; // sizeof(struct _objc_module) 3772 // char *name; 3773 // struct _objc_symtab* symtab; 3774 // } 3775 ModuleTy = 3776 llvm::StructType::get(LongTy, 3777 LongTy, 3778 Int8PtrTy, 3779 SymtabPtrTy, 3780 NULL); 3781 CGM.getModule().addTypeName("struct._objc_module", ModuleTy); 3782 3783 3784 // FIXME: This is the size of the setjmp buffer and should be 3785 // target specific. 18 is what's used on 32-bit X86. 3786 uint64_t SetJmpBufferSize = 18; 3787 3788 // Exceptions 3789 const llvm::Type *StackPtrTy = 3790 llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4); 3791 3792 ExceptionDataTy = 3793 llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty, 3794 SetJmpBufferSize), 3795 StackPtrTy, NULL); 3796 CGM.getModule().addTypeName("struct._objc_exception_data", 3797 ExceptionDataTy); 3798 3799} 3800 3801ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm) 3802: ObjCCommonTypesHelper(cgm) 3803{ 3804 // struct _method_list_t { 3805 // uint32_t entsize; // sizeof(struct _objc_method) 3806 // uint32_t method_count; 3807 // struct _objc_method method_list[method_count]; 3808 // } 3809 MethodListnfABITy = llvm::StructType::get(IntTy, 3810 IntTy, 3811 llvm::ArrayType::get(MethodTy, 0), 3812 NULL); 3813 CGM.getModule().addTypeName("struct.__method_list_t", 3814 MethodListnfABITy); 3815 // struct method_list_t * 3816 MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy); 3817 3818 // struct _protocol_t { 3819 // id isa; // NULL 3820 // const char * const protocol_name; 3821 // const struct _protocol_list_t * protocol_list; // super protocols 3822 // const struct method_list_t * const instance_methods; 3823 // const struct method_list_t * const class_methods; 3824 // const struct method_list_t *optionalInstanceMethods; 3825 // const struct method_list_t *optionalClassMethods; 3826 // const struct _prop_list_t * properties; 3827 // const uint32_t size; // sizeof(struct _protocol_t) 3828 // const uint32_t flags; // = 0 3829 // } 3830 3831 // Holder for struct _protocol_list_t * 3832 llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get(); 3833 3834 ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy, 3835 Int8PtrTy, 3836 llvm::PointerType::getUnqual( 3837 ProtocolListTyHolder), 3838 MethodListnfABIPtrTy, 3839 MethodListnfABIPtrTy, 3840 MethodListnfABIPtrTy, 3841 MethodListnfABIPtrTy, 3842 PropertyListPtrTy, 3843 IntTy, 3844 IntTy, 3845 NULL); 3846 CGM.getModule().addTypeName("struct._protocol_t", 3847 ProtocolnfABITy); 3848 3849 // struct _protocol_t* 3850 ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy); 3851 3852 // struct _protocol_list_t { 3853 // long protocol_count; // Note, this is 32/64 bit 3854 // struct _protocol_t *[protocol_count]; 3855 // } 3856 ProtocolListnfABITy = llvm::StructType::get(LongTy, 3857 llvm::ArrayType::get( 3858 ProtocolnfABIPtrTy, 0), 3859 NULL); 3860 CGM.getModule().addTypeName("struct._objc_protocol_list", 3861 ProtocolListnfABITy); 3862 cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo( 3863 ProtocolListnfABITy); 3864 3865 // struct _objc_protocol_list* 3866 ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy); 3867 3868 // struct _ivar_t { 3869 // unsigned long int *offset; // pointer to ivar offset location 3870 // char *name; 3871 // char *type; 3872 // uint32_t alignment; 3873 // uint32_t size; 3874 // } 3875 IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy), 3876 Int8PtrTy, 3877 Int8PtrTy, 3878 IntTy, 3879 IntTy, 3880 NULL); 3881 CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy); 3882 3883 // struct _ivar_list_t { 3884 // uint32 entsize; // sizeof(struct _ivar_t) 3885 // uint32 count; 3886 // struct _iver_t list[count]; 3887 // } 3888 IvarListnfABITy = llvm::StructType::get(IntTy, 3889 IntTy, 3890 llvm::ArrayType::get( 3891 IvarnfABITy, 0), 3892 NULL); 3893 CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy); 3894 3895 IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy); 3896 3897 // struct _class_ro_t { 3898 // uint32_t const flags; 3899 // uint32_t const instanceStart; 3900 // uint32_t const instanceSize; 3901 // uint32_t const reserved; // only when building for 64bit targets 3902 // const uint8_t * const ivarLayout; 3903 // const char *const name; 3904 // const struct _method_list_t * const baseMethods; 3905 // const struct _objc_protocol_list *const baseProtocols; 3906 // const struct _ivar_list_t *const ivars; 3907 // const uint8_t * const weakIvarLayout; 3908 // const struct _prop_list_t * const properties; 3909 // } 3910 3911 // FIXME. Add 'reserved' field in 64bit abi mode! 3912 ClassRonfABITy = llvm::StructType::get(IntTy, 3913 IntTy, 3914 IntTy, 3915 Int8PtrTy, 3916 Int8PtrTy, 3917 MethodListnfABIPtrTy, 3918 ProtocolListnfABIPtrTy, 3919 IvarListnfABIPtrTy, 3920 Int8PtrTy, 3921 PropertyListPtrTy, 3922 NULL); 3923 CGM.getModule().addTypeName("struct._class_ro_t", 3924 ClassRonfABITy); 3925 3926 // ImpnfABITy - LLVM for id (*)(id, SEL, ...) 3927 std::vector<const llvm::Type*> Params; 3928 Params.push_back(ObjectPtrTy); 3929 Params.push_back(SelectorPtrTy); 3930 ImpnfABITy = llvm::PointerType::getUnqual( 3931 llvm::FunctionType::get(ObjectPtrTy, Params, false)); 3932 3933 // struct _class_t { 3934 // struct _class_t *isa; 3935 // struct _class_t * const superclass; 3936 // void *cache; 3937 // IMP *vtable; 3938 // struct class_ro_t *ro; 3939 // } 3940 3941 llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get(); 3942 ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder), 3943 llvm::PointerType::getUnqual(ClassTyHolder), 3944 CachePtrTy, 3945 llvm::PointerType::getUnqual(ImpnfABITy), 3946 llvm::PointerType::getUnqual( 3947 ClassRonfABITy), 3948 NULL); 3949 CGM.getModule().addTypeName("struct._class_t", ClassnfABITy); 3950 3951 cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo( 3952 ClassnfABITy); 3953 3954 // LLVM for struct _class_t * 3955 ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy); 3956 3957 // struct _category_t { 3958 // const char * const name; 3959 // struct _class_t *const cls; 3960 // const struct _method_list_t * const instance_methods; 3961 // const struct _method_list_t * const class_methods; 3962 // const struct _protocol_list_t * const protocols; 3963 // const struct _prop_list_t * const properties; 3964 // } 3965 CategorynfABITy = llvm::StructType::get(Int8PtrTy, 3966 ClassnfABIPtrTy, 3967 MethodListnfABIPtrTy, 3968 MethodListnfABIPtrTy, 3969 ProtocolListnfABIPtrTy, 3970 PropertyListPtrTy, 3971 NULL); 3972 CGM.getModule().addTypeName("struct._category_t", CategorynfABITy); 3973 3974 // New types for nonfragile abi messaging. 3975 CodeGen::CodeGenTypes &Types = CGM.getTypes(); 3976 ASTContext &Ctx = CGM.getContext(); 3977 3978 // MessageRefTy - LLVM for: 3979 // struct _message_ref_t { 3980 // IMP messenger; 3981 // SEL name; 3982 // }; 3983 3984 // First the clang type for struct _message_ref_t 3985 RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0, 3986 SourceLocation(), 3987 &Ctx.Idents.get("_message_ref_t")); 3988 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0, 3989 Ctx.VoidPtrTy, 0, false)); 3990 RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0, 3991 Ctx.getObjCSelType(), 0, false)); 3992 RD->completeDefinition(Ctx); 3993 3994 MessageRefCTy = Ctx.getTagDeclType(RD); 3995 MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy); 3996 MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy)); 3997 3998 // MessageRefPtrTy - LLVM for struct _message_ref_t* 3999 MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy); 4000 4001 // SuperMessageRefTy - LLVM for: 4002 // struct _super_message_ref_t { 4003 // SUPER_IMP messenger; 4004 // SEL name; 4005 // }; 4006 SuperMessageRefTy = llvm::StructType::get(ImpnfABITy, 4007 SelectorPtrTy, 4008 NULL); 4009 CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy); 4010 4011 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t* 4012 SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy); 4013 4014 4015 // struct objc_typeinfo { 4016 // const void** vtable; // objc_ehtype_vtable + 2 4017 // const char* name; // c++ typeinfo string 4018 // Class cls; 4019 // }; 4020 EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy), 4021 Int8PtrTy, 4022 ClassnfABIPtrTy, 4023 NULL); 4024 CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy); 4025 EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy); 4026} 4027 4028llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() { 4029 FinishNonFragileABIModule(); 4030 4031 return NULL; 4032} 4033 4034void CGObjCNonFragileABIMac::FinishNonFragileABIModule() { 4035 // nonfragile abi has no module definition. 4036 4037 // Build list of all implemented classe addresses in array 4038 // L_OBJC_LABEL_CLASS_$. 4039 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$ 4040 // list of 'nonlazy' implementations (defined as those with a +load{} 4041 // method!!). 4042 unsigned NumClasses = DefinedClasses.size(); 4043 if (NumClasses) { 4044 std::vector<llvm::Constant*> Symbols(NumClasses); 4045 for (unsigned i=0; i<NumClasses; i++) 4046 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i], 4047 ObjCTypes.Int8PtrTy); 4048 llvm::Constant* Init = 4049 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy, 4050 NumClasses), 4051 Symbols); 4052 4053 llvm::GlobalVariable *GV = 4054 new llvm::GlobalVariable(Init->getType(), false, 4055 llvm::GlobalValue::InternalLinkage, 4056 Init, 4057 "\01L_OBJC_LABEL_CLASS_$", 4058 &CGM.getModule()); 4059 GV->setAlignment(8); 4060 GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip"); 4061 UsedGlobals.push_back(GV); 4062 } 4063 4064 // Build list of all implemented category addresses in array 4065 // L_OBJC_LABEL_CATEGORY_$. 4066 // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$ 4067 // list of 'nonlazy' category implementations (defined as those with a +load{} 4068 // method!!). 4069 unsigned NumCategory = DefinedCategories.size(); 4070 if (NumCategory) { 4071 std::vector<llvm::Constant*> Symbols(NumCategory); 4072 for (unsigned i=0; i<NumCategory; i++) 4073 Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i], 4074 ObjCTypes.Int8PtrTy); 4075 llvm::Constant* Init = 4076 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy, 4077 NumCategory), 4078 Symbols); 4079 4080 llvm::GlobalVariable *GV = 4081 new llvm::GlobalVariable(Init->getType(), false, 4082 llvm::GlobalValue::InternalLinkage, 4083 Init, 4084 "\01L_OBJC_LABEL_CATEGORY_$", 4085 &CGM.getModule()); 4086 GV->setAlignment(8); 4087 GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip"); 4088 UsedGlobals.push_back(GV); 4089 } 4090 4091 // static int L_OBJC_IMAGE_INFO[2] = { 0, flags }; 4092 // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0 4093 std::vector<llvm::Constant*> Values(2); 4094 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0); 4095 unsigned int flags = 0; 4096 // FIXME: Fix and continue? 4097 if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC) 4098 flags |= eImageInfo_GarbageCollected; 4099 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly) 4100 flags |= eImageInfo_GCOnly; 4101 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags); 4102 llvm::Constant* Init = llvm::ConstantArray::get( 4103 llvm::ArrayType::get(ObjCTypes.IntTy, 2), 4104 Values); 4105 llvm::GlobalVariable *IMGV = 4106 new llvm::GlobalVariable(Init->getType(), false, 4107 llvm::GlobalValue::InternalLinkage, 4108 Init, 4109 "\01L_OBJC_IMAGE_INFO", 4110 &CGM.getModule()); 4111 IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip"); 4112 UsedGlobals.push_back(IMGV); 4113 4114 std::vector<llvm::Constant*> Used; 4115 4116 for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(), 4117 e = UsedGlobals.end(); i != e; ++i) { 4118 Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy)); 4119 } 4120 4121 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size()); 4122 llvm::GlobalValue *GV = 4123 new llvm::GlobalVariable(AT, false, 4124 llvm::GlobalValue::AppendingLinkage, 4125 llvm::ConstantArray::get(AT, Used), 4126 "llvm.used", 4127 &CGM.getModule()); 4128 4129 GV->setSection("llvm.metadata"); 4130 4131} 4132 4133// Metadata flags 4134enum MetaDataDlags { 4135 CLS = 0x0, 4136 CLS_META = 0x1, 4137 CLS_ROOT = 0x2, 4138 OBJC2_CLS_HIDDEN = 0x10, 4139 CLS_EXCEPTION = 0x20 4140}; 4141/// BuildClassRoTInitializer - generate meta-data for: 4142/// struct _class_ro_t { 4143/// uint32_t const flags; 4144/// uint32_t const instanceStart; 4145/// uint32_t const instanceSize; 4146/// uint32_t const reserved; // only when building for 64bit targets 4147/// const uint8_t * const ivarLayout; 4148/// const char *const name; 4149/// const struct _method_list_t * const baseMethods; 4150/// const struct _protocol_list_t *const baseProtocols; 4151/// const struct _ivar_list_t *const ivars; 4152/// const uint8_t * const weakIvarLayout; 4153/// const struct _prop_list_t * const properties; 4154/// } 4155/// 4156llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer( 4157 unsigned flags, 4158 unsigned InstanceStart, 4159 unsigned InstanceSize, 4160 const ObjCImplementationDecl *ID) { 4161 std::string ClassName = ID->getNameAsString(); 4162 std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets! 4163 Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags); 4164 Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart); 4165 Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize); 4166 // FIXME. For 64bit targets add 0 here. 4167 // FIXME. ivarLayout is currently null! 4168 Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes) 4169 : BuildIvarLayout(ID, true); 4170 // Values[ 3] = GetIvarLayoutName(0, ObjCTypes); 4171 Values[ 4] = GetClassName(ID->getIdentifier()); 4172 // const struct _method_list_t * const baseMethods; 4173 std::vector<llvm::Constant*> Methods; 4174 std::string MethodListName("\01l_OBJC_$_"); 4175 if (flags & CLS_META) { 4176 MethodListName += "CLASS_METHODS_" + ID->getNameAsString(); 4177 for (ObjCImplementationDecl::classmeth_iterator 4178 i = ID->classmeth_begin(CGM.getContext()), 4179 e = ID->classmeth_end(CGM.getContext()); i != e; ++i) { 4180 // Class methods should always be defined. 4181 Methods.push_back(GetMethodConstant(*i)); 4182 } 4183 } else { 4184 MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString(); 4185 for (ObjCImplementationDecl::instmeth_iterator 4186 i = ID->instmeth_begin(CGM.getContext()), 4187 e = ID->instmeth_end(CGM.getContext()); i != e; ++i) { 4188 // Instance methods should always be defined. 4189 Methods.push_back(GetMethodConstant(*i)); 4190 } 4191 for (ObjCImplementationDecl::propimpl_iterator 4192 i = ID->propimpl_begin(CGM.getContext()), 4193 e = ID->propimpl_end(CGM.getContext()); i != e; ++i) { 4194 ObjCPropertyImplDecl *PID = *i; 4195 4196 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){ 4197 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 4198 4199 if (ObjCMethodDecl *MD = PD->getGetterMethodDecl()) 4200 if (llvm::Constant *C = GetMethodConstant(MD)) 4201 Methods.push_back(C); 4202 if (ObjCMethodDecl *MD = PD->getSetterMethodDecl()) 4203 if (llvm::Constant *C = GetMethodConstant(MD)) 4204 Methods.push_back(C); 4205 } 4206 } 4207 } 4208 Values[ 5] = EmitMethodList(MethodListName, 4209 "__DATA, __objc_const", Methods); 4210 4211 const ObjCInterfaceDecl *OID = ID->getClassInterface(); 4212 assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer"); 4213 Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_" 4214 + OID->getNameAsString(), 4215 OID->protocol_begin(), 4216 OID->protocol_end()); 4217 4218 if (flags & CLS_META) 4219 Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy); 4220 else 4221 Values[ 7] = EmitIvarList(ID); 4222 // FIXME. weakIvarLayout is currently null. 4223 Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes) 4224 : BuildIvarLayout(ID, false); 4225 // Values[ 8] = GetIvarLayoutName(0, ObjCTypes); 4226 if (flags & CLS_META) 4227 Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); 4228 else 4229 Values[ 9] = 4230 EmitPropertyList( 4231 "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(), 4232 ID, ID->getClassInterface(), ObjCTypes); 4233 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy, 4234 Values); 4235 llvm::GlobalVariable *CLASS_RO_GV = 4236 new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false, 4237 llvm::GlobalValue::InternalLinkage, 4238 Init, 4239 (flags & CLS_META) ? 4240 std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName : 4241 std::string("\01l_OBJC_CLASS_RO_$_")+ClassName, 4242 &CGM.getModule()); 4243 CLASS_RO_GV->setAlignment( 4244 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy)); 4245 CLASS_RO_GV->setSection("__DATA, __objc_const"); 4246 return CLASS_RO_GV; 4247 4248} 4249 4250/// BuildClassMetaData - This routine defines that to-level meta-data 4251/// for the given ClassName for: 4252/// struct _class_t { 4253/// struct _class_t *isa; 4254/// struct _class_t * const superclass; 4255/// void *cache; 4256/// IMP *vtable; 4257/// struct class_ro_t *ro; 4258/// } 4259/// 4260llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData( 4261 std::string &ClassName, 4262 llvm::Constant *IsAGV, 4263 llvm::Constant *SuperClassGV, 4264 llvm::Constant *ClassRoGV, 4265 bool HiddenVisibility) { 4266 std::vector<llvm::Constant*> Values(5); 4267 Values[0] = IsAGV; 4268 Values[1] = SuperClassGV 4269 ? SuperClassGV 4270 : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy); 4271 Values[2] = ObjCEmptyCacheVar; // &ObjCEmptyCacheVar 4272 Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar 4273 Values[4] = ClassRoGV; // &CLASS_RO_GV 4274 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy, 4275 Values); 4276 llvm::GlobalVariable *GV = GetClassGlobal(ClassName); 4277 GV->setInitializer(Init); 4278 GV->setSection("__DATA, __objc_data"); 4279 GV->setAlignment( 4280 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy)); 4281 if (HiddenVisibility) 4282 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 4283 return GV; 4284} 4285 4286void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCInterfaceDecl *OID, 4287 uint32_t &InstanceStart, 4288 uint32_t &InstanceSize) { 4289 // Find first and last (non-padding) ivars in this interface. 4290 4291 // FIXME: Use iterator. 4292 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars; 4293 GetNamedIvarList(OID, OIvars); 4294 4295 if (OIvars.empty()) { 4296 InstanceStart = InstanceSize = 0; 4297 return; 4298 } 4299 4300 const ObjCIvarDecl *First = OIvars.front(); 4301 const ObjCIvarDecl *Last = OIvars.back(); 4302 4303 InstanceStart = ComputeIvarBaseOffset(CGM, OID, First); 4304 const llvm::Type *FieldTy = 4305 CGM.getTypes().ConvertTypeForMem(Last->getType()); 4306 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy); 4307// FIXME. This breaks compatibility with llvm-gcc-4.2 (but makes it compatible 4308// with gcc-4.2). We postpone this for now. 4309#if 0 4310 if (Last->isBitField()) { 4311 Expr *BitWidth = Last->getBitWidth(); 4312 uint64_t BitFieldSize = 4313 BitWidth->getIntegerConstantExprValue(CGM.getContext()).getZExtValue(); 4314 Size = (BitFieldSize / 8) + ((BitFieldSize % 8) != 0); 4315 } 4316#endif 4317 InstanceSize = ComputeIvarBaseOffset(CGM, OID, Last) + Size; 4318} 4319 4320void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) { 4321 std::string ClassName = ID->getNameAsString(); 4322 if (!ObjCEmptyCacheVar) { 4323 ObjCEmptyCacheVar = new llvm::GlobalVariable( 4324 ObjCTypes.CacheTy, 4325 false, 4326 llvm::GlobalValue::ExternalLinkage, 4327 0, 4328 "_objc_empty_cache", 4329 &CGM.getModule()); 4330 4331 ObjCEmptyVtableVar = new llvm::GlobalVariable( 4332 ObjCTypes.ImpnfABITy, 4333 false, 4334 llvm::GlobalValue::ExternalLinkage, 4335 0, 4336 "_objc_empty_vtable", 4337 &CGM.getModule()); 4338 } 4339 assert(ID->getClassInterface() && 4340 "CGObjCNonFragileABIMac::GenerateClass - class is 0"); 4341 // FIXME: Is this correct (that meta class size is never computed)? 4342 uint32_t InstanceStart = 4343 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy); 4344 uint32_t InstanceSize = InstanceStart; 4345 uint32_t flags = CLS_META; 4346 std::string ObjCMetaClassName(getMetaclassSymbolPrefix()); 4347 std::string ObjCClassName(getClassSymbolPrefix()); 4348 4349 llvm::GlobalVariable *SuperClassGV, *IsAGV; 4350 4351 bool classIsHidden = 4352 CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden; 4353 if (classIsHidden) 4354 flags |= OBJC2_CLS_HIDDEN; 4355 if (!ID->getClassInterface()->getSuperClass()) { 4356 // class is root 4357 flags |= CLS_ROOT; 4358 SuperClassGV = GetClassGlobal(ObjCClassName + ClassName); 4359 IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName); 4360 } else { 4361 // Has a root. Current class is not a root. 4362 const ObjCInterfaceDecl *Root = ID->getClassInterface(); 4363 while (const ObjCInterfaceDecl *Super = Root->getSuperClass()) 4364 Root = Super; 4365 IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString()); 4366 // work on super class metadata symbol. 4367 std::string SuperClassName = 4368 ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString(); 4369 SuperClassGV = GetClassGlobal(SuperClassName); 4370 } 4371 llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags, 4372 InstanceStart, 4373 InstanceSize,ID); 4374 std::string TClassName = ObjCMetaClassName + ClassName; 4375 llvm::GlobalVariable *MetaTClass = 4376 BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV, 4377 classIsHidden); 4378 4379 // Metadata for the class 4380 flags = CLS; 4381 if (classIsHidden) 4382 flags |= OBJC2_CLS_HIDDEN; 4383 4384 if (hasObjCExceptionAttribute(ID->getClassInterface())) 4385 flags |= CLS_EXCEPTION; 4386 4387 if (!ID->getClassInterface()->getSuperClass()) { 4388 flags |= CLS_ROOT; 4389 SuperClassGV = 0; 4390 } else { 4391 // Has a root. Current class is not a root. 4392 std::string RootClassName = 4393 ID->getClassInterface()->getSuperClass()->getNameAsString(); 4394 SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName); 4395 } 4396 GetClassSizeInfo(ID->getClassInterface(), InstanceStart, InstanceSize); 4397 CLASS_RO_GV = BuildClassRoTInitializer(flags, 4398 InstanceStart, 4399 InstanceSize, 4400 ID); 4401 4402 TClassName = ObjCClassName + ClassName; 4403 llvm::GlobalVariable *ClassMD = 4404 BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV, 4405 classIsHidden); 4406 DefinedClasses.push_back(ClassMD); 4407 4408 // Force the definition of the EHType if necessary. 4409 if (flags & CLS_EXCEPTION) 4410 GetInterfaceEHType(ID->getClassInterface(), true); 4411} 4412 4413/// GenerateProtocolRef - This routine is called to generate code for 4414/// a protocol reference expression; as in: 4415/// @code 4416/// @protocol(Proto1); 4417/// @endcode 4418/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1 4419/// which will hold address of the protocol meta-data. 4420/// 4421llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder, 4422 const ObjCProtocolDecl *PD) { 4423 4424 // This routine is called for @protocol only. So, we must build definition 4425 // of protocol's meta-data (not a reference to it!) 4426 // 4427 llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD), 4428 ObjCTypes.ExternalProtocolPtrTy); 4429 4430 std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_"); 4431 ProtocolName += PD->getNameAsCString(); 4432 4433 llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName); 4434 if (PTGV) 4435 return Builder.CreateLoad(PTGV, false, "tmp"); 4436 PTGV = new llvm::GlobalVariable( 4437 Init->getType(), false, 4438 llvm::GlobalValue::WeakAnyLinkage, 4439 Init, 4440 ProtocolName, 4441 &CGM.getModule()); 4442 PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip"); 4443 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility); 4444 UsedGlobals.push_back(PTGV); 4445 return Builder.CreateLoad(PTGV, false, "tmp"); 4446} 4447 4448/// GenerateCategory - Build metadata for a category implementation. 4449/// struct _category_t { 4450/// const char * const name; 4451/// struct _class_t *const cls; 4452/// const struct _method_list_t * const instance_methods; 4453/// const struct _method_list_t * const class_methods; 4454/// const struct _protocol_list_t * const protocols; 4455/// const struct _prop_list_t * const properties; 4456/// } 4457/// 4458void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) 4459{ 4460 const ObjCInterfaceDecl *Interface = OCD->getClassInterface(); 4461 const char *Prefix = "\01l_OBJC_$_CATEGORY_"; 4462 std::string ExtCatName(Prefix + Interface->getNameAsString()+ 4463 "_$_" + OCD->getNameAsString()); 4464 std::string ExtClassName(getClassSymbolPrefix() + 4465 Interface->getNameAsString()); 4466 4467 std::vector<llvm::Constant*> Values(6); 4468 Values[0] = GetClassName(OCD->getIdentifier()); 4469 // meta-class entry symbol 4470 llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName); 4471 Values[1] = ClassGV; 4472 std::vector<llvm::Constant*> Methods; 4473 std::string MethodListName(Prefix); 4474 MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() + 4475 "_$_" + OCD->getNameAsString(); 4476 4477 for (ObjCCategoryImplDecl::instmeth_iterator 4478 i = OCD->instmeth_begin(CGM.getContext()), 4479 e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) { 4480 // Instance methods should always be defined. 4481 Methods.push_back(GetMethodConstant(*i)); 4482 } 4483 4484 Values[2] = EmitMethodList(MethodListName, 4485 "__DATA, __objc_const", 4486 Methods); 4487 4488 MethodListName = Prefix; 4489 MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" + 4490 OCD->getNameAsString(); 4491 Methods.clear(); 4492 for (ObjCCategoryImplDecl::classmeth_iterator 4493 i = OCD->classmeth_begin(CGM.getContext()), 4494 e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) { 4495 // Class methods should always be defined. 4496 Methods.push_back(GetMethodConstant(*i)); 4497 } 4498 4499 Values[3] = EmitMethodList(MethodListName, 4500 "__DATA, __objc_const", 4501 Methods); 4502 const ObjCCategoryDecl *Category = 4503 Interface->FindCategoryDeclaration(OCD->getIdentifier()); 4504 if (Category) { 4505 std::string ExtName(Interface->getNameAsString() + "_$_" + 4506 OCD->getNameAsString()); 4507 Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_" 4508 + Interface->getNameAsString() + "_$_" 4509 + Category->getNameAsString(), 4510 Category->protocol_begin(), 4511 Category->protocol_end()); 4512 Values[5] = 4513 EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName, 4514 OCD, Category, ObjCTypes); 4515 } 4516 else { 4517 Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy); 4518 Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); 4519 } 4520 4521 llvm::Constant *Init = 4522 llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy, 4523 Values); 4524 llvm::GlobalVariable *GCATV 4525 = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy, 4526 false, 4527 llvm::GlobalValue::InternalLinkage, 4528 Init, 4529 ExtCatName, 4530 &CGM.getModule()); 4531 GCATV->setAlignment( 4532 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy)); 4533 GCATV->setSection("__DATA, __objc_const"); 4534 UsedGlobals.push_back(GCATV); 4535 DefinedCategories.push_back(GCATV); 4536} 4537 4538/// GetMethodConstant - Return a struct objc_method constant for the 4539/// given method if it has been defined. The result is null if the 4540/// method has not been defined. The return value has type MethodPtrTy. 4541llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant( 4542 const ObjCMethodDecl *MD) { 4543 // FIXME: Use DenseMap::lookup 4544 llvm::Function *Fn = MethodDefinitions[MD]; 4545 if (!Fn) 4546 return 0; 4547 4548 std::vector<llvm::Constant*> Method(3); 4549 Method[0] = 4550 llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()), 4551 ObjCTypes.SelectorPtrTy); 4552 Method[1] = GetMethodVarType(MD); 4553 Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy); 4554 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method); 4555} 4556 4557/// EmitMethodList - Build meta-data for method declarations 4558/// struct _method_list_t { 4559/// uint32_t entsize; // sizeof(struct _objc_method) 4560/// uint32_t method_count; 4561/// struct _objc_method method_list[method_count]; 4562/// } 4563/// 4564llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList( 4565 const std::string &Name, 4566 const char *Section, 4567 const ConstantVector &Methods) { 4568 // Return null for empty list. 4569 if (Methods.empty()) 4570 return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy); 4571 4572 std::vector<llvm::Constant*> Values(3); 4573 // sizeof(struct _objc_method) 4574 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy); 4575 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 4576 // method_count 4577 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size()); 4578 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy, 4579 Methods.size()); 4580 Values[2] = llvm::ConstantArray::get(AT, Methods); 4581 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 4582 4583 llvm::GlobalVariable *GV = 4584 new llvm::GlobalVariable(Init->getType(), false, 4585 llvm::GlobalValue::InternalLinkage, 4586 Init, 4587 Name, 4588 &CGM.getModule()); 4589 GV->setAlignment( 4590 CGM.getTargetData().getPrefTypeAlignment(Init->getType())); 4591 GV->setSection(Section); 4592 UsedGlobals.push_back(GV); 4593 return llvm::ConstantExpr::getBitCast(GV, 4594 ObjCTypes.MethodListnfABIPtrTy); 4595} 4596 4597/// ObjCIvarOffsetVariable - Returns the ivar offset variable for 4598/// the given ivar. 4599/// 4600llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable( 4601 const ObjCInterfaceDecl *ID, 4602 const ObjCIvarDecl *Ivar) { 4603 std::string Name = "OBJC_IVAR_$_" + 4604 getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() + 4605 '.' + Ivar->getNameAsString(); 4606 llvm::GlobalVariable *IvarOffsetGV = 4607 CGM.getModule().getGlobalVariable(Name); 4608 if (!IvarOffsetGV) 4609 IvarOffsetGV = 4610 new llvm::GlobalVariable(ObjCTypes.LongTy, 4611 false, 4612 llvm::GlobalValue::ExternalLinkage, 4613 0, 4614 Name, 4615 &CGM.getModule()); 4616 return IvarOffsetGV; 4617} 4618 4619llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar( 4620 const ObjCInterfaceDecl *ID, 4621 const ObjCIvarDecl *Ivar, 4622 unsigned long int Offset) { 4623 llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar); 4624 IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy, 4625 Offset)); 4626 IvarOffsetGV->setAlignment( 4627 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy)); 4628 4629 // FIXME: This matches gcc, but shouldn't the visibility be set on 4630 // the use as well (i.e., in ObjCIvarOffsetVariable). 4631 if (Ivar->getAccessControl() == ObjCIvarDecl::Private || 4632 Ivar->getAccessControl() == ObjCIvarDecl::Package || 4633 CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden) 4634 IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility); 4635 else 4636 IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility); 4637 IvarOffsetGV->setSection("__DATA, __objc_const"); 4638 return IvarOffsetGV; 4639} 4640 4641/// EmitIvarList - Emit the ivar list for the given 4642/// implementation. The return value has type 4643/// IvarListnfABIPtrTy. 4644/// struct _ivar_t { 4645/// unsigned long int *offset; // pointer to ivar offset location 4646/// char *name; 4647/// char *type; 4648/// uint32_t alignment; 4649/// uint32_t size; 4650/// } 4651/// struct _ivar_list_t { 4652/// uint32 entsize; // sizeof(struct _ivar_t) 4653/// uint32 count; 4654/// struct _iver_t list[count]; 4655/// } 4656/// 4657 4658void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID, 4659 llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const { 4660 for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(), 4661 E = OID->ivar_end(); I != E; ++I) { 4662 // Ignore unnamed bit-fields. 4663 if (!(*I)->getDeclName()) 4664 continue; 4665 4666 Res.push_back(*I); 4667 } 4668 4669 for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()), 4670 E = OID->prop_end(CGM.getContext()); I != E; ++I) 4671 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl()) 4672 Res.push_back(IV); 4673} 4674 4675llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList( 4676 const ObjCImplementationDecl *ID) { 4677 4678 std::vector<llvm::Constant*> Ivars, Ivar(5); 4679 4680 const ObjCInterfaceDecl *OID = ID->getClassInterface(); 4681 assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface"); 4682 4683 // FIXME. Consolidate this with similar code in GenerateClass. 4684 4685 // Collect declared and synthesized ivars in a small vector. 4686 llvm::SmallVector<ObjCIvarDecl*, 16> OIvars; 4687 GetNamedIvarList(OID, OIvars); 4688 4689 for (unsigned i = 0, e = OIvars.size(); i != e; ++i) { 4690 ObjCIvarDecl *IVD = OIvars[i]; 4691 Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD, 4692 ComputeIvarBaseOffset(CGM, OID, IVD)); 4693 Ivar[1] = GetMethodVarName(IVD->getIdentifier()); 4694 Ivar[2] = GetMethodVarType(IVD); 4695 const llvm::Type *FieldTy = 4696 CGM.getTypes().ConvertTypeForMem(IVD->getType()); 4697 unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy); 4698 unsigned Align = CGM.getContext().getPreferredTypeAlign( 4699 IVD->getType().getTypePtr()) >> 3; 4700 Align = llvm::Log2_32(Align); 4701 Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align); 4702 // NOTE. Size of a bitfield does not match gcc's, because of the 4703 // way bitfields are treated special in each. But I am told that 4704 // 'size' for bitfield ivars is ignored by the runtime so it does 4705 // not matter. If it matters, there is enough info to get the 4706 // bitfield right! 4707 Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 4708 Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar)); 4709 } 4710 // Return null for empty list. 4711 if (Ivars.empty()) 4712 return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy); 4713 std::vector<llvm::Constant*> Values(3); 4714 unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy); 4715 Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 4716 Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size()); 4717 llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy, 4718 Ivars.size()); 4719 Values[2] = llvm::ConstantArray::get(AT, Ivars); 4720 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 4721 const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_"; 4722 llvm::GlobalVariable *GV = 4723 new llvm::GlobalVariable(Init->getType(), false, 4724 llvm::GlobalValue::InternalLinkage, 4725 Init, 4726 Prefix + OID->getNameAsString(), 4727 &CGM.getModule()); 4728 GV->setAlignment( 4729 CGM.getTargetData().getPrefTypeAlignment(Init->getType())); 4730 GV->setSection("__DATA, __objc_const"); 4731 4732 UsedGlobals.push_back(GV); 4733 return llvm::ConstantExpr::getBitCast(GV, 4734 ObjCTypes.IvarListnfABIPtrTy); 4735} 4736 4737llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef( 4738 const ObjCProtocolDecl *PD) { 4739 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()]; 4740 4741 if (!Entry) { 4742 // We use the initializer as a marker of whether this is a forward 4743 // reference or not. At module finalization we add the empty 4744 // contents for protocols which were referenced but never defined. 4745 Entry = 4746 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false, 4747 llvm::GlobalValue::ExternalLinkage, 4748 0, 4749 "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(), 4750 &CGM.getModule()); 4751 Entry->setSection("__DATA,__datacoal_nt,coalesced"); 4752 UsedGlobals.push_back(Entry); 4753 } 4754 4755 return Entry; 4756} 4757 4758/// GetOrEmitProtocol - Generate the protocol meta-data: 4759/// @code 4760/// struct _protocol_t { 4761/// id isa; // NULL 4762/// const char * const protocol_name; 4763/// const struct _protocol_list_t * protocol_list; // super protocols 4764/// const struct method_list_t * const instance_methods; 4765/// const struct method_list_t * const class_methods; 4766/// const struct method_list_t *optionalInstanceMethods; 4767/// const struct method_list_t *optionalClassMethods; 4768/// const struct _prop_list_t * properties; 4769/// const uint32_t size; // sizeof(struct _protocol_t) 4770/// const uint32_t flags; // = 0 4771/// } 4772/// @endcode 4773/// 4774 4775llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol( 4776 const ObjCProtocolDecl *PD) { 4777 llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()]; 4778 4779 // Early exit if a defining object has already been generated. 4780 if (Entry && Entry->hasInitializer()) 4781 return Entry; 4782 4783 const char *ProtocolName = PD->getNameAsCString(); 4784 4785 // Construct method lists. 4786 std::vector<llvm::Constant*> InstanceMethods, ClassMethods; 4787 std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods; 4788 for (ObjCProtocolDecl::instmeth_iterator 4789 i = PD->instmeth_begin(CGM.getContext()), 4790 e = PD->instmeth_end(CGM.getContext()); 4791 i != e; ++i) { 4792 ObjCMethodDecl *MD = *i; 4793 llvm::Constant *C = GetMethodDescriptionConstant(MD); 4794 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { 4795 OptInstanceMethods.push_back(C); 4796 } else { 4797 InstanceMethods.push_back(C); 4798 } 4799 } 4800 4801 for (ObjCProtocolDecl::classmeth_iterator 4802 i = PD->classmeth_begin(CGM.getContext()), 4803 e = PD->classmeth_end(CGM.getContext()); 4804 i != e; ++i) { 4805 ObjCMethodDecl *MD = *i; 4806 llvm::Constant *C = GetMethodDescriptionConstant(MD); 4807 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { 4808 OptClassMethods.push_back(C); 4809 } else { 4810 ClassMethods.push_back(C); 4811 } 4812 } 4813 4814 std::vector<llvm::Constant*> Values(10); 4815 // isa is NULL 4816 Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy); 4817 Values[1] = GetClassName(PD->getIdentifier()); 4818 Values[2] = EmitProtocolList( 4819 "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(), 4820 PD->protocol_begin(), 4821 PD->protocol_end()); 4822 4823 Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_" 4824 + PD->getNameAsString(), 4825 "__DATA, __objc_const", 4826 InstanceMethods); 4827 Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_" 4828 + PD->getNameAsString(), 4829 "__DATA, __objc_const", 4830 ClassMethods); 4831 Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_" 4832 + PD->getNameAsString(), 4833 "__DATA, __objc_const", 4834 OptInstanceMethods); 4835 Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_" 4836 + PD->getNameAsString(), 4837 "__DATA, __objc_const", 4838 OptClassMethods); 4839 Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(), 4840 0, PD, ObjCTypes); 4841 uint32_t Size = 4842 CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy); 4843 Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size); 4844 Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy); 4845 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy, 4846 Values); 4847 4848 if (Entry) { 4849 // Already created, fix the linkage and update the initializer. 4850 Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage); 4851 Entry->setInitializer(Init); 4852 } else { 4853 Entry = 4854 new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false, 4855 llvm::GlobalValue::WeakAnyLinkage, 4856 Init, 4857 std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName, 4858 &CGM.getModule()); 4859 Entry->setAlignment( 4860 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy)); 4861 Entry->setSection("__DATA,__datacoal_nt,coalesced"); 4862 } 4863 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility); 4864 4865 // Use this protocol meta-data to build protocol list table in section 4866 // __DATA, __objc_protolist 4867 llvm::GlobalVariable *PTGV = new llvm::GlobalVariable( 4868 ObjCTypes.ProtocolnfABIPtrTy, false, 4869 llvm::GlobalValue::WeakAnyLinkage, 4870 Entry, 4871 std::string("\01l_OBJC_LABEL_PROTOCOL_$_") 4872 +ProtocolName, 4873 &CGM.getModule()); 4874 PTGV->setAlignment( 4875 CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy)); 4876 PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip"); 4877 PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility); 4878 UsedGlobals.push_back(PTGV); 4879 return Entry; 4880} 4881 4882/// EmitProtocolList - Generate protocol list meta-data: 4883/// @code 4884/// struct _protocol_list_t { 4885/// long protocol_count; // Note, this is 32/64 bit 4886/// struct _protocol_t[protocol_count]; 4887/// } 4888/// @endcode 4889/// 4890llvm::Constant * 4891CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name, 4892 ObjCProtocolDecl::protocol_iterator begin, 4893 ObjCProtocolDecl::protocol_iterator end) { 4894 std::vector<llvm::Constant*> ProtocolRefs; 4895 4896 // Just return null for empty protocol lists 4897 if (begin == end) 4898 return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy); 4899 4900 // FIXME: We shouldn't need to do this lookup here, should we? 4901 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true); 4902 if (GV) 4903 return llvm::ConstantExpr::getBitCast(GV, 4904 ObjCTypes.ProtocolListnfABIPtrTy); 4905 4906 for (; begin != end; ++begin) 4907 ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented??? 4908 4909 // This list is null terminated. 4910 ProtocolRefs.push_back(llvm::Constant::getNullValue( 4911 ObjCTypes.ProtocolnfABIPtrTy)); 4912 4913 std::vector<llvm::Constant*> Values(2); 4914 Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1); 4915 Values[1] = 4916 llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy, 4917 ProtocolRefs.size()), 4918 ProtocolRefs); 4919 4920 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 4921 GV = new llvm::GlobalVariable(Init->getType(), false, 4922 llvm::GlobalValue::InternalLinkage, 4923 Init, 4924 Name, 4925 &CGM.getModule()); 4926 GV->setSection("__DATA, __objc_const"); 4927 GV->setAlignment( 4928 CGM.getTargetData().getPrefTypeAlignment(Init->getType())); 4929 UsedGlobals.push_back(GV); 4930 return llvm::ConstantExpr::getBitCast(GV, 4931 ObjCTypes.ProtocolListnfABIPtrTy); 4932} 4933 4934/// GetMethodDescriptionConstant - This routine build following meta-data: 4935/// struct _objc_method { 4936/// SEL _cmd; 4937/// char *method_type; 4938/// char *_imp; 4939/// } 4940 4941llvm::Constant * 4942CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) { 4943 std::vector<llvm::Constant*> Desc(3); 4944 Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()), 4945 ObjCTypes.SelectorPtrTy); 4946 Desc[1] = GetMethodVarType(MD); 4947 // Protocol methods have no implementation. So, this entry is always NULL. 4948 Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 4949 return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc); 4950} 4951 4952/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference. 4953/// This code gen. amounts to generating code for: 4954/// @code 4955/// (type *)((char *)base + _OBJC_IVAR_$_.ivar; 4956/// @encode 4957/// 4958LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar( 4959 CodeGen::CodeGenFunction &CGF, 4960 QualType ObjectTy, 4961 llvm::Value *BaseValue, 4962 const ObjCIvarDecl *Ivar, 4963 unsigned CVRQualifiers) { 4964 const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl(); 4965 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers, 4966 EmitIvarOffset(CGF, ID, Ivar)); 4967} 4968 4969llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset( 4970 CodeGen::CodeGenFunction &CGF, 4971 const ObjCInterfaceDecl *Interface, 4972 const ObjCIvarDecl *Ivar) { 4973 return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar), 4974 false, "ivar"); 4975} 4976 4977CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend( 4978 CodeGen::CodeGenFunction &CGF, 4979 QualType ResultType, 4980 Selector Sel, 4981 llvm::Value *Receiver, 4982 QualType Arg0Ty, 4983 bool IsSuper, 4984 const CallArgList &CallArgs) { 4985 // FIXME. Even though IsSuper is passes. This function doese not 4986 // handle calls to 'super' receivers. 4987 CodeGenTypes &Types = CGM.getTypes(); 4988 llvm::Value *Arg0 = Receiver; 4989 if (!IsSuper) 4990 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp"); 4991 4992 // Find the message function name. 4993 // FIXME. This is too much work to get the ABI-specific result type 4994 // needed to find the message name. 4995 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, 4996 llvm::SmallVector<QualType, 16>()); 4997 llvm::Constant *Fn; 4998 std::string Name("\01l_"); 4999 if (CGM.ReturnTypeUsesSret(FnInfo)) { 5000#if 0 5001 // unlike what is documented. gcc never generates this API!! 5002 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) { 5003 Fn = ObjCTypes.getMessageSendIdStretFixupFn(); 5004 // FIXME. Is there a better way of getting these names. 5005 // They are available in RuntimeFunctions vector pair. 5006 Name += "objc_msgSendId_stret_fixup"; 5007 } 5008 else 5009#endif 5010 if (IsSuper) { 5011 Fn = ObjCTypes.getMessageSendSuper2StretFixupFn(); 5012 Name += "objc_msgSendSuper2_stret_fixup"; 5013 } 5014 else 5015 { 5016 Fn = ObjCTypes.getMessageSendStretFixupFn(); 5017 Name += "objc_msgSend_stret_fixup"; 5018 } 5019 } 5020 else if (ResultType->isFloatingType() && 5021 // Selection of frret API only happens in 32bit nonfragile ABI. 5022 CGM.getTargetData().getTypePaddedSize(ObjCTypes.LongTy) == 4) { 5023 Fn = ObjCTypes.getMessageSendFpretFixupFn(); 5024 Name += "objc_msgSend_fpret_fixup"; 5025 } 5026 else { 5027#if 0 5028// unlike what is documented. gcc never generates this API!! 5029 if (Receiver->getType() == ObjCTypes.ObjectPtrTy) { 5030 Fn = ObjCTypes.getMessageSendIdFixupFn(); 5031 Name += "objc_msgSendId_fixup"; 5032 } 5033 else 5034#endif 5035 if (IsSuper) { 5036 Fn = ObjCTypes.getMessageSendSuper2FixupFn(); 5037 Name += "objc_msgSendSuper2_fixup"; 5038 } 5039 else 5040 { 5041 Fn = ObjCTypes.getMessageSendFixupFn(); 5042 Name += "objc_msgSend_fixup"; 5043 } 5044 } 5045 Name += '_'; 5046 std::string SelName(Sel.getAsString()); 5047 // Replace all ':' in selector name with '_' ouch! 5048 for(unsigned i = 0; i < SelName.size(); i++) 5049 if (SelName[i] == ':') 5050 SelName[i] = '_'; 5051 Name += SelName; 5052 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name); 5053 if (!GV) { 5054 // Build message ref table entry. 5055 std::vector<llvm::Constant*> Values(2); 5056 Values[0] = Fn; 5057 Values[1] = GetMethodVarName(Sel); 5058 llvm::Constant *Init = llvm::ConstantStruct::get(Values); 5059 GV = new llvm::GlobalVariable(Init->getType(), false, 5060 llvm::GlobalValue::WeakAnyLinkage, 5061 Init, 5062 Name, 5063 &CGM.getModule()); 5064 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 5065 GV->setAlignment(16); 5066 GV->setSection("__DATA, __objc_msgrefs, coalesced"); 5067 } 5068 llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy); 5069 5070 CallArgList ActualArgs; 5071 ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty)); 5072 ActualArgs.push_back(std::make_pair(RValue::get(Arg1), 5073 ObjCTypes.MessageRefCPtrTy)); 5074 ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end()); 5075 const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs); 5076 llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0); 5077 Callee = CGF.Builder.CreateLoad(Callee); 5078 const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true); 5079 Callee = CGF.Builder.CreateBitCast(Callee, 5080 llvm::PointerType::getUnqual(FTy)); 5081 return CGF.EmitCall(FnInfo1, Callee, ActualArgs); 5082} 5083 5084/// Generate code for a message send expression in the nonfragile abi. 5085CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend( 5086 CodeGen::CodeGenFunction &CGF, 5087 QualType ResultType, 5088 Selector Sel, 5089 llvm::Value *Receiver, 5090 bool IsClassMessage, 5091 const CallArgList &CallArgs) { 5092 return EmitMessageSend(CGF, ResultType, Sel, 5093 Receiver, CGF.getContext().getObjCIdType(), 5094 false, CallArgs); 5095} 5096 5097llvm::GlobalVariable * 5098CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) { 5099 llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name); 5100 5101 if (!GV) { 5102 GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false, 5103 llvm::GlobalValue::ExternalLinkage, 5104 0, Name, &CGM.getModule()); 5105 } 5106 5107 return GV; 5108} 5109 5110llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder, 5111 const ObjCInterfaceDecl *ID) { 5112 llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()]; 5113 5114 if (!Entry) { 5115 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString()); 5116 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName); 5117 Entry = 5118 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false, 5119 llvm::GlobalValue::InternalLinkage, 5120 ClassGV, 5121 "\01L_OBJC_CLASSLIST_REFERENCES_$_", 5122 &CGM.getModule()); 5123 Entry->setAlignment( 5124 CGM.getTargetData().getPrefTypeAlignment( 5125 ObjCTypes.ClassnfABIPtrTy)); 5126 Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip"); 5127 UsedGlobals.push_back(Entry); 5128 } 5129 5130 return Builder.CreateLoad(Entry, false, "tmp"); 5131} 5132 5133llvm::Value * 5134CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder, 5135 const ObjCInterfaceDecl *ID) { 5136 llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()]; 5137 5138 if (!Entry) { 5139 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString()); 5140 llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName); 5141 Entry = 5142 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false, 5143 llvm::GlobalValue::InternalLinkage, 5144 ClassGV, 5145 "\01L_OBJC_CLASSLIST_SUP_REFS_$_", 5146 &CGM.getModule()); 5147 Entry->setAlignment( 5148 CGM.getTargetData().getPrefTypeAlignment( 5149 ObjCTypes.ClassnfABIPtrTy)); 5150 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip"); 5151 UsedGlobals.push_back(Entry); 5152 } 5153 5154 return Builder.CreateLoad(Entry, false, "tmp"); 5155} 5156 5157/// EmitMetaClassRef - Return a Value * of the address of _class_t 5158/// meta-data 5159/// 5160llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder, 5161 const ObjCInterfaceDecl *ID) { 5162 llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()]; 5163 if (Entry) 5164 return Builder.CreateLoad(Entry, false, "tmp"); 5165 5166 std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString()); 5167 llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName); 5168 Entry = 5169 new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false, 5170 llvm::GlobalValue::InternalLinkage, 5171 MetaClassGV, 5172 "\01L_OBJC_CLASSLIST_SUP_REFS_$_", 5173 &CGM.getModule()); 5174 Entry->setAlignment( 5175 CGM.getTargetData().getPrefTypeAlignment( 5176 ObjCTypes.ClassnfABIPtrTy)); 5177 5178 Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip"); 5179 UsedGlobals.push_back(Entry); 5180 5181 return Builder.CreateLoad(Entry, false, "tmp"); 5182} 5183 5184/// GetClass - Return a reference to the class for the given interface 5185/// decl. 5186llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder, 5187 const ObjCInterfaceDecl *ID) { 5188 return EmitClassRef(Builder, ID); 5189} 5190 5191/// Generates a message send where the super is the receiver. This is 5192/// a message send to self with special delivery semantics indicating 5193/// which class's method should be called. 5194CodeGen::RValue 5195CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, 5196 QualType ResultType, 5197 Selector Sel, 5198 const ObjCInterfaceDecl *Class, 5199 bool isCategoryImpl, 5200 llvm::Value *Receiver, 5201 bool IsClassMessage, 5202 const CodeGen::CallArgList &CallArgs) { 5203 // ... 5204 // Create and init a super structure; this is a (receiver, class) 5205 // pair we will pass to objc_msgSendSuper. 5206 llvm::Value *ObjCSuper = 5207 CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super"); 5208 5209 llvm::Value *ReceiverAsObject = 5210 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy); 5211 CGF.Builder.CreateStore(ReceiverAsObject, 5212 CGF.Builder.CreateStructGEP(ObjCSuper, 0)); 5213 5214 // If this is a class message the metaclass is passed as the target. 5215 llvm::Value *Target; 5216 if (IsClassMessage) { 5217 if (isCategoryImpl) { 5218 // Message sent to "super' in a class method defined in 5219 // a category implementation. 5220 Target = EmitClassRef(CGF.Builder, Class); 5221 Target = CGF.Builder.CreateStructGEP(Target, 0); 5222 Target = CGF.Builder.CreateLoad(Target); 5223 } 5224 else 5225 Target = EmitMetaClassRef(CGF.Builder, Class); 5226 } 5227 else 5228 Target = EmitSuperClassRef(CGF.Builder, Class); 5229 5230 // FIXME: We shouldn't need to do this cast, rectify the ASTContext 5231 // and ObjCTypes types. 5232 const llvm::Type *ClassTy = 5233 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType()); 5234 Target = CGF.Builder.CreateBitCast(Target, ClassTy); 5235 CGF.Builder.CreateStore(Target, 5236 CGF.Builder.CreateStructGEP(ObjCSuper, 1)); 5237 5238 return EmitMessageSend(CGF, ResultType, Sel, 5239 ObjCSuper, ObjCTypes.SuperPtrCTy, 5240 true, CallArgs); 5241} 5242 5243llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder, 5244 Selector Sel) { 5245 llvm::GlobalVariable *&Entry = SelectorReferences[Sel]; 5246 5247 if (!Entry) { 5248 llvm::Constant *Casted = 5249 llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel), 5250 ObjCTypes.SelectorPtrTy); 5251 Entry = 5252 new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false, 5253 llvm::GlobalValue::InternalLinkage, 5254 Casted, "\01L_OBJC_SELECTOR_REFERENCES_", 5255 &CGM.getModule()); 5256 Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip"); 5257 UsedGlobals.push_back(Entry); 5258 } 5259 5260 return Builder.CreateLoad(Entry, false, "tmp"); 5261} 5262/// EmitObjCIvarAssign - Code gen for assigning to a __strong object. 5263/// objc_assign_ivar (id src, id *dst) 5264/// 5265void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, 5266 llvm::Value *src, llvm::Value *dst) 5267{ 5268 const llvm::Type * SrcTy = src->getType(); 5269 if (!isa<llvm::PointerType>(SrcTy)) { 5270 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy); 5271 assert(Size <= 8 && "does not support size > 8"); 5272 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) 5273 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy)); 5274 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); 5275 } 5276 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 5277 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 5278 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(), 5279 src, dst, "assignivar"); 5280 return; 5281} 5282 5283/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object. 5284/// objc_assign_strongCast (id src, id *dst) 5285/// 5286void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign( 5287 CodeGen::CodeGenFunction &CGF, 5288 llvm::Value *src, llvm::Value *dst) 5289{ 5290 const llvm::Type * SrcTy = src->getType(); 5291 if (!isa<llvm::PointerType>(SrcTy)) { 5292 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy); 5293 assert(Size <= 8 && "does not support size > 8"); 5294 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) 5295 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy)); 5296 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); 5297 } 5298 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 5299 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 5300 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(), 5301 src, dst, "weakassign"); 5302 return; 5303} 5304 5305/// EmitObjCWeakRead - Code gen for loading value of a __weak 5306/// object: objc_read_weak (id *src) 5307/// 5308llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead( 5309 CodeGen::CodeGenFunction &CGF, 5310 llvm::Value *AddrWeakObj) 5311{ 5312 const llvm::Type* DestTy = 5313 cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType(); 5314 AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy); 5315 llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(), 5316 AddrWeakObj, "weakread"); 5317 read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy); 5318 return read_weak; 5319} 5320 5321/// EmitObjCWeakAssign - Code gen for assigning to a __weak object. 5322/// objc_assign_weak (id src, id *dst) 5323/// 5324void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, 5325 llvm::Value *src, llvm::Value *dst) 5326{ 5327 const llvm::Type * SrcTy = src->getType(); 5328 if (!isa<llvm::PointerType>(SrcTy)) { 5329 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy); 5330 assert(Size <= 8 && "does not support size > 8"); 5331 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) 5332 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy)); 5333 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); 5334 } 5335 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 5336 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 5337 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(), 5338 src, dst, "weakassign"); 5339 return; 5340} 5341 5342/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object. 5343/// objc_assign_global (id src, id *dst) 5344/// 5345void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, 5346 llvm::Value *src, llvm::Value *dst) 5347{ 5348 const llvm::Type * SrcTy = src->getType(); 5349 if (!isa<llvm::PointerType>(SrcTy)) { 5350 unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy); 5351 assert(Size <= 8 && "does not support size > 8"); 5352 src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) 5353 : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy)); 5354 src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); 5355 } 5356 src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); 5357 dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); 5358 CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(), 5359 src, dst, "globalassign"); 5360 return; 5361} 5362 5363void 5364CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, 5365 const Stmt &S) { 5366 bool isTry = isa<ObjCAtTryStmt>(S); 5367 llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try"); 5368 llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest(); 5369 llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler"); 5370 llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally"); 5371 llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw"); 5372 llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end"); 5373 5374 // For @synchronized, call objc_sync_enter(sync.expr). The 5375 // evaluation of the expression must occur before we enter the 5376 // @synchronized. We can safely avoid a temp here because jumps into 5377 // @synchronized are illegal & this will dominate uses. 5378 llvm::Value *SyncArg = 0; 5379 if (!isTry) { 5380 SyncArg = 5381 CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr()); 5382 SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy); 5383 CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg); 5384 } 5385 5386 // Push an EH context entry, used for handling rethrows and jumps 5387 // through finally. 5388 CGF.PushCleanupBlock(FinallyBlock); 5389 5390 CGF.setInvokeDest(TryHandler); 5391 5392 CGF.EmitBlock(TryBlock); 5393 CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody() 5394 : cast<ObjCAtSynchronizedStmt>(S).getSynchBody()); 5395 CGF.EmitBranchThroughCleanup(FinallyEnd); 5396 5397 // Emit the exception handler. 5398 5399 CGF.EmitBlock(TryHandler); 5400 5401 llvm::Value *llvm_eh_exception = 5402 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception); 5403 llvm::Value *llvm_eh_selector_i64 = 5404 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64); 5405 llvm::Value *llvm_eh_typeid_for_i64 = 5406 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64); 5407 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc"); 5408 llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow"); 5409 5410 llvm::SmallVector<llvm::Value*, 8> SelectorArgs; 5411 SelectorArgs.push_back(Exc); 5412 SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr()); 5413 5414 // Construct the lists of (type, catch body) to handle. 5415 llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers; 5416 bool HasCatchAll = false; 5417 if (isTry) { 5418 if (const ObjCAtCatchStmt* CatchStmt = 5419 cast<ObjCAtTryStmt>(S).getCatchStmts()) { 5420 for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) { 5421 const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl(); 5422 Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody())); 5423 5424 // catch(...) always matches. 5425 if (!CatchDecl) { 5426 // Use i8* null here to signal this is a catch all, not a cleanup. 5427 llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); 5428 SelectorArgs.push_back(Null); 5429 HasCatchAll = true; 5430 break; 5431 } 5432 5433 if (CGF.getContext().isObjCIdType(CatchDecl->getType()) || 5434 CatchDecl->getType()->isObjCQualifiedIdType()) { 5435 llvm::Value *IDEHType = 5436 CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id"); 5437 if (!IDEHType) 5438 IDEHType = 5439 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false, 5440 llvm::GlobalValue::ExternalLinkage, 5441 0, "OBJC_EHTYPE_id", &CGM.getModule()); 5442 SelectorArgs.push_back(IDEHType); 5443 HasCatchAll = true; 5444 break; 5445 } 5446 5447 // All other types should be Objective-C interface pointer types. 5448 const PointerType *PT = CatchDecl->getType()->getAsPointerType(); 5449 assert(PT && "Invalid @catch type."); 5450 const ObjCInterfaceType *IT = 5451 PT->getPointeeType()->getAsObjCInterfaceType(); 5452 assert(IT && "Invalid @catch type."); 5453 llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false); 5454 SelectorArgs.push_back(EHType); 5455 } 5456 } 5457 } 5458 5459 // We use a cleanup unless there was already a catch all. 5460 if (!HasCatchAll) { 5461 SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0)); 5462 Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0)); 5463 } 5464 5465 llvm::Value *Selector = 5466 CGF.Builder.CreateCall(llvm_eh_selector_i64, 5467 SelectorArgs.begin(), SelectorArgs.end(), 5468 "selector"); 5469 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) { 5470 const ParmVarDecl *CatchParam = Handlers[i].first; 5471 const Stmt *CatchBody = Handlers[i].second; 5472 5473 llvm::BasicBlock *Next = 0; 5474 5475 // The last handler always matches. 5476 if (i + 1 != e) { 5477 assert(CatchParam && "Only last handler can be a catch all."); 5478 5479 llvm::BasicBlock *Match = CGF.createBasicBlock("match"); 5480 Next = CGF.createBasicBlock("catch.next"); 5481 llvm::Value *Id = 5482 CGF.Builder.CreateCall(llvm_eh_typeid_for_i64, 5483 CGF.Builder.CreateBitCast(SelectorArgs[i+2], 5484 ObjCTypes.Int8PtrTy)); 5485 CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id), 5486 Match, Next); 5487 5488 CGF.EmitBlock(Match); 5489 } 5490 5491 if (CatchBody) { 5492 llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end"); 5493 llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler"); 5494 5495 // Cleanups must call objc_end_catch. 5496 // 5497 // FIXME: It seems incorrect for objc_begin_catch to be inside 5498 // this context, but this matches gcc. 5499 CGF.PushCleanupBlock(MatchEnd); 5500 CGF.setInvokeDest(MatchHandler); 5501 5502 llvm::Value *ExcObject = 5503 CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc); 5504 5505 // Bind the catch parameter if it exists. 5506 if (CatchParam) { 5507 ExcObject = 5508 CGF.Builder.CreateBitCast(ExcObject, 5509 CGF.ConvertType(CatchParam->getType())); 5510 // CatchParam is a ParmVarDecl because of the grammar 5511 // construction used to handle this, but for codegen purposes 5512 // we treat this as a local decl. 5513 CGF.EmitLocalBlockVarDecl(*CatchParam); 5514 CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam)); 5515 } 5516 5517 CGF.ObjCEHValueStack.push_back(ExcObject); 5518 CGF.EmitStmt(CatchBody); 5519 CGF.ObjCEHValueStack.pop_back(); 5520 5521 CGF.EmitBranchThroughCleanup(FinallyEnd); 5522 5523 CGF.EmitBlock(MatchHandler); 5524 5525 llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc"); 5526 // We are required to emit this call to satisfy LLVM, even 5527 // though we don't use the result. 5528 llvm::SmallVector<llvm::Value*, 8> Args; 5529 Args.push_back(Exc); 5530 Args.push_back(ObjCTypes.getEHPersonalityPtr()); 5531 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 5532 0)); 5533 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end()); 5534 CGF.Builder.CreateStore(Exc, RethrowPtr); 5535 CGF.EmitBranchThroughCleanup(FinallyRethrow); 5536 5537 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock(); 5538 5539 CGF.EmitBlock(MatchEnd); 5540 5541 // Unfortunately, we also have to generate another EH frame here 5542 // in case this throws. 5543 llvm::BasicBlock *MatchEndHandler = 5544 CGF.createBasicBlock("match.end.handler"); 5545 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont"); 5546 CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(), 5547 Cont, MatchEndHandler, 5548 Args.begin(), Args.begin()); 5549 5550 CGF.EmitBlock(Cont); 5551 if (Info.SwitchBlock) 5552 CGF.EmitBlock(Info.SwitchBlock); 5553 if (Info.EndBlock) 5554 CGF.EmitBlock(Info.EndBlock); 5555 5556 CGF.EmitBlock(MatchEndHandler); 5557 Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc"); 5558 // We are required to emit this call to satisfy LLVM, even 5559 // though we don't use the result. 5560 Args.clear(); 5561 Args.push_back(Exc); 5562 Args.push_back(ObjCTypes.getEHPersonalityPtr()); 5563 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 5564 0)); 5565 CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end()); 5566 CGF.Builder.CreateStore(Exc, RethrowPtr); 5567 CGF.EmitBranchThroughCleanup(FinallyRethrow); 5568 5569 if (Next) 5570 CGF.EmitBlock(Next); 5571 } else { 5572 assert(!Next && "catchup should be last handler."); 5573 5574 CGF.Builder.CreateStore(Exc, RethrowPtr); 5575 CGF.EmitBranchThroughCleanup(FinallyRethrow); 5576 } 5577 } 5578 5579 // Pop the cleanup entry, the @finally is outside this cleanup 5580 // scope. 5581 CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock(); 5582 CGF.setInvokeDest(PrevLandingPad); 5583 5584 CGF.EmitBlock(FinallyBlock); 5585 5586 if (isTry) { 5587 if (const ObjCAtFinallyStmt* FinallyStmt = 5588 cast<ObjCAtTryStmt>(S).getFinallyStmt()) 5589 CGF.EmitStmt(FinallyStmt->getFinallyBody()); 5590 } else { 5591 // Emit 'objc_sync_exit(expr)' as finally's sole statement for 5592 // @synchronized. 5593 CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg); 5594 } 5595 5596 if (Info.SwitchBlock) 5597 CGF.EmitBlock(Info.SwitchBlock); 5598 if (Info.EndBlock) 5599 CGF.EmitBlock(Info.EndBlock); 5600 5601 // Branch around the rethrow code. 5602 CGF.EmitBranch(FinallyEnd); 5603 5604 CGF.EmitBlock(FinallyRethrow); 5605 CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(), 5606 CGF.Builder.CreateLoad(RethrowPtr)); 5607 CGF.Builder.CreateUnreachable(); 5608 5609 CGF.EmitBlock(FinallyEnd); 5610} 5611 5612/// EmitThrowStmt - Generate code for a throw statement. 5613void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF, 5614 const ObjCAtThrowStmt &S) { 5615 llvm::Value *Exception; 5616 if (const Expr *ThrowExpr = S.getThrowExpr()) { 5617 Exception = CGF.EmitScalarExpr(ThrowExpr); 5618 } else { 5619 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) && 5620 "Unexpected rethrow outside @catch block."); 5621 Exception = CGF.ObjCEHValueStack.back(); 5622 } 5623 5624 llvm::Value *ExceptionAsObject = 5625 CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp"); 5626 llvm::BasicBlock *InvokeDest = CGF.getInvokeDest(); 5627 if (InvokeDest) { 5628 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont"); 5629 CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(), 5630 Cont, InvokeDest, 5631 &ExceptionAsObject, &ExceptionAsObject + 1); 5632 CGF.EmitBlock(Cont); 5633 } else 5634 CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject); 5635 CGF.Builder.CreateUnreachable(); 5636 5637 // Clear the insertion point to indicate we are in unreachable code. 5638 CGF.Builder.ClearInsertionPoint(); 5639} 5640 5641llvm::Value * 5642CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID, 5643 bool ForDefinition) { 5644 llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()]; 5645 5646 // If we don't need a definition, return the entry if found or check 5647 // if we use an external reference. 5648 if (!ForDefinition) { 5649 if (Entry) 5650 return Entry; 5651 5652 // If this type (or a super class) has the __objc_exception__ 5653 // attribute, emit an external reference. 5654 if (hasObjCExceptionAttribute(ID)) 5655 return Entry = 5656 new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false, 5657 llvm::GlobalValue::ExternalLinkage, 5658 0, 5659 (std::string("OBJC_EHTYPE_$_") + 5660 ID->getIdentifier()->getName()), 5661 &CGM.getModule()); 5662 } 5663 5664 // Otherwise we need to either make a new entry or fill in the 5665 // initializer. 5666 assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition"); 5667 std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString()); 5668 std::string VTableName = "objc_ehtype_vtable"; 5669 llvm::GlobalVariable *VTableGV = 5670 CGM.getModule().getGlobalVariable(VTableName); 5671 if (!VTableGV) 5672 VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false, 5673 llvm::GlobalValue::ExternalLinkage, 5674 0, VTableName, &CGM.getModule()); 5675 5676 llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2); 5677 5678 std::vector<llvm::Constant*> Values(3); 5679 Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1); 5680 Values[1] = GetClassName(ID->getIdentifier()); 5681 Values[2] = GetClassGlobal(ClassName); 5682 llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values); 5683 5684 if (Entry) { 5685 Entry->setInitializer(Init); 5686 } else { 5687 Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false, 5688 llvm::GlobalValue::WeakAnyLinkage, 5689 Init, 5690 (std::string("OBJC_EHTYPE_$_") + 5691 ID->getIdentifier()->getName()), 5692 &CGM.getModule()); 5693 } 5694 5695 if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden) 5696 Entry->setVisibility(llvm::GlobalValue::HiddenVisibility); 5697 Entry->setAlignment(8); 5698 5699 if (ForDefinition) { 5700 Entry->setSection("__DATA,__objc_const"); 5701 Entry->setLinkage(llvm::GlobalValue::ExternalLinkage); 5702 } else { 5703 Entry->setSection("__DATA,__datacoal_nt,coalesced"); 5704 } 5705 5706 return Entry; 5707} 5708 5709/* *** */ 5710 5711CodeGen::CGObjCRuntime * 5712CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) { 5713 return new CGObjCMac(CGM); 5714} 5715 5716CodeGen::CGObjCRuntime * 5717CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) { 5718 return new CGObjCNonFragileABIMac(CGM); 5719} 5720