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