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