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