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