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