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