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