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