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