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