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