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