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