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