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