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