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