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