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