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