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