CGObjCMac.cpp revision 058a1b7f9d7d3498783f7d24e73235c4ba7ee851
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  // MethodListnfABITy - LLVM for struct _method_list_t
220  const llvm::StructType *MethodListnfABITy;
221
222  // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
223  const llvm::Type *MethodListnfABIPtrTy;
224
225  // ProtocolnfABITy = LLVM for struct _protocol_t
226  const llvm::StructType *ProtocolnfABITy;
227
228  // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
229  const llvm::StructType *ProtocolListnfABITy;
230
231  // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
232  const llvm::Type *ProtocolListnfABIPtrTy;
233
234  // ClassnfABITy - LLVM for struct _class_t
235  const llvm::StructType *ClassnfABITy;
236
237  // ClassnfABIPtrTy - LLVM for struct _class_t*
238  const llvm::Type *ClassnfABIPtrTy;
239
240  // IvarnfABITy - LLVM for struct _ivar_t
241  const llvm::StructType *IvarnfABITy;
242
243  // IvarListnfABITy - LLVM for struct _ivar_list_t
244  const llvm::StructType *IvarListnfABITy;
245
246  // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
247  const llvm::Type *IvarListnfABIPtrTy;
248
249  // ClassRonfABITy - LLVM for struct _class_ro_t
250  const llvm::StructType *ClassRonfABITy;
251
252  // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
253  const llvm::Type *ImpnfABITy;
254
255  // CategorynfABITy - LLVM for struct _category_t
256  const llvm::StructType *CategorynfABITy;
257
258  ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
259  ~ObjCNonFragileABITypesHelper(){}
260};
261
262class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
263protected:
264  CodeGen::CodeGenModule &CGM;
265  // FIXME! May not be needing this after all.
266  unsigned ObjCABI;
267
268  /// LazySymbols - Symbols to generate a lazy reference for. See
269  /// DefinedSymbols and FinishModule().
270  std::set<IdentifierInfo*> LazySymbols;
271
272  /// DefinedSymbols - External symbols which are defined by this
273  /// module. The symbols in this list and LazySymbols are used to add
274  /// special linker symbols which ensure that Objective-C modules are
275  /// linked properly.
276  std::set<IdentifierInfo*> DefinedSymbols;
277
278  /// ClassNames - uniqued class names.
279  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
280
281  /// MethodVarNames - uniqued method variable names.
282  llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
283
284  /// MethodVarTypes - uniqued method type signatures. We have to use
285  /// a StringMap here because have no other unique reference.
286  llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
287
288  /// MethodDefinitions - map of methods which have been defined in
289  /// this translation unit.
290  llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
291
292  /// PropertyNames - uniqued method variable names.
293  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
294
295  /// ClassReferences - uniqued class references.
296  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
297
298  /// SelectorReferences - uniqued selector references.
299  llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
300
301  /// Protocols - Protocols for which an objc_protocol structure has
302  /// been emitted. Forward declarations are handled by creating an
303  /// empty structure whose initializer is filled in when/if defined.
304  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
305
306  /// DefinedProtocols - Protocols which have actually been
307  /// defined. We should not need this, see FIXME in GenerateProtocol.
308  llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
309
310  /// DefinedClasses - List of defined classes.
311  std::vector<llvm::GlobalValue*> DefinedClasses;
312
313  /// DefinedCategories - List of defined categories.
314  std::vector<llvm::GlobalValue*> DefinedCategories;
315
316  /// UsedGlobals - List of globals to pack into the llvm.used metadata
317  /// to prevent them from being clobbered.
318  std::vector<llvm::GlobalVariable*> UsedGlobals;
319
320  /// GetNameForMethod - Return a name for the given method.
321  /// \param[out] NameOut - The return value.
322  void GetNameForMethod(const ObjCMethodDecl *OMD,
323                        const ObjCContainerDecl *CD,
324                        std::string &NameOut);
325
326  /// GetMethodVarName - Return a unique constant for the given
327  /// selector's name. The return value has type char *.
328  llvm::Constant *GetMethodVarName(Selector Sel);
329  llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
330  llvm::Constant *GetMethodVarName(const std::string &Name);
331
332  /// GetMethodVarType - Return a unique constant for the given
333  /// selector's name. The return value has type char *.
334
335  // FIXME: This is a horrible name.
336  llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
337  llvm::Constant *GetMethodVarType(const std::string &Name);
338
339  /// GetPropertyName - Return a unique constant for the given
340  /// name. The return value has type char *.
341  llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
342
343  // FIXME: This can be dropped once string functions are unified.
344  llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
345                                        const Decl *Container);
346
347  /// GetClassName - Return a unique constant for the given selector's
348  /// name. The return value has type char *.
349  llvm::Constant *GetClassName(IdentifierInfo *Ident);
350
351public:
352  CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
353  { }
354
355  virtual llvm::Constant *GenerateConstantString(const std::string &String);
356};
357
358class CGObjCMac : public CGObjCCommonMac {
359private:
360  ObjCTypesHelper ObjCTypes;
361  /// EmitImageInfo - Emit the image info marker used to encode some module
362  /// level information.
363  void EmitImageInfo();
364
365  /// EmitModuleInfo - Another marker encoding module level
366  /// information.
367  void EmitModuleInfo();
368
369  /// EmitModuleSymols - Emit module symbols, the list of defined
370  /// classes and categories. The result has type SymtabPtrTy.
371  llvm::Constant *EmitModuleSymbols();
372
373  /// FinishModule - Write out global data structures at the end of
374  /// processing a translation unit.
375  void FinishModule();
376
377  /// EmitClassExtension - Generate the class extension structure used
378  /// to store the weak ivar layout and properties. The return value
379  /// has type ClassExtensionPtrTy.
380  llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
381
382  /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
383  /// for the given class.
384  llvm::Value *EmitClassRef(CGBuilderTy &Builder,
385                            const ObjCInterfaceDecl *ID);
386
387  CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
388                                  QualType ResultType,
389                                  Selector Sel,
390                                  llvm::Value *Arg0,
391                                  QualType Arg0Ty,
392                                  bool IsSuper,
393                                  const CallArgList &CallArgs);
394
395  /// EmitIvarList - Emit the ivar list for the given
396  /// implementation. If ForClass is true the list of class ivars
397  /// (i.e. metaclass ivars) is emitted, otherwise the list of
398  /// interface ivars will be emitted. The return value has type
399  /// IvarListPtrTy.
400  llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
401                               bool ForClass,
402                               const llvm::Type *InterfaceTy);
403
404  /// EmitMetaClass - Emit a forward reference to the class structure
405  /// for the metaclass of the given interface. The return value has
406  /// type ClassPtrTy.
407  llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
408
409  /// EmitMetaClass - Emit a class structure for the metaclass of the
410  /// given implementation. The return value has type ClassPtrTy.
411  llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
412                                llvm::Constant *Protocols,
413                                const llvm::Type *InterfaceTy,
414                                const ConstantVector &Methods);
415
416  llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
417
418  llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
419
420  /// EmitMethodList - Emit the method list for the given
421  /// implementation. The return value has type MethodListPtrTy.
422  llvm::Constant *EmitMethodList(const std::string &Name,
423                                 const char *Section,
424                                 const ConstantVector &Methods);
425
426  /// EmitMethodDescList - Emit a method description list for a list of
427  /// method declarations.
428  ///  - TypeName: The name for the type containing the methods.
429  ///  - IsProtocol: True iff these methods are for a protocol.
430  ///  - ClassMethds: True iff these are class methods.
431  ///  - Required: When true, only "required" methods are
432  ///    listed. Similarly, when false only "optional" methods are
433  ///    listed. For classes this should always be true.
434  ///  - begin, end: The method list to output.
435  ///
436  /// The return value has type MethodDescriptionListPtrTy.
437  llvm::Constant *EmitMethodDescList(const std::string &Name,
438                                     const char *Section,
439                                     const ConstantVector &Methods);
440
441  /// EmitPropertyList - Emit the given property list. The return
442  /// value has type PropertyListPtrTy.
443  llvm::Constant *EmitPropertyList(const std::string &Name,
444                                   const Decl *Container,
445                                   const ObjCContainerDecl *OCD);
446
447  /// GetOrEmitProtocol - Get the protocol object for the given
448  /// declaration, emitting it if necessary. The return value has type
449  /// ProtocolPtrTy.
450  llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
451
452  /// GetOrEmitProtocolRef - Get a forward reference to the protocol
453  /// object for the given declaration, emitting it if needed. These
454  /// forward references will be filled in with empty bodies if no
455  /// definition is seen. The return value has type ProtocolPtrTy.
456  llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
457
458  /// EmitProtocolExtension - Generate the protocol extension
459  /// structure used to store optional instance and class methods, and
460  /// protocol properties. The return value has type
461  /// ProtocolExtensionPtrTy.
462  llvm::Constant *
463  EmitProtocolExtension(const ObjCProtocolDecl *PD,
464                        const ConstantVector &OptInstanceMethods,
465                        const ConstantVector &OptClassMethods);
466
467  /// EmitProtocolList - Generate the list of referenced
468  /// protocols. The return value has type ProtocolListPtrTy.
469  llvm::Constant *EmitProtocolList(const std::string &Name,
470                                   ObjCProtocolDecl::protocol_iterator begin,
471                                   ObjCProtocolDecl::protocol_iterator end);
472
473  /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
474  /// for the given selector.
475  llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
476
477  /// GetProtocolRef - Return a reference to the internal protocol
478  /// description, creating an empty one if it has not been
479  /// defined. The return value has type ProtocolPtrTy.
480  llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
481
482public:
483  CGObjCMac(CodeGen::CodeGenModule &cgm);
484
485  virtual llvm::Function *ModuleInitFunction();
486
487  virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
488                                              QualType ResultType,
489                                              Selector Sel,
490                                              llvm::Value *Receiver,
491                                              bool IsClassMessage,
492                                              const CallArgList &CallArgs);
493
494  virtual CodeGen::RValue
495  GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
496                           QualType ResultType,
497                           Selector Sel,
498                           const ObjCInterfaceDecl *Class,
499                           llvm::Value *Receiver,
500                           bool IsClassMessage,
501                           const CallArgList &CallArgs);
502
503  virtual llvm::Value *GetClass(CGBuilderTy &Builder,
504                                const ObjCInterfaceDecl *ID);
505
506  virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
507
508  virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
509                                         const ObjCContainerDecl *CD=0);
510
511  virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
512
513  virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
514
515  virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
516                                           const ObjCProtocolDecl *PD);
517
518  virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
519
520  virtual llvm::Function *GetPropertyGetFunction();
521  virtual llvm::Function *GetPropertySetFunction();
522  virtual llvm::Function *EnumerationMutationFunction();
523
524  virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
525                                         const Stmt &S);
526  virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
527                             const ObjCAtThrowStmt &S);
528  virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
529                                         llvm::Value *AddrWeakObj);
530  virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
531                                  llvm::Value *src, llvm::Value *dst);
532  virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
533                                    llvm::Value *src, llvm::Value *dest);
534  virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
535                                  llvm::Value *src, llvm::Value *dest);
536  virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
537                                        llvm::Value *src, llvm::Value *dest);
538};
539
540class CGObjCNonFragileABIMac : public CGObjCCommonMac {
541private:
542  ObjCNonFragileABITypesHelper ObjCTypes;
543  llvm::GlobalVariable* ObjCEmptyCacheVar;
544  llvm::GlobalVariable* ObjCEmptyVtableVar;
545
546  /// FinishNonFragileABIModule - Write out global data structures at the end of
547  /// processing a translation unit.
548  void FinishNonFragileABIModule();
549
550  llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
551                                unsigned InstanceStart,
552                                unsigned InstanceSize,
553                                const ObjCImplementationDecl *ID);
554  void BuildClassMetaData(std::string &ClassName,
555                          llvm::Constant *IsAGV, llvm::Constant *SuperClassGV,
556                          llvm::Constant *ClassRoGV);
557
558
559
560public:
561  CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
562  // FIXME. All stubs for now!
563  virtual llvm::Function *ModuleInitFunction();
564
565  virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
566                                              QualType ResultType,
567                                              Selector Sel,
568                                              llvm::Value *Receiver,
569                                              bool IsClassMessage,
570                                              const CallArgList &CallArgs)
571    {return RValue::get(0);}
572
573  virtual CodeGen::RValue
574  GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
575                           QualType ResultType,
576                           Selector Sel,
577                           const ObjCInterfaceDecl *Class,
578                           llvm::Value *Receiver,
579                           bool IsClassMessage,
580                           const CallArgList &CallArgs){ return RValue::get(0);}
581
582  virtual llvm::Value *GetClass(CGBuilderTy &Builder,
583                                const ObjCInterfaceDecl *ID){ return 0; }
584
585  virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
586    { return 0; }
587
588  virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
589                                         const ObjCContainerDecl *CD=0)
590    { return 0; }
591
592  virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD)
593  { return; }
594
595  virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
596
597  virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
598                                           const ObjCProtocolDecl *PD)
599    { return 0; }
600
601  virtual void GenerateProtocol(const ObjCProtocolDecl *PD){ return; }
602
603  virtual llvm::Function *GetPropertyGetFunction(){ return 0; }
604  virtual llvm::Function *GetPropertySetFunction()
605    { return 0; }
606  virtual llvm::Function *EnumerationMutationFunction()
607    { return 0; }
608
609  virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
610                                         const Stmt &S)
611    { return; }
612  virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
613                             const ObjCAtThrowStmt &S)
614    { return; }
615  virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
616                                         llvm::Value *AddrWeakObj)
617    { return 0; }
618  virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
619                                  llvm::Value *src, llvm::Value *dst)
620    { return; }
621  virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
622                                    llvm::Value *src, llvm::Value *dest)
623    { return; }
624  virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
625                                  llvm::Value *src, llvm::Value *dest)
626  { return; }
627  virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
628                                        llvm::Value *src, llvm::Value *dest)
629    { return; }
630};
631
632} // end anonymous namespace
633
634/* *** Helper Functions *** */
635
636/// getConstantGEP() - Help routine to construct simple GEPs.
637static llvm::Constant *getConstantGEP(llvm::Constant *C,
638                                      unsigned idx0,
639                                      unsigned idx1) {
640  llvm::Value *Idxs[] = {
641    llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
642    llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
643  };
644  return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
645}
646
647/* *** CGObjCMac Public Interface *** */
648
649CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
650                                                    ObjCTypes(cgm)
651{
652  ObjCABI = 1;
653  EmitImageInfo();
654}
655
656/// GetClass - Return a reference to the class for the given interface
657/// decl.
658llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
659                                 const ObjCInterfaceDecl *ID) {
660  return EmitClassRef(Builder, ID);
661}
662
663/// GetSelector - Return the pointer to the unique'd string for this selector.
664llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
665  return EmitSelector(Builder, Sel);
666}
667
668/// Generate a constant CFString object.
669/*
670   struct __builtin_CFString {
671     const int *isa; // point to __CFConstantStringClassReference
672     int flags;
673     const char *str;
674     long length;
675   };
676*/
677
678llvm::Constant *CGObjCCommonMac::GenerateConstantString(
679                                                  const std::string &String) {
680  return CGM.GetAddrOfConstantCFString(String);
681}
682
683/// Generates a message send where the super is the receiver.  This is
684/// a message send to self with special delivery semantics indicating
685/// which class's method should be called.
686CodeGen::RValue
687CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
688                                    QualType ResultType,
689                                    Selector Sel,
690                                    const ObjCInterfaceDecl *Class,
691                                    llvm::Value *Receiver,
692                                    bool IsClassMessage,
693                                    const CodeGen::CallArgList &CallArgs) {
694  // Create and init a super structure; this is a (receiver, class)
695  // pair we will pass to objc_msgSendSuper.
696  llvm::Value *ObjCSuper =
697    CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
698  llvm::Value *ReceiverAsObject =
699    CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
700  CGF.Builder.CreateStore(ReceiverAsObject,
701                          CGF.Builder.CreateStructGEP(ObjCSuper, 0));
702
703  // If this is a class message the metaclass is passed as the target.
704  llvm::Value *Target;
705  if (IsClassMessage) {
706    llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
707    llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
708    llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
709    Target = Super;
710  } else {
711    Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
712  }
713  // FIXME: We shouldn't need to do this cast, rectify the ASTContext
714  // and ObjCTypes types.
715  const llvm::Type *ClassTy =
716    CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
717  Target = CGF.Builder.CreateBitCast(Target, ClassTy);
718  CGF.Builder.CreateStore(Target,
719                          CGF.Builder.CreateStructGEP(ObjCSuper, 1));
720
721  return EmitMessageSend(CGF, ResultType, Sel,
722                         ObjCSuper, ObjCTypes.SuperPtrCTy,
723                         true, CallArgs);
724}
725
726/// Generate code for a message send expression.
727CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
728                                               QualType ResultType,
729                                               Selector Sel,
730                                               llvm::Value *Receiver,
731                                               bool IsClassMessage,
732                                               const CallArgList &CallArgs) {
733  llvm::Value *Arg0 =
734    CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
735  return EmitMessageSend(CGF, ResultType, Sel,
736                         Arg0, CGF.getContext().getObjCIdType(),
737                         false, CallArgs);
738}
739
740CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
741                                           QualType ResultType,
742                                           Selector Sel,
743                                           llvm::Value *Arg0,
744                                           QualType Arg0Ty,
745                                           bool IsSuper,
746                                           const CallArgList &CallArgs) {
747  CallArgList ActualArgs;
748  ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
749  ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
750                                                               Sel)),
751                                      CGF.getContext().getObjCSelType()));
752  ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
753
754  const llvm::FunctionType *FTy =
755    CGM.getTypes().GetFunctionType(CGCallInfo(ResultType, ActualArgs),
756                                   false);
757
758  llvm::Constant *Fn;
759  if (CGM.ReturnTypeUsesSret(ResultType)) {
760    Fn = ObjCTypes.getSendStretFn(IsSuper);
761  } else if (ResultType->isFloatingType()) {
762    // FIXME: Sadly, this is wrong. This actually depends on the
763    // architecture. This happens to be right for x86-32 though.
764    Fn = ObjCTypes.getSendFpretFn(IsSuper);
765  } else {
766    Fn = ObjCTypes.getSendFn(IsSuper);
767  }
768  Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
769  return CGF.EmitCall(Fn, ResultType, ActualArgs);
770}
771
772llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
773                                            const ObjCProtocolDecl *PD) {
774  // FIXME: I don't understand why gcc generates this, or where it is
775  // resolved. Investigate. Its also wasteful to look this up over and
776  // over.
777  LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
778
779  return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
780                                        ObjCTypes.ExternalProtocolPtrTy);
781}
782
783void CGObjCMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
784  // FIXME: We shouldn't need this, the protocol decl should contain
785  // enough information to tell us whether this was a declaration or a
786  // definition.
787  DefinedProtocols.insert(PD->getIdentifier());
788
789  // If we have generated a forward reference to this protocol, emit
790  // it now. Otherwise do nothing, the protocol objects are lazily
791  // emitted.
792  if (Protocols.count(PD->getIdentifier()))
793    GetOrEmitProtocol(PD);
794}
795
796llvm::Constant *CGObjCMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
797  if (DefinedProtocols.count(PD->getIdentifier()))
798    return GetOrEmitProtocol(PD);
799  return GetOrEmitProtocolRef(PD);
800}
801
802/*
803     // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
804  struct _objc_protocol {
805    struct _objc_protocol_extension *isa;
806    char *protocol_name;
807    struct _objc_protocol_list *protocol_list;
808    struct _objc__method_prototype_list *instance_methods;
809    struct _objc__method_prototype_list *class_methods
810  };
811
812  See EmitProtocolExtension().
813*/
814llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
815  llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
816
817  // Early exit if a defining object has already been generated.
818  if (Entry && Entry->hasInitializer())
819    return Entry;
820
821  // FIXME: I don't understand why gcc generates this, or where it is
822  // resolved. Investigate. Its also wasteful to look this up over and
823  // over.
824  LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
825
826  const char *ProtocolName = PD->getNameAsCString();
827
828  // Construct method lists.
829  std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
830  std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
831  for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
832         e = PD->instmeth_end(); i != e; ++i) {
833    ObjCMethodDecl *MD = *i;
834    llvm::Constant *C = GetMethodDescriptionConstant(MD);
835    if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
836      OptInstanceMethods.push_back(C);
837    } else {
838      InstanceMethods.push_back(C);
839    }
840  }
841
842  for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
843         e = PD->classmeth_end(); i != e; ++i) {
844    ObjCMethodDecl *MD = *i;
845    llvm::Constant *C = GetMethodDescriptionConstant(MD);
846    if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
847      OptClassMethods.push_back(C);
848    } else {
849      ClassMethods.push_back(C);
850    }
851  }
852
853  std::vector<llvm::Constant*> Values(5);
854  Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
855  Values[1] = GetClassName(PD->getIdentifier());
856  Values[2] =
857    EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
858                     PD->protocol_begin(),
859                     PD->protocol_end());
860  Values[3] =
861    EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
862                          + PD->getNameAsString(),
863                       "__OBJC,__cat_inst_meth,regular,no_dead_strip",
864                       InstanceMethods);
865  Values[4] =
866    EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
867                            + PD->getNameAsString(),
868                       "__OBJC,__cat_cls_meth,regular,no_dead_strip",
869                       ClassMethods);
870  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
871                                                   Values);
872
873  if (Entry) {
874    // Already created, fix the linkage and update the initializer.
875    Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
876    Entry->setInitializer(Init);
877  } else {
878    Entry =
879      new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
880                               llvm::GlobalValue::InternalLinkage,
881                               Init,
882                               std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
883                               &CGM.getModule());
884    Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
885    UsedGlobals.push_back(Entry);
886    // FIXME: Is this necessary? Why only for protocol?
887    Entry->setAlignment(4);
888  }
889
890  return Entry;
891}
892
893llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
894  llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
895
896  if (!Entry) {
897    // We use the initializer as a marker of whether this is a forward
898    // reference or not. At module finalization we add the empty
899    // contents for protocols which were referenced but never defined.
900    Entry =
901      new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
902                               llvm::GlobalValue::ExternalLinkage,
903                               0,
904                               "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
905                               &CGM.getModule());
906    Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
907    UsedGlobals.push_back(Entry);
908    // FIXME: Is this necessary? Why only for protocol?
909    Entry->setAlignment(4);
910  }
911
912  return Entry;
913}
914
915/*
916  struct _objc_protocol_extension {
917    uint32_t size;
918    struct objc_method_description_list *optional_instance_methods;
919    struct objc_method_description_list *optional_class_methods;
920    struct objc_property_list *instance_properties;
921  };
922*/
923llvm::Constant *
924CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
925                                 const ConstantVector &OptInstanceMethods,
926                                 const ConstantVector &OptClassMethods) {
927  uint64_t Size =
928    CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
929  std::vector<llvm::Constant*> Values(4);
930  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
931  Values[1] =
932    EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
933                           + PD->getNameAsString(),
934                       "__OBJC,__cat_inst_meth,regular,no_dead_strip",
935                       OptInstanceMethods);
936  Values[2] =
937    EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
938                          + PD->getNameAsString(),
939                       "__OBJC,__cat_cls_meth,regular,no_dead_strip",
940                       OptClassMethods);
941  Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
942                                   PD->getNameAsString(),
943                               0, PD);
944
945  // Return null if no extension bits are used.
946  if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
947      Values[3]->isNullValue())
948    return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
949
950  llvm::Constant *Init =
951    llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
952  llvm::GlobalVariable *GV =
953      new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false,
954                               llvm::GlobalValue::InternalLinkage,
955                               Init,
956                               "\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
957                               &CGM.getModule());
958  // No special section, but goes in llvm.used
959  UsedGlobals.push_back(GV);
960
961  return GV;
962}
963
964/*
965  struct objc_protocol_list {
966    struct objc_protocol_list *next;
967    long count;
968    Protocol *list[];
969  };
970*/
971llvm::Constant *
972CGObjCMac::EmitProtocolList(const std::string &Name,
973                            ObjCProtocolDecl::protocol_iterator begin,
974                            ObjCProtocolDecl::protocol_iterator end) {
975  std::vector<llvm::Constant*> ProtocolRefs;
976
977  for (; begin != end; ++begin)
978    ProtocolRefs.push_back(GetProtocolRef(*begin));
979
980  // Just return null for empty protocol lists
981  if (ProtocolRefs.empty())
982    return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
983
984  // This list is null terminated.
985  ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
986
987  std::vector<llvm::Constant*> Values(3);
988  // This field is only used by the runtime.
989  Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
990  Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
991  Values[2] =
992    llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
993                                                  ProtocolRefs.size()),
994                             ProtocolRefs);
995
996  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
997  llvm::GlobalVariable *GV =
998    new llvm::GlobalVariable(Init->getType(), false,
999                             llvm::GlobalValue::InternalLinkage,
1000                             Init,
1001                             Name,
1002                             &CGM.getModule());
1003  GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip");
1004  return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1005}
1006
1007/*
1008  struct _objc_property {
1009    const char * const name;
1010    const char * const attributes;
1011  };
1012
1013  struct _objc_property_list {
1014    uint32_t entsize; // sizeof (struct _objc_property)
1015    uint32_t prop_count;
1016    struct _objc_property[prop_count];
1017  };
1018*/
1019llvm::Constant *CGObjCMac::EmitPropertyList(const std::string &Name,
1020                                            const Decl *Container,
1021                                            const ObjCContainerDecl *OCD) {
1022  std::vector<llvm::Constant*> Properties, Prop(2);
1023  for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(),
1024       E = OCD->prop_end(); I != E; ++I) {
1025    const ObjCPropertyDecl *PD = *I;
1026    Prop[0] = GetPropertyName(PD->getIdentifier());
1027    Prop[1] = GetPropertyTypeString(PD, Container);
1028    Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1029                                                   Prop));
1030  }
1031
1032  // Return null for empty list.
1033  if (Properties.empty())
1034    return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1035
1036  unsigned PropertySize =
1037    CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
1038  std::vector<llvm::Constant*> Values(3);
1039  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1040  Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1041  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1042                                             Properties.size());
1043  Values[2] = llvm::ConstantArray::get(AT, Properties);
1044  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1045
1046  llvm::GlobalVariable *GV =
1047    new llvm::GlobalVariable(Init->getType(), false,
1048                             llvm::GlobalValue::InternalLinkage,
1049                             Init,
1050                             Name,
1051                             &CGM.getModule());
1052  // No special section on property lists?
1053  UsedGlobals.push_back(GV);
1054  return llvm::ConstantExpr::getBitCast(GV,
1055                                        ObjCTypes.PropertyListPtrTy);
1056
1057}
1058
1059/*
1060  struct objc_method_description_list {
1061    int count;
1062    struct objc_method_description list[];
1063  };
1064*/
1065llvm::Constant *
1066CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1067  std::vector<llvm::Constant*> Desc(2);
1068  Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1069                                           ObjCTypes.SelectorPtrTy);
1070  Desc[1] = GetMethodVarType(MD);
1071  return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1072                                   Desc);
1073}
1074
1075llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1076                                              const char *Section,
1077                                              const ConstantVector &Methods) {
1078  // Return null for empty list.
1079  if (Methods.empty())
1080    return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1081
1082  std::vector<llvm::Constant*> Values(2);
1083  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1084  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1085                                             Methods.size());
1086  Values[1] = llvm::ConstantArray::get(AT, Methods);
1087  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1088
1089  llvm::GlobalVariable *GV =
1090    new llvm::GlobalVariable(Init->getType(), false,
1091                             llvm::GlobalValue::InternalLinkage,
1092                             Init, Name, &CGM.getModule());
1093  GV->setSection(Section);
1094  UsedGlobals.push_back(GV);
1095  return llvm::ConstantExpr::getBitCast(GV,
1096                                        ObjCTypes.MethodDescriptionListPtrTy);
1097}
1098
1099/*
1100  struct _objc_category {
1101    char *category_name;
1102    char *class_name;
1103    struct _objc_method_list *instance_methods;
1104    struct _objc_method_list *class_methods;
1105    struct _objc_protocol_list *protocols;
1106    uint32_t size; // <rdar://4585769>
1107    struct _objc_property_list *instance_properties;
1108  };
1109 */
1110void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
1111  unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
1112
1113  // FIXME: This is poor design, the OCD should have a pointer to the
1114  // category decl. Additionally, note that Category can be null for
1115  // the @implementation w/o an @interface case. Sema should just
1116  // create one for us as it does for @implementation so everyone else
1117  // can live life under a clear blue sky.
1118  const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
1119  const ObjCCategoryDecl *Category =
1120    Interface->FindCategoryDeclaration(OCD->getIdentifier());
1121  std::string ExtName(Interface->getNameAsString() + "_" +
1122                      OCD->getNameAsString());
1123
1124  std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1125  for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
1126         e = OCD->instmeth_end(); i != e; ++i) {
1127    // Instance methods should always be defined.
1128    InstanceMethods.push_back(GetMethodConstant(*i));
1129  }
1130  for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
1131         e = OCD->classmeth_end(); i != e; ++i) {
1132    // Class methods should always be defined.
1133    ClassMethods.push_back(GetMethodConstant(*i));
1134  }
1135
1136  std::vector<llvm::Constant*> Values(7);
1137  Values[0] = GetClassName(OCD->getIdentifier());
1138  Values[1] = GetClassName(Interface->getIdentifier());
1139  Values[2] =
1140    EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1141                   ExtName,
1142                   "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1143                   InstanceMethods);
1144  Values[3] =
1145    EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
1146                   "__OBJC,__cat_class_meth,regular,no_dead_strip",
1147                   ClassMethods);
1148  if (Category) {
1149    Values[4] =
1150      EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1151                       Category->protocol_begin(),
1152                       Category->protocol_end());
1153  } else {
1154    Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1155  }
1156  Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
1157
1158  // If there is no category @interface then there can be no properties.
1159  if (Category) {
1160    Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
1161                                 OCD, Category);
1162  } else {
1163    Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1164  }
1165
1166  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1167                                                   Values);
1168
1169  llvm::GlobalVariable *GV =
1170    new llvm::GlobalVariable(ObjCTypes.CategoryTy, false,
1171                             llvm::GlobalValue::InternalLinkage,
1172                             Init,
1173                             std::string("\01L_OBJC_CATEGORY_")+ExtName,
1174                             &CGM.getModule());
1175  GV->setSection("__OBJC,__category,regular,no_dead_strip");
1176  UsedGlobals.push_back(GV);
1177  DefinedCategories.push_back(GV);
1178}
1179
1180// FIXME: Get from somewhere?
1181enum ClassFlags {
1182  eClassFlags_Factory              = 0x00001,
1183  eClassFlags_Meta                 = 0x00002,
1184  // <rdr://5142207>
1185  eClassFlags_HasCXXStructors      = 0x02000,
1186  eClassFlags_Hidden               = 0x20000,
1187  eClassFlags_ABI2_Hidden          = 0x00010,
1188  eClassFlags_ABI2_HasCXXStructors = 0x00004   // <rdr://4923634>
1189};
1190
1191// <rdr://5142207&4705298&4843145>
1192static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1193  if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1194    // FIXME: Support -fvisibility
1195    switch (attr->getVisibility()) {
1196    default:
1197      assert(0 && "Unknown visibility");
1198      return false;
1199    case VisibilityAttr::DefaultVisibility:
1200    case VisibilityAttr::ProtectedVisibility:  // FIXME: What do we do here?
1201      return false;
1202    case VisibilityAttr::HiddenVisibility:
1203      return true;
1204    }
1205  } else {
1206    return false; // FIXME: Support -fvisibility
1207  }
1208}
1209
1210/*
1211  struct _objc_class {
1212    Class isa;
1213    Class super_class;
1214    const char *name;
1215    long version;
1216    long info;
1217    long instance_size;
1218    struct _objc_ivar_list *ivars;
1219    struct _objc_method_list *methods;
1220    struct _objc_cache *cache;
1221    struct _objc_protocol_list *protocols;
1222    // Objective-C 1.0 extensions (<rdr://4585769>)
1223    const char *ivar_layout;
1224    struct _objc_class_ext *ext;
1225  };
1226
1227  See EmitClassExtension();
1228 */
1229void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
1230  DefinedSymbols.insert(ID->getIdentifier());
1231
1232  std::string ClassName = ID->getNameAsString();
1233  // FIXME: Gross
1234  ObjCInterfaceDecl *Interface =
1235    const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
1236  llvm::Constant *Protocols =
1237    EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
1238                     Interface->protocol_begin(),
1239                     Interface->protocol_end());
1240  const llvm::Type *InterfaceTy =
1241   CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
1242  unsigned Flags = eClassFlags_Factory;
1243  unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
1244
1245  // FIXME: Set CXX-structors flag.
1246  if (IsClassHidden(ID->getClassInterface()))
1247    Flags |= eClassFlags_Hidden;
1248
1249  std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1250  for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1251         e = ID->instmeth_end(); i != e; ++i) {
1252    // Instance methods should always be defined.
1253    InstanceMethods.push_back(GetMethodConstant(*i));
1254  }
1255  for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1256         e = ID->classmeth_end(); i != e; ++i) {
1257    // Class methods should always be defined.
1258    ClassMethods.push_back(GetMethodConstant(*i));
1259  }
1260
1261  for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1262         e = ID->propimpl_end(); i != e; ++i) {
1263    ObjCPropertyImplDecl *PID = *i;
1264
1265    if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1266      ObjCPropertyDecl *PD = PID->getPropertyDecl();
1267
1268      if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1269        if (llvm::Constant *C = GetMethodConstant(MD))
1270          InstanceMethods.push_back(C);
1271      if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1272        if (llvm::Constant *C = GetMethodConstant(MD))
1273          InstanceMethods.push_back(C);
1274    }
1275  }
1276
1277  std::vector<llvm::Constant*> Values(12);
1278  Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
1279  if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
1280    // Record a reference to the super class.
1281    LazySymbols.insert(Super->getIdentifier());
1282
1283    Values[ 1] =
1284      llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1285                                     ObjCTypes.ClassPtrTy);
1286  } else {
1287    Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1288  }
1289  Values[ 2] = GetClassName(ID->getIdentifier());
1290  // Version is always 0.
1291  Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1292  Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1293  Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1294  Values[ 6] = EmitIvarList(ID, false, InterfaceTy);
1295  Values[ 7] =
1296    EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
1297                   "__OBJC,__inst_meth,regular,no_dead_strip",
1298                   InstanceMethods);
1299  // cache is always NULL.
1300  Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1301  Values[ 9] = Protocols;
1302  // FIXME: Set ivar_layout
1303  Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1304  Values[11] = EmitClassExtension(ID);
1305  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1306                                                   Values);
1307
1308  llvm::GlobalVariable *GV =
1309    new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1310                             llvm::GlobalValue::InternalLinkage,
1311                             Init,
1312                             std::string("\01L_OBJC_CLASS_")+ClassName,
1313                             &CGM.getModule());
1314  GV->setSection("__OBJC,__class,regular,no_dead_strip");
1315  UsedGlobals.push_back(GV);
1316  // FIXME: Why?
1317  GV->setAlignment(32);
1318  DefinedClasses.push_back(GV);
1319}
1320
1321llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1322                                         llvm::Constant *Protocols,
1323                                         const llvm::Type *InterfaceTy,
1324                                         const ConstantVector &Methods) {
1325  unsigned Flags = eClassFlags_Meta;
1326  unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
1327
1328  if (IsClassHidden(ID->getClassInterface()))
1329    Flags |= eClassFlags_Hidden;
1330
1331  std::vector<llvm::Constant*> Values(12);
1332  // The isa for the metaclass is the root of the hierarchy.
1333  const ObjCInterfaceDecl *Root = ID->getClassInterface();
1334  while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1335    Root = Super;
1336  Values[ 0] =
1337    llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1338                                   ObjCTypes.ClassPtrTy);
1339  // The super class for the metaclass is emitted as the name of the
1340  // super class. The runtime fixes this up to point to the
1341  // *metaclass* for the super class.
1342  if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1343    Values[ 1] =
1344      llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1345                                     ObjCTypes.ClassPtrTy);
1346  } else {
1347    Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1348  }
1349  Values[ 2] = GetClassName(ID->getIdentifier());
1350  // Version is always 0.
1351  Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1352  Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1353  Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1354  Values[ 6] = EmitIvarList(ID, true, InterfaceTy);
1355  Values[ 7] =
1356    EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
1357                   "__OBJC,__inst_meth,regular,no_dead_strip",
1358                   Methods);
1359  // cache is always NULL.
1360  Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1361  Values[ 9] = Protocols;
1362  // ivar_layout for metaclass is always NULL.
1363  Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1364  // The class extension is always unused for metaclasses.
1365  Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1366  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1367                                                   Values);
1368
1369  std::string Name("\01L_OBJC_METACLASS_");
1370  Name += ID->getNameAsCString();
1371
1372  // Check for a forward reference.
1373  llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1374  if (GV) {
1375    assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1376           "Forward metaclass reference has incorrect type.");
1377    GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1378    GV->setInitializer(Init);
1379  } else {
1380    GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1381                                  llvm::GlobalValue::InternalLinkage,
1382                                  Init, Name,
1383                                  &CGM.getModule());
1384  }
1385  GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
1386  UsedGlobals.push_back(GV);
1387  // FIXME: Why?
1388  GV->setAlignment(32);
1389
1390  return GV;
1391}
1392
1393llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
1394  std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
1395
1396  // FIXME: Should we look these up somewhere other than the
1397  // module. Its a bit silly since we only generate these while
1398  // processing an implementation, so exactly one pointer would work
1399  // if know when we entered/exitted an implementation block.
1400
1401  // Check for an existing forward reference.
1402  // Previously, metaclass with internal linkage may have been defined.
1403  // pass 'true' as 2nd argument so it is returned.
1404  if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
1405    assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1406           "Forward metaclass reference has incorrect type.");
1407    return GV;
1408  } else {
1409    // Generate as an external reference to keep a consistent
1410    // module. This will be patched up when we emit the metaclass.
1411    return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1412                                    llvm::GlobalValue::ExternalLinkage,
1413                                    0,
1414                                    Name,
1415                                    &CGM.getModule());
1416  }
1417}
1418
1419/*
1420  struct objc_class_ext {
1421    uint32_t size;
1422    const char *weak_ivar_layout;
1423    struct _objc_property_list *properties;
1424  };
1425*/
1426llvm::Constant *
1427CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1428  uint64_t Size =
1429    CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
1430
1431  std::vector<llvm::Constant*> Values(3);
1432  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
1433  // FIXME: Output weak_ivar_layout string.
1434  Values[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1435  Values[2] = EmitPropertyList("\01L_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
1436                               ID, ID->getClassInterface());
1437
1438  // Return null if no extension bits are used.
1439  if (Values[1]->isNullValue() && Values[2]->isNullValue())
1440    return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1441
1442  llvm::Constant *Init =
1443    llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
1444  llvm::GlobalVariable *GV =
1445    new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false,
1446                             llvm::GlobalValue::InternalLinkage,
1447                             Init,
1448                             "\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
1449                             &CGM.getModule());
1450  // No special section, but goes in llvm.used
1451  UsedGlobals.push_back(GV);
1452
1453  return GV;
1454}
1455
1456/// countInheritedIvars - count number of ivars in class and its super class(s)
1457///
1458static int countInheritedIvars(const ObjCInterfaceDecl *OI) {
1459  int count = 0;
1460  if (!OI)
1461    return 0;
1462  const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
1463  if (SuperClass)
1464    count += countInheritedIvars(SuperClass);
1465  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1466       E = OI->ivar_end(); I != E; ++I)
1467    ++count;
1468  return count;
1469}
1470
1471/*
1472  struct objc_ivar {
1473    char *ivar_name;
1474    char *ivar_type;
1475    int ivar_offset;
1476  };
1477
1478  struct objc_ivar_list {
1479    int ivar_count;
1480    struct objc_ivar list[count];
1481  };
1482 */
1483llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
1484                                        bool ForClass,
1485                                        const llvm::Type *InterfaceTy) {
1486  std::vector<llvm::Constant*> Ivars, Ivar(3);
1487
1488  // When emitting the root class GCC emits ivar entries for the
1489  // actual class structure. It is not clear if we need to follow this
1490  // behavior; for now lets try and get away with not doing it. If so,
1491  // the cleanest solution would be to make up an ObjCInterfaceDecl
1492  // for the class.
1493  if (ForClass)
1494    return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1495
1496  const llvm::StructLayout *Layout =
1497    CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
1498  ObjCInterfaceDecl *OID =
1499    const_cast<ObjCInterfaceDecl *>(ID->getClassInterface());
1500  int countSuperClassIvars = countInheritedIvars(OID->getSuperClass());
1501  const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
1502  RecordDecl::field_iterator ifield = RD->field_begin();
1503  while (countSuperClassIvars-- > 0)
1504    ++ifield;
1505  for (RecordDecl::field_iterator e = RD->field_end(); ifield != e; ++ifield) {
1506    FieldDecl *Field = *ifield;
1507    unsigned Offset = Layout->getElementOffset(CGM.getTypes().
1508                                               getLLVMFieldNo(Field));
1509    if (Field->getIdentifier())
1510      Ivar[0] = GetMethodVarName(Field->getIdentifier());
1511    else
1512      Ivar[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1513    std::string TypeStr;
1514    CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
1515    Ivar[1] = GetMethodVarType(TypeStr);
1516    Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
1517    Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
1518  }
1519
1520  // Return null for empty list.
1521  if (Ivars.empty())
1522    return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1523
1524  std::vector<llvm::Constant*> Values(2);
1525  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1526  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1527                                             Ivars.size());
1528  Values[1] = llvm::ConstantArray::get(AT, Ivars);
1529  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1530
1531  const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
1532                        "\01L_OBJC_INSTANCE_VARIABLES_");
1533  llvm::GlobalVariable *GV =
1534    new llvm::GlobalVariable(Init->getType(), false,
1535                             llvm::GlobalValue::InternalLinkage,
1536                             Init,
1537                             Prefix + ID->getNameAsString(),
1538                             &CGM.getModule());
1539  if (ForClass) {
1540    GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
1541    // FIXME: Why is this only here?
1542    GV->setAlignment(32);
1543  } else {
1544    GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
1545  }
1546  UsedGlobals.push_back(GV);
1547  return llvm::ConstantExpr::getBitCast(GV,
1548                                        ObjCTypes.IvarListPtrTy);
1549}
1550
1551/*
1552  struct objc_method {
1553    SEL method_name;
1554    char *method_types;
1555    void *method;
1556  };
1557
1558  struct objc_method_list {
1559    struct objc_method_list *obsolete;
1560    int count;
1561    struct objc_method methods_list[count];
1562  };
1563*/
1564
1565/// GetMethodConstant - Return a struct objc_method constant for the
1566/// given method if it has been defined. The result is null if the
1567/// method has not been defined. The return value has type MethodPtrTy.
1568llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
1569  // FIXME: Use DenseMap::lookup
1570  llvm::Function *Fn = MethodDefinitions[MD];
1571  if (!Fn)
1572    return 0;
1573
1574  std::vector<llvm::Constant*> Method(3);
1575  Method[0] =
1576    llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1577                                   ObjCTypes.SelectorPtrTy);
1578  Method[1] = GetMethodVarType(MD);
1579  Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1580  return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1581}
1582
1583llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1584                                          const char *Section,
1585                                          const ConstantVector &Methods) {
1586  // Return null for empty list.
1587  if (Methods.empty())
1588    return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1589
1590  std::vector<llvm::Constant*> Values(3);
1591  Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1592  Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1593  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1594                                             Methods.size());
1595  Values[2] = llvm::ConstantArray::get(AT, Methods);
1596  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1597
1598  llvm::GlobalVariable *GV =
1599    new llvm::GlobalVariable(Init->getType(), false,
1600                             llvm::GlobalValue::InternalLinkage,
1601                             Init,
1602                             Name,
1603                             &CGM.getModule());
1604  GV->setSection(Section);
1605  UsedGlobals.push_back(GV);
1606  return llvm::ConstantExpr::getBitCast(GV,
1607                                        ObjCTypes.MethodListPtrTy);
1608}
1609
1610llvm::Function *CGObjCMac::GenerateMethod(const ObjCMethodDecl *OMD,
1611                                          const ObjCContainerDecl *CD) {
1612  std::string Name;
1613  GetNameForMethod(OMD, CD, Name);
1614
1615  const llvm::FunctionType *MethodTy =
1616    CGM.getTypes().GetFunctionType(CGFunctionInfo(OMD, CGM.getContext()));
1617  llvm::Function *Method =
1618    llvm::Function::Create(MethodTy,
1619                           llvm::GlobalValue::InternalLinkage,
1620                           Name,
1621                           &CGM.getModule());
1622  MethodDefinitions.insert(std::make_pair(OMD, Method));
1623
1624  return Method;
1625}
1626
1627llvm::Function *CGObjCMac::ModuleInitFunction() {
1628  // Abuse this interface function as a place to finalize.
1629  FinishModule();
1630
1631  return NULL;
1632}
1633
1634llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1635  return ObjCTypes.GetPropertyFn;
1636}
1637
1638llvm::Function *CGObjCMac::GetPropertySetFunction() {
1639  return ObjCTypes.SetPropertyFn;
1640}
1641
1642llvm::Function *CGObjCMac::EnumerationMutationFunction()
1643{
1644  return ObjCTypes.EnumerationMutationFn;
1645}
1646
1647/*
1648
1649Objective-C setjmp-longjmp (sjlj) Exception Handling
1650--
1651
1652The basic framework for a @try-catch-finally is as follows:
1653{
1654  objc_exception_data d;
1655  id _rethrow = null;
1656
1657  objc_exception_try_enter(&d);
1658  if (!setjmp(d.jmp_buf)) {
1659    ... try body ...
1660  } else {
1661    // exception path
1662    id _caught = objc_exception_extract(&d);
1663
1664    // enter new try scope for handlers
1665    if (!setjmp(d.jmp_buf)) {
1666      ... match exception and execute catch blocks ...
1667
1668      // fell off end, rethrow.
1669      _rethrow = _caught;
1670      ... jump-through-finally to finally_rethrow ...
1671    } else {
1672      // exception in catch block
1673      _rethrow = objc_exception_extract(&d);
1674      ... jump-through-finally_no_exit to finally_rethrow ...
1675    }
1676  }
1677  ... jump-through-finally to finally_end ...
1678
1679finally:
1680  // match either the initial try_enter or the catch try_enter,
1681  // depending on the path followed.
1682  objc_exception_try_exit(&d);
1683finally_no_exit:
1684  ... finally block ....
1685  ... dispatch to finally destination ...
1686
1687finally_rethrow:
1688  objc_exception_throw(_rethrow);
1689
1690finally_end:
1691}
1692
1693This framework differs slightly from the one gcc uses, in that gcc
1694uses _rethrow to determine if objc_exception_try_exit should be called
1695and if the object should be rethrown. This breaks in the face of
1696throwing nil and introduces unnecessary branches.
1697
1698We specialize this framework for a few particular circumstances:
1699
1700 - If there are no catch blocks, then we avoid emitting the second
1701   exception handling context.
1702
1703 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1704   e)) we avoid emitting the code to rethrow an uncaught exception.
1705
1706 - FIXME: If there is no @finally block we can do a few more
1707   simplifications.
1708
1709Rethrows and Jumps-Through-Finally
1710--
1711
1712Support for implicit rethrows and jumping through the finally block is
1713handled by storing the current exception-handling context in
1714ObjCEHStack.
1715
1716In order to implement proper @finally semantics, we support one basic
1717mechanism for jumping through the finally block to an arbitrary
1718destination. Constructs which generate exits from a @try or @catch
1719block use this mechanism to implement the proper semantics by chaining
1720jumps, as necessary.
1721
1722This mechanism works like the one used for indirect goto: we
1723arbitrarily assign an ID to each destination and store the ID for the
1724destination in a variable prior to entering the finally block. At the
1725end of the finally block we simply create a switch to the proper
1726destination.
1727
1728Code gen for @synchronized(expr) stmt;
1729Effectively generating code for:
1730objc_sync_enter(expr);
1731@try stmt @finally { objc_sync_exit(expr); }
1732*/
1733
1734void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1735                                          const Stmt &S) {
1736  bool isTry = isa<ObjCAtTryStmt>(S);
1737  // Create various blocks we refer to for handling @finally.
1738  llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1739  llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1740  llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1741  llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
1742  llvm::Value *DestCode =
1743    CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst");
1744
1745  // Generate jump code. Done here so we can directly add things to
1746  // the switch instruction.
1747  llvm::BasicBlock *FinallyJump = CGF.createBasicBlock("finally.jump");
1748  llvm::SwitchInst *FinallySwitch =
1749    llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump),
1750                             FinallyEnd, 10, FinallyJump);
1751
1752  // Push an EH context entry, used for handling rethrows and jumps
1753  // through finally.
1754  CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit,
1755                                       FinallySwitch, DestCode);
1756  CGF.ObjCEHStack.push_back(&EHEntry);
1757
1758  // Allocate memory for the exception data and rethrow pointer.
1759  llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1760                                                    "exceptiondata.ptr");
1761  llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1762                                                 "_rethrow");
1763  if (!isTry) {
1764    // For @synchronized, call objc_sync_enter(sync.expr)
1765    llvm::Value *Arg = CGF.EmitScalarExpr(
1766                         cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1767    Arg = CGF.Builder.CreateBitCast(Arg, ObjCTypes.ObjectPtrTy);
1768    CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn, Arg);
1769  }
1770
1771  // Enter a new try block and call setjmp.
1772  CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1773  llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1774                                                       "jmpbufarray");
1775  JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1776  llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1777                                                     JmpBufPtr, "result");
1778
1779  llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1780  llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
1781  CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
1782                           TryHandler, TryBlock);
1783
1784  // Emit the @try block.
1785  CGF.EmitBlock(TryBlock);
1786  CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
1787                     : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
1788  CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
1789
1790  // Emit the "exception in @try" block.
1791  CGF.EmitBlock(TryHandler);
1792
1793  // Retrieve the exception object.  We may emit multiple blocks but
1794  // nothing can cross this so the value is already in SSA form.
1795  llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1796                                               ExceptionData,
1797                                               "caught");
1798  EHEntry.Exception = Caught;
1799  if (!isTry)
1800  {
1801    CGF.Builder.CreateStore(Caught, RethrowPtr);
1802    CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
1803  }
1804  else if (const ObjCAtCatchStmt* CatchStmt =
1805           cast<ObjCAtTryStmt>(S).getCatchStmts())
1806  {
1807    // Enter a new exception try block (in case a @catch block throws
1808    // an exception).
1809    CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1810
1811    llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1812                                                       JmpBufPtr, "result");
1813    llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
1814
1815    llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
1816    llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
1817    CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
1818
1819    CGF.EmitBlock(CatchBlock);
1820
1821    // Handle catch list. As a special case we check if everything is
1822    // matched and avoid generating code for falling off the end if
1823    // so.
1824    bool AllMatched = false;
1825    for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
1826      llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
1827
1828      const DeclStmt *CatchParam =
1829        cast_or_null<DeclStmt>(CatchStmt->getCatchParamStmt());
1830      const VarDecl *VD = 0;
1831      const PointerType *PT = 0;
1832
1833      // catch(...) always matches.
1834      if (!CatchParam) {
1835        AllMatched = true;
1836      } else {
1837        VD = cast<VarDecl>(CatchParam->getSolitaryDecl());
1838        PT = VD->getType()->getAsPointerType();
1839
1840        // catch(id e) always matches.
1841        // FIXME: For the time being we also match id<X>; this should
1842        // be rejected by Sema instead.
1843        if ((PT && CGF.getContext().isObjCIdType(PT->getPointeeType())) ||
1844            VD->getType()->isObjCQualifiedIdType())
1845          AllMatched = true;
1846      }
1847
1848      if (AllMatched) {
1849        if (CatchParam) {
1850          CGF.EmitStmt(CatchParam);
1851          assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
1852          CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(VD));
1853        }
1854
1855        CGF.EmitStmt(CatchStmt->getCatchBody());
1856        CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
1857        break;
1858      }
1859
1860      assert(PT && "Unexpected non-pointer type in @catch");
1861      QualType T = PT->getPointeeType();
1862      const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
1863      assert(ObjCType && "Catch parameter must have Objective-C type!");
1864
1865      // Check if the @catch block matches the exception object.
1866      llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
1867
1868      llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
1869                                                   Class, Caught, "match");
1870
1871      llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
1872
1873      CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
1874                               MatchedBlock, NextCatchBlock);
1875
1876      // Emit the @catch block.
1877      CGF.EmitBlock(MatchedBlock);
1878      CGF.EmitStmt(CatchParam);
1879      assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
1880
1881      llvm::Value *Tmp =
1882        CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(VD->getType()),
1883                                  "tmp");
1884      CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(VD));
1885
1886      CGF.EmitStmt(CatchStmt->getCatchBody());
1887      CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
1888
1889      CGF.EmitBlock(NextCatchBlock);
1890    }
1891
1892    if (!AllMatched) {
1893      // None of the handlers caught the exception, so store it to be
1894      // rethrown at the end of the @finally block.
1895      CGF.Builder.CreateStore(Caught, RethrowPtr);
1896      CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow);
1897    }
1898
1899    // Emit the exception handler for the @catch blocks.
1900    CGF.EmitBlock(CatchHandler);
1901    CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1902                                                   ExceptionData),
1903                            RethrowPtr);
1904    CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
1905  } else {
1906    CGF.Builder.CreateStore(Caught, RethrowPtr);
1907    CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
1908  }
1909
1910  // Pop the exception-handling stack entry. It is important to do
1911  // this now, because the code in the @finally block is not in this
1912  // context.
1913  CGF.ObjCEHStack.pop_back();
1914
1915  // Emit the @finally block.
1916  CGF.EmitBlock(FinallyBlock);
1917  CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
1918
1919  CGF.EmitBlock(FinallyNoExit);
1920  if (isTry) {
1921    if (const ObjCAtFinallyStmt* FinallyStmt =
1922          cast<ObjCAtTryStmt>(S).getFinallyStmt())
1923      CGF.EmitStmt(FinallyStmt->getFinallyBody());
1924  }
1925  else {
1926    // For @synchronized objc_sync_exit(expr); As finally's sole statement.
1927    // For @synchronized, call objc_sync_enter(sync.expr)
1928    llvm::Value *Arg = CGF.EmitScalarExpr(
1929                         cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1930    Arg = CGF.Builder.CreateBitCast(Arg, ObjCTypes.ObjectPtrTy);
1931    CGF.Builder.CreateCall(ObjCTypes.SyncExitFn, Arg);
1932  }
1933
1934  CGF.EmitBlock(FinallyJump);
1935
1936  CGF.EmitBlock(FinallyRethrow);
1937  CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
1938                         CGF.Builder.CreateLoad(RethrowPtr));
1939  CGF.Builder.CreateUnreachable();
1940
1941  CGF.EmitBlock(FinallyEnd);
1942}
1943
1944void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1945                              const ObjCAtThrowStmt &S) {
1946  llvm::Value *ExceptionAsObject;
1947
1948  if (const Expr *ThrowExpr = S.getThrowExpr()) {
1949    llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
1950    ExceptionAsObject =
1951      CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
1952  } else {
1953    assert((!CGF.ObjCEHStack.empty() && CGF.ObjCEHStack.back()->Exception) &&
1954           "Unexpected rethrow outside @catch block.");
1955    ExceptionAsObject = CGF.ObjCEHStack.back()->Exception;
1956  }
1957
1958  CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
1959  CGF.Builder.CreateUnreachable();
1960
1961  // Clear the insertion point to indicate we are in unreachable code.
1962  CGF.Builder.ClearInsertionPoint();
1963}
1964
1965void CodeGenFunction::EmitJumpThroughFinally(ObjCEHEntry *E,
1966                                             llvm::BasicBlock *Dst,
1967                                             bool ExecuteTryExit) {
1968  if (!HaveInsertPoint())
1969    return;
1970
1971  // Find the destination code for this block. We always use 0 for the
1972  // fallthrough block (default destination).
1973  llvm::SwitchInst *SI = E->FinallySwitch;
1974  llvm::ConstantInt *ID;
1975  if (Dst == SI->getDefaultDest()) {
1976    ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
1977  } else {
1978    ID = SI->findCaseDest(Dst);
1979    if (!ID) {
1980      // No code found, get a new unique one by just using the number
1981      // of switch successors.
1982      ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, SI->getNumSuccessors());
1983      SI->addCase(ID, Dst);
1984    }
1985  }
1986
1987  // Set the destination code and branch.
1988  Builder.CreateStore(ID, E->DestCode);
1989  EmitBranch(ExecuteTryExit ? E->FinallyBlock : E->FinallyNoExit);
1990}
1991
1992/// EmitObjCWeakRead - Code gen for loading value of a __weak
1993/// object: objc_read_weak (id *src)
1994///
1995llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
1996                                          llvm::Value *AddrWeakObj)
1997{
1998  AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
1999  llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.GcReadWeakFn,
2000                                                  AddrWeakObj, "weakread");
2001  return read_weak;
2002}
2003
2004/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2005/// objc_assign_weak (id src, id *dst)
2006///
2007void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2008                                   llvm::Value *src, llvm::Value *dst)
2009{
2010  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2011  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2012  CGF.Builder.CreateCall2(ObjCTypes.GcAssignWeakFn,
2013                          src, dst, "weakassign");
2014  return;
2015}
2016
2017/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2018/// objc_assign_global (id src, id *dst)
2019///
2020void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2021                                     llvm::Value *src, llvm::Value *dst)
2022{
2023  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2024  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2025  CGF.Builder.CreateCall2(ObjCTypes.GcAssignGlobalFn,
2026                          src, dst, "globalassign");
2027  return;
2028}
2029
2030/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2031/// objc_assign_ivar (id src, id *dst)
2032///
2033void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2034                                   llvm::Value *src, llvm::Value *dst)
2035{
2036  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2037  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2038  CGF.Builder.CreateCall2(ObjCTypes.GcAssignIvarFn,
2039                          src, dst, "assignivar");
2040  return;
2041}
2042
2043/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2044/// objc_assign_strongCast (id src, id *dst)
2045///
2046void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2047                                         llvm::Value *src, llvm::Value *dst)
2048{
2049  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2050  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2051  CGF.Builder.CreateCall2(ObjCTypes.GcAssignStrongCastFn,
2052                          src, dst, "weakassign");
2053  return;
2054}
2055
2056/* *** Private Interface *** */
2057
2058/// EmitImageInfo - Emit the image info marker used to encode some module
2059/// level information.
2060///
2061/// See: <rdr://4810609&4810587&4810587>
2062/// struct IMAGE_INFO {
2063///   unsigned version;
2064///   unsigned flags;
2065/// };
2066enum ImageInfoFlags {
2067  eImageInfo_FixAndContinue   = (1 << 0), // FIXME: Not sure what this implies
2068  eImageInfo_GarbageCollected = (1 << 1),
2069  eImageInfo_GCOnly           = (1 << 2)
2070};
2071
2072void CGObjCMac::EmitImageInfo() {
2073  unsigned version = 0; // Version is unused?
2074  unsigned flags = 0;
2075
2076  // FIXME: Fix and continue?
2077  if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2078    flags |= eImageInfo_GarbageCollected;
2079  if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2080    flags |= eImageInfo_GCOnly;
2081
2082  // Emitted as int[2];
2083  llvm::Constant *values[2] = {
2084    llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2085    llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2086  };
2087  llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
2088  llvm::GlobalVariable *GV =
2089    new llvm::GlobalVariable(AT, true,
2090                             llvm::GlobalValue::InternalLinkage,
2091                             llvm::ConstantArray::get(AT, values, 2),
2092                             "\01L_OBJC_IMAGE_INFO",
2093                             &CGM.getModule());
2094
2095  if (ObjCABI == 1) {
2096    GV->setSection("__OBJC, __image_info,regular");
2097  } else {
2098    GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
2099  }
2100
2101  UsedGlobals.push_back(GV);
2102}
2103
2104
2105// struct objc_module {
2106//   unsigned long version;
2107//   unsigned long size;
2108//   const char *name;
2109//   Symtab symtab;
2110// };
2111
2112// FIXME: Get from somewhere
2113static const int ModuleVersion = 7;
2114
2115void CGObjCMac::EmitModuleInfo() {
2116  uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
2117
2118  std::vector<llvm::Constant*> Values(4);
2119  Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2120  Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
2121  // This used to be the filename, now it is unused. <rdr://4327263>
2122  Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
2123  Values[3] = EmitModuleSymbols();
2124
2125  llvm::GlobalVariable *GV =
2126    new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
2127                             llvm::GlobalValue::InternalLinkage,
2128                             llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
2129                                                       Values),
2130                             "\01L_OBJC_MODULES",
2131                             &CGM.getModule());
2132  GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
2133  UsedGlobals.push_back(GV);
2134}
2135
2136llvm::Constant *CGObjCMac::EmitModuleSymbols() {
2137  unsigned NumClasses = DefinedClasses.size();
2138  unsigned NumCategories = DefinedCategories.size();
2139
2140  // Return null if no symbols were defined.
2141  if (!NumClasses && !NumCategories)
2142    return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2143
2144  std::vector<llvm::Constant*> Values(5);
2145  Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2146  Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2147  Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2148  Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2149
2150  // The runtime expects exactly the list of defined classes followed
2151  // by the list of defined categories, in a single array.
2152  std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
2153  for (unsigned i=0; i<NumClasses; i++)
2154    Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2155                                                ObjCTypes.Int8PtrTy);
2156  for (unsigned i=0; i<NumCategories; i++)
2157    Symbols[NumClasses + i] =
2158      llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2159                                     ObjCTypes.Int8PtrTy);
2160
2161  Values[4] =
2162    llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
2163                                                  NumClasses + NumCategories),
2164                             Symbols);
2165
2166  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2167
2168  llvm::GlobalVariable *GV =
2169    new llvm::GlobalVariable(Init->getType(), false,
2170                             llvm::GlobalValue::InternalLinkage,
2171                             Init,
2172                             "\01L_OBJC_SYMBOLS",
2173                             &CGM.getModule());
2174  GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
2175  UsedGlobals.push_back(GV);
2176  return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2177}
2178
2179llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
2180                                     const ObjCInterfaceDecl *ID) {
2181  LazySymbols.insert(ID->getIdentifier());
2182
2183  llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2184
2185  if (!Entry) {
2186    llvm::Constant *Casted =
2187      llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2188                                     ObjCTypes.ClassPtrTy);
2189    Entry =
2190      new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
2191                               llvm::GlobalValue::InternalLinkage,
2192                               Casted, "\01L_OBJC_CLASS_REFERENCES_",
2193                               &CGM.getModule());
2194    Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
2195    UsedGlobals.push_back(Entry);
2196  }
2197
2198  return Builder.CreateLoad(Entry, false, "tmp");
2199}
2200
2201llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
2202  llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2203
2204  if (!Entry) {
2205    llvm::Constant *Casted =
2206      llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2207                                     ObjCTypes.SelectorPtrTy);
2208    Entry =
2209      new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
2210                               llvm::GlobalValue::InternalLinkage,
2211                               Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
2212                               &CGM.getModule());
2213    Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
2214    UsedGlobals.push_back(Entry);
2215  }
2216
2217  return Builder.CreateLoad(Entry, false, "tmp");
2218}
2219
2220llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
2221  llvm::GlobalVariable *&Entry = ClassNames[Ident];
2222
2223  if (!Entry) {
2224    llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2225    Entry =
2226      new llvm::GlobalVariable(C->getType(), false,
2227                               llvm::GlobalValue::InternalLinkage,
2228                               C, "\01L_OBJC_CLASS_NAME_",
2229                               &CGM.getModule());
2230    Entry->setSection("__TEXT,__cstring,cstring_literals");
2231    UsedGlobals.push_back(Entry);
2232  }
2233
2234  return getConstantGEP(Entry, 0, 0);
2235}
2236
2237llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
2238  llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2239
2240  if (!Entry) {
2241    // FIXME: Avoid std::string copying.
2242    llvm::Constant *C = llvm::ConstantArray::get(Sel.getAsString());
2243    Entry =
2244      new llvm::GlobalVariable(C->getType(), false,
2245                               llvm::GlobalValue::InternalLinkage,
2246                               C, "\01L_OBJC_METH_VAR_NAME_",
2247                               &CGM.getModule());
2248    Entry->setSection("__TEXT,__cstring,cstring_literals");
2249    UsedGlobals.push_back(Entry);
2250  }
2251
2252  return getConstantGEP(Entry, 0, 0);
2253}
2254
2255// FIXME: Merge into a single cstring creation function.
2256llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
2257  return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2258}
2259
2260// FIXME: Merge into a single cstring creation function.
2261llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
2262  return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2263}
2264
2265llvm::Constant *CGObjCCommonMac::GetMethodVarType(const std::string &Name) {
2266  llvm::GlobalVariable *&Entry = MethodVarTypes[Name];
2267
2268  if (!Entry) {
2269    llvm::Constant *C = llvm::ConstantArray::get(Name);
2270    Entry =
2271      new llvm::GlobalVariable(C->getType(), false,
2272                               llvm::GlobalValue::InternalLinkage,
2273                               C, "\01L_OBJC_METH_VAR_TYPE_",
2274                               &CGM.getModule());
2275    Entry->setSection("__TEXT,__cstring,cstring_literals");
2276    UsedGlobals.push_back(Entry);
2277  }
2278
2279  return getConstantGEP(Entry, 0, 0);
2280}
2281
2282// FIXME: Merge into a single cstring creation function.
2283llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
2284  std::string TypeStr;
2285  CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2286                                                TypeStr);
2287  return GetMethodVarType(TypeStr);
2288}
2289
2290// FIXME: Merge into a single cstring creation function.
2291llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
2292  llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2293
2294  if (!Entry) {
2295    llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2296    Entry =
2297      new llvm::GlobalVariable(C->getType(), false,
2298                               llvm::GlobalValue::InternalLinkage,
2299                               C, "\01L_OBJC_PROP_NAME_ATTR_",
2300                               &CGM.getModule());
2301    Entry->setSection("__TEXT,__cstring,cstring_literals");
2302    UsedGlobals.push_back(Entry);
2303  }
2304
2305  return getConstantGEP(Entry, 0, 0);
2306}
2307
2308// FIXME: Merge into a single cstring creation function.
2309// FIXME: This Decl should be more precise.
2310llvm::Constant *CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
2311                                                 const Decl *Container) {
2312  std::string TypeStr;
2313  CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
2314  return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2315}
2316
2317void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
2318                                       const ObjCContainerDecl *CD,
2319                                       std::string &NameOut) {
2320  // FIXME: Find the mangling GCC uses.
2321  NameOut = (D->isInstanceMethod() ? "-" : "+");
2322  NameOut += '[';
2323  assert (CD && "Missing container decl in GetNameForMethod");
2324  NameOut += CD->getNameAsString();
2325  NameOut += ' ';
2326  NameOut += D->getSelector().getAsString();
2327  NameOut += ']';
2328}
2329
2330void CGObjCMac::FinishModule() {
2331  EmitModuleInfo();
2332
2333  // Emit the dummy bodies for any protocols which were referenced but
2334  // never defined.
2335  for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2336         i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2337    if (i->second->hasInitializer())
2338      continue;
2339
2340    std::vector<llvm::Constant*> Values(5);
2341    Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2342    Values[1] = GetClassName(i->first);
2343    Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2344    Values[3] = Values[4] =
2345      llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2346    i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2347    i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2348                                                        Values));
2349  }
2350
2351  std::vector<llvm::Constant*> Used;
2352  for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
2353         e = UsedGlobals.end(); i != e; ++i) {
2354    Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
2355  }
2356
2357  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
2358  llvm::GlobalValue *GV =
2359    new llvm::GlobalVariable(AT, false,
2360                             llvm::GlobalValue::AppendingLinkage,
2361                             llvm::ConstantArray::get(AT, Used),
2362                             "llvm.used",
2363                             &CGM.getModule());
2364
2365  GV->setSection("llvm.metadata");
2366
2367  // Add assembler directives to add lazy undefined symbol references
2368  // for classes which are referenced but not defined. This is
2369  // important for correct linker interaction.
2370
2371  // FIXME: Uh, this isn't particularly portable.
2372  std::stringstream s;
2373
2374  if (!CGM.getModule().getModuleInlineAsm().empty())
2375    s << "\n";
2376
2377  for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2378         e = LazySymbols.end(); i != e; ++i) {
2379    s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2380  }
2381  for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2382         e = DefinedSymbols.end(); i != e; ++i) {
2383    s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
2384      << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2385  }
2386
2387  CGM.getModule().appendModuleInlineAsm(s.str());
2388}
2389
2390CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
2391  : CGObjCCommonMac(cgm),
2392  ObjCTypes(cgm)
2393{
2394  ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
2395  ObjCABI = 2;
2396}
2397
2398/* *** */
2399
2400ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
2401: CGM(cgm)
2402{
2403  CodeGen::CodeGenTypes &Types = CGM.getTypes();
2404  ASTContext &Ctx = CGM.getContext();
2405
2406  ShortTy = Types.ConvertType(Ctx.ShortTy);
2407  IntTy = Types.ConvertType(Ctx.IntTy);
2408  LongTy = Types.ConvertType(Ctx.LongTy);
2409  Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2410
2411  ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
2412  PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
2413  SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
2414
2415  // FIXME: It would be nice to unify this with the opaque type, so
2416  // that the IR comes out a bit cleaner.
2417  const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2418  ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
2419
2420  // I'm not sure I like this. The implicit coordination is a bit
2421  // gross. We should solve this in a reasonable fashion because this
2422  // is a pretty common task (match some runtime data structure with
2423  // an LLVM data structure).
2424
2425  // FIXME: This is leaked.
2426  // FIXME: Merge with rewriter code?
2427
2428  // struct _objc_super {
2429  //   id self;
2430  //   Class cls;
2431  // }
2432  RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2433                                      SourceLocation(),
2434                                      &Ctx.Idents.get("_objc_super"));
2435  RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2436                                Ctx.getObjCIdType(), 0, false));
2437  RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
2438                                Ctx.getObjCClassType(), 0, false));
2439  RD->completeDefinition(Ctx);
2440
2441  SuperCTy = Ctx.getTagDeclType(RD);
2442  SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2443
2444  SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
2445  SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
2446
2447  // struct _prop_t {
2448  //   char *name;
2449  //   char *attributes;
2450  // }
2451  PropertyTy = llvm::StructType::get(Int8PtrTy,
2452                                     Int8PtrTy,
2453                                     NULL);
2454  CGM.getModule().addTypeName("struct._prop_t",
2455                              PropertyTy);
2456
2457  // struct _prop_list_t {
2458  //   uint32_t entsize;      // sizeof(struct _prop_t)
2459  //   uint32_t count_of_properties;
2460  //   struct _prop_t prop_list[count_of_properties];
2461  // }
2462  PropertyListTy = llvm::StructType::get(IntTy,
2463                                         IntTy,
2464                                         llvm::ArrayType::get(PropertyTy, 0),
2465                                         NULL);
2466  CGM.getModule().addTypeName("struct._prop_list_t",
2467                              PropertyListTy);
2468  // struct _prop_list_t *
2469  PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2470
2471  // struct _objc_method {
2472  //   SEL _cmd;
2473  //   char *method_type;
2474  //   char *_imp;
2475  // }
2476  MethodTy = llvm::StructType::get(SelectorPtrTy,
2477                                   Int8PtrTy,
2478                                   Int8PtrTy,
2479                                   NULL);
2480  CGM.getModule().addTypeName("struct._objc_method", MethodTy);
2481
2482  // struct _objc_cache *
2483  CacheTy = llvm::OpaqueType::get();
2484  CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2485  CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
2486
2487  // Property manipulation functions.
2488
2489  // id objc_getProperty (id, SEL, ptrdiff_t, bool)
2490  std::vector<const llvm::Type*> Params;
2491  Params.push_back(ObjectPtrTy);
2492  Params.push_back(SelectorPtrTy);
2493  Params.push_back(LongTy);
2494  Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2495  GetPropertyFn =
2496  CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2497                                                    Params,
2498                                                    false),
2499                            "objc_getProperty");
2500
2501  // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
2502  Params.clear();
2503  Params.push_back(ObjectPtrTy);
2504  Params.push_back(SelectorPtrTy);
2505  Params.push_back(LongTy);
2506  Params.push_back(ObjectPtrTy);
2507  Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2508  Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2509  SetPropertyFn =
2510  CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2511                                                    Params,
2512                                                    false),
2513                            "objc_setProperty");
2514  // Enumeration mutation.
2515
2516  Params.clear();
2517  Params.push_back(ObjectPtrTy);
2518  EnumerationMutationFn =
2519  CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2520                                                    Params,
2521                                                    false),
2522                            "objc_enumerationMutation");
2523
2524  // gc's API
2525  // id objc_read_weak (id *)
2526  Params.clear();
2527  Params.push_back(PtrObjectPtrTy);
2528  GcReadWeakFn =
2529  CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2530                                                    Params,
2531                                                    false),
2532                            "objc_read_weak");
2533  // id objc_assign_weak (id, id *)
2534  Params.clear();
2535  Params.push_back(ObjectPtrTy);
2536  Params.push_back(PtrObjectPtrTy);
2537  GcAssignWeakFn =
2538  CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2539                                                    Params,
2540                                                    false),
2541                            "objc_assign_weak");
2542  GcAssignGlobalFn =
2543  CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2544                                                    Params,
2545                                                    false),
2546                            "objc_assign_global");
2547  GcAssignIvarFn =
2548  CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2549                                                    Params,
2550                                                    false),
2551                            "objc_assign_ivar");
2552  GcAssignStrongCastFn =
2553  CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2554                                                    Params,
2555                                                    false),
2556                            "objc_assign_strongCast");
2557}
2558
2559ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
2560  : ObjCCommonTypesHelper(cgm)
2561{
2562  // struct _objc_method_description {
2563  //   SEL name;
2564  //   char *types;
2565  // }
2566  MethodDescriptionTy =
2567    llvm::StructType::get(SelectorPtrTy,
2568                          Int8PtrTy,
2569                          NULL);
2570  CGM.getModule().addTypeName("struct._objc_method_description",
2571                              MethodDescriptionTy);
2572
2573  // struct _objc_method_description_list {
2574  //   int count;
2575  //   struct _objc_method_description[1];
2576  // }
2577  MethodDescriptionListTy =
2578    llvm::StructType::get(IntTy,
2579                          llvm::ArrayType::get(MethodDescriptionTy, 0),
2580                          NULL);
2581  CGM.getModule().addTypeName("struct._objc_method_description_list",
2582                              MethodDescriptionListTy);
2583
2584  // struct _objc_method_description_list *
2585  MethodDescriptionListPtrTy =
2586    llvm::PointerType::getUnqual(MethodDescriptionListTy);
2587
2588  // Protocol description structures
2589
2590  // struct _objc_protocol_extension {
2591  //   uint32_t size;  // sizeof(struct _objc_protocol_extension)
2592  //   struct _objc_method_description_list *optional_instance_methods;
2593  //   struct _objc_method_description_list *optional_class_methods;
2594  //   struct _objc_property_list *instance_properties;
2595  // }
2596  ProtocolExtensionTy =
2597    llvm::StructType::get(IntTy,
2598                          MethodDescriptionListPtrTy,
2599                          MethodDescriptionListPtrTy,
2600                          PropertyListPtrTy,
2601                          NULL);
2602  CGM.getModule().addTypeName("struct._objc_protocol_extension",
2603                              ProtocolExtensionTy);
2604
2605  // struct _objc_protocol_extension *
2606  ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2607
2608  // Handle recursive construction of Protocol and ProtocolList types
2609
2610  llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2611  llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2612
2613  const llvm::Type *T =
2614    llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2615                          LongTy,
2616                          llvm::ArrayType::get(ProtocolTyHolder, 0),
2617                          NULL);
2618  cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2619
2620  // struct _objc_protocol {
2621  //   struct _objc_protocol_extension *isa;
2622  //   char *protocol_name;
2623  //   struct _objc_protocol **_objc_protocol_list;
2624  //   struct _objc_method_description_list *instance_methods;
2625  //   struct _objc_method_description_list *class_methods;
2626  // }
2627  T = llvm::StructType::get(ProtocolExtensionPtrTy,
2628                            Int8PtrTy,
2629                            llvm::PointerType::getUnqual(ProtocolListTyHolder),
2630                            MethodDescriptionListPtrTy,
2631                            MethodDescriptionListPtrTy,
2632                            NULL);
2633  cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2634
2635  ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2636  CGM.getModule().addTypeName("struct._objc_protocol_list",
2637                              ProtocolListTy);
2638  // struct _objc_protocol_list *
2639  ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2640
2641  ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
2642  CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
2643  ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
2644
2645  // Class description structures
2646
2647  // struct _objc_ivar {
2648  //   char *ivar_name;
2649  //   char *ivar_type;
2650  //   int  ivar_offset;
2651  // }
2652  IvarTy = llvm::StructType::get(Int8PtrTy,
2653                                 Int8PtrTy,
2654                                 IntTy,
2655                                 NULL);
2656  CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2657
2658  // struct _objc_ivar_list *
2659  IvarListTy = llvm::OpaqueType::get();
2660  CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2661  IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2662
2663  // struct _objc_method_list *
2664  MethodListTy = llvm::OpaqueType::get();
2665  CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2666  MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2667
2668  // struct _objc_class_extension *
2669  ClassExtensionTy =
2670    llvm::StructType::get(IntTy,
2671                          Int8PtrTy,
2672                          PropertyListPtrTy,
2673                          NULL);
2674  CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
2675  ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
2676
2677  llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
2678
2679  // struct _objc_class {
2680  //   Class isa;
2681  //   Class super_class;
2682  //   char *name;
2683  //   long version;
2684  //   long info;
2685  //   long instance_size;
2686  //   struct _objc_ivar_list *ivars;
2687  //   struct _objc_method_list *methods;
2688  //   struct _objc_cache *cache;
2689  //   struct _objc_protocol_list *protocols;
2690  //   char *ivar_layout;
2691  //   struct _objc_class_ext *ext;
2692  // };
2693  T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
2694                            llvm::PointerType::getUnqual(ClassTyHolder),
2695                            Int8PtrTy,
2696                            LongTy,
2697                            LongTy,
2698                            LongTy,
2699                            IvarListPtrTy,
2700                            MethodListPtrTy,
2701                            CachePtrTy,
2702                            ProtocolListPtrTy,
2703                            Int8PtrTy,
2704                            ClassExtensionPtrTy,
2705                            NULL);
2706  cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
2707
2708  ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
2709  CGM.getModule().addTypeName("struct._objc_class", ClassTy);
2710  ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
2711
2712  // struct _objc_category {
2713  //   char *category_name;
2714  //   char *class_name;
2715  //   struct _objc_method_list *instance_method;
2716  //   struct _objc_method_list *class_method;
2717  //   uint32_t size;  // sizeof(struct _objc_category)
2718  //   struct _objc_property_list *instance_properties;// category's @property
2719  // }
2720  CategoryTy = llvm::StructType::get(Int8PtrTy,
2721                                     Int8PtrTy,
2722                                     MethodListPtrTy,
2723                                     MethodListPtrTy,
2724                                     ProtocolListPtrTy,
2725                                     IntTy,
2726                                     PropertyListPtrTy,
2727                                     NULL);
2728  CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
2729
2730  // Global metadata structures
2731
2732  // struct _objc_symtab {
2733  //   long sel_ref_cnt;
2734  //   SEL *refs;
2735  //   short cls_def_cnt;
2736  //   short cat_def_cnt;
2737  //   char *defs[cls_def_cnt + cat_def_cnt];
2738  // }
2739  SymtabTy = llvm::StructType::get(LongTy,
2740                                   SelectorPtrTy,
2741                                   ShortTy,
2742                                   ShortTy,
2743                                   llvm::ArrayType::get(Int8PtrTy, 0),
2744                                   NULL);
2745  CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
2746  SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
2747
2748  // struct _objc_module {
2749  //   long version;
2750  //   long size;   // sizeof(struct _objc_module)
2751  //   char *name;
2752  //   struct _objc_symtab* symtab;
2753  //  }
2754  ModuleTy =
2755    llvm::StructType::get(LongTy,
2756                          LongTy,
2757                          Int8PtrTy,
2758                          SymtabPtrTy,
2759                          NULL);
2760  CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
2761
2762  // Message send functions.
2763
2764  // id objc_msgSend (id, SEL, ...)
2765  std::vector<const llvm::Type*> Params;
2766  Params.push_back(ObjectPtrTy);
2767  Params.push_back(SelectorPtrTy);
2768  MessageSendFn =
2769    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2770                                                      Params,
2771                                                      true),
2772                              "objc_msgSend");
2773
2774  // id objc_msgSend_stret (id, SEL, ...)
2775  Params.clear();
2776  Params.push_back(ObjectPtrTy);
2777  Params.push_back(SelectorPtrTy);
2778  MessageSendStretFn =
2779    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2780                                                      Params,
2781                                                      true),
2782                              "objc_msgSend_stret");
2783
2784  //
2785  Params.clear();
2786  Params.push_back(ObjectPtrTy);
2787  Params.push_back(SelectorPtrTy);
2788  // FIXME: This should be long double on x86_64?
2789  // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
2790  MessageSendFpretFn =
2791    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
2792                                                      Params,
2793                                                      true),
2794                              "objc_msgSend_fpret");
2795
2796  // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
2797  Params.clear();
2798  Params.push_back(SuperPtrTy);
2799  Params.push_back(SelectorPtrTy);
2800  MessageSendSuperFn =
2801    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2802                                                      Params,
2803                                                      true),
2804                              "objc_msgSendSuper");
2805
2806  // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
2807  //                              SEL op, ...)
2808  Params.clear();
2809  Params.push_back(Int8PtrTy);
2810  Params.push_back(SuperPtrTy);
2811  Params.push_back(SelectorPtrTy);
2812  MessageSendSuperStretFn =
2813    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2814                                                      Params,
2815                                                      true),
2816                              "objc_msgSendSuper_stret");
2817
2818  // There is no objc_msgSendSuper_fpret? How can that work?
2819  MessageSendSuperFpretFn = MessageSendSuperFn;
2820
2821  // FIXME: This is the size of the setjmp buffer and should be
2822  // target specific. 18 is what's used on 32-bit X86.
2823  uint64_t SetJmpBufferSize = 18;
2824
2825  // Exceptions
2826  const llvm::Type *StackPtrTy =
2827    llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
2828
2829  ExceptionDataTy =
2830    llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
2831                                               SetJmpBufferSize),
2832                          StackPtrTy, NULL);
2833  CGM.getModule().addTypeName("struct._objc_exception_data",
2834                              ExceptionDataTy);
2835
2836  Params.clear();
2837  Params.push_back(ObjectPtrTy);
2838  ExceptionThrowFn =
2839    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2840                                                      Params,
2841                                                      false),
2842                              "objc_exception_throw");
2843
2844  Params.clear();
2845  Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
2846  ExceptionTryEnterFn =
2847    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2848                                                      Params,
2849                                                      false),
2850                              "objc_exception_try_enter");
2851  ExceptionTryExitFn =
2852    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2853                                                      Params,
2854                                                      false),
2855                              "objc_exception_try_exit");
2856  ExceptionExtractFn =
2857    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2858                                                      Params,
2859                                                      false),
2860                              "objc_exception_extract");
2861
2862  Params.clear();
2863  Params.push_back(ClassPtrTy);
2864  Params.push_back(ObjectPtrTy);
2865  ExceptionMatchFn =
2866    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2867                                                      Params,
2868                                                      false),
2869                              "objc_exception_match");
2870
2871  // synchronized APIs
2872  // void objc_sync_enter (id)
2873  Params.clear();
2874  Params.push_back(ObjectPtrTy);
2875  SyncEnterFn =
2876  CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2877                                                    Params,
2878                                                    false),
2879                            "objc_sync_enter");
2880  // void objc_sync_exit (id)
2881  SyncExitFn =
2882  CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2883                                                    Params,
2884                                                    false),
2885                            "objc_sync_exit");
2886
2887
2888  Params.clear();
2889  Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
2890  SetJmpFn =
2891    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2892                                                      Params,
2893                                                      false),
2894                              "_setjmp");
2895
2896}
2897
2898ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
2899: ObjCCommonTypesHelper(cgm)
2900{
2901  // struct _method_list_t {
2902  //   uint32_t entsize;  // sizeof(struct _objc_method)
2903  //   uint32_t method_count;
2904  //   struct _objc_method method_list[method_count];
2905  // }
2906  MethodListnfABITy = llvm::StructType::get(IntTy,
2907                                            IntTy,
2908                                            llvm::ArrayType::get(MethodTy, 0),
2909                                            NULL);
2910  CGM.getModule().addTypeName("struct.__method_list_t",
2911                              MethodListnfABITy);
2912  // struct method_list_t *
2913  MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
2914
2915  // struct _protocol_t {
2916  //   id isa;  // NULL
2917  //   const char * const protocol_name;
2918  //   const struct _protocol_list_t * protocol_list; // super protocols
2919  //   const struct method_list_t * const instance_methods;
2920  //   const struct method_list_t * const class_methods;
2921  //   const struct method_list_t *optionalInstanceMethods;
2922  //   const struct method_list_t *optionalClassMethods;
2923  //   const struct _prop_list_t * properties;
2924  //   const uint32_t size;  // sizeof(struct _protocol_t)
2925  //   const uint32_t flags;  // = 0
2926  // }
2927
2928  // Holder for struct _protocol_list_t *
2929  llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2930
2931  ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
2932                                          Int8PtrTy,
2933                                          llvm::PointerType::getUnqual(
2934                                            ProtocolListTyHolder),
2935                                          MethodListnfABIPtrTy,
2936                                          MethodListnfABIPtrTy,
2937                                          MethodListnfABIPtrTy,
2938                                          MethodListnfABIPtrTy,
2939                                          PropertyListPtrTy,
2940                                          IntTy,
2941                                          IntTy,
2942                                          NULL);
2943  CGM.getModule().addTypeName("struct._protocol_t",
2944                              ProtocolnfABITy);
2945
2946  // struct _objc_protocol_list {
2947  //   long protocol_count;   // Note, this is 32/64 bit
2948  //   struct _protocol_t[protocol_count];
2949  // }
2950  ProtocolListnfABITy = llvm::StructType::get(LongTy,
2951                                              llvm::ArrayType::get(
2952                                                ProtocolnfABITy, 0),
2953                                              NULL);
2954  CGM.getModule().addTypeName("struct._objc_protocol_list",
2955                              ProtocolListnfABITy);
2956
2957  // struct _objc_protocol_list*
2958  ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
2959
2960  // FIXME! Is this doing the right thing?
2961  cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
2962                                                      ProtocolListnfABIPtrTy);
2963
2964  // struct _ivar_t {
2965  //   unsigned long int *offset;  // pointer to ivar offset location
2966  //   char *name;
2967  //   char *type;
2968  //   uint32_t alignment;
2969  //   uint32_t size;
2970  // }
2971  IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
2972                                      Int8PtrTy,
2973                                      Int8PtrTy,
2974                                      IntTy,
2975                                      IntTy,
2976                                      NULL);
2977  CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
2978
2979  // struct _ivar_list_t {
2980  //   uint32 entsize;  // sizeof(struct _ivar_t)
2981  //   uint32 count;
2982  //   struct _iver_t list[count];
2983  // }
2984  IvarListnfABITy = llvm::StructType::get(IntTy,
2985                                          IntTy,
2986                                          llvm::ArrayType::get(
2987                                                               IvarnfABITy, 0),
2988                                          NULL);
2989  CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
2990
2991  IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
2992
2993  // struct _class_ro_t {
2994  //   uint32_t const flags;
2995  //   uint32_t const instanceStart;
2996  //   uint32_t const instanceSize;
2997  //   uint32_t const reserved;  // only when building for 64bit targets
2998  //   const uint8_t * const ivarLayout;
2999  //   const char *const name;
3000  //   const struct _method_list_t * const baseMethods;
3001  //   const struct _objc_protocol_list *const baseProtocols;
3002  //   const struct _ivar_list_t *const ivars;
3003  //   const uint8_t * const weakIvarLayout;
3004  //   const struct _prop_list_t * const properties;
3005  // }
3006
3007  // FIXME. Add 'reserved' field in 64bit abi mode!
3008  ClassRonfABITy = llvm::StructType::get(IntTy,
3009                                         IntTy,
3010                                         IntTy,
3011                                         Int8PtrTy,
3012                                         Int8PtrTy,
3013                                         MethodListnfABIPtrTy,
3014                                         ProtocolListnfABIPtrTy,
3015                                         IvarListnfABIPtrTy,
3016                                         Int8PtrTy,
3017                                         PropertyListPtrTy,
3018                                         NULL);
3019  CGM.getModule().addTypeName("struct._class_ro_t",
3020                              ClassRonfABITy);
3021
3022  // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3023  std::vector<const llvm::Type*> Params;
3024  Params.push_back(ObjectPtrTy);
3025  Params.push_back(SelectorPtrTy);
3026  ImpnfABITy = llvm::PointerType::getUnqual(
3027                          llvm::FunctionType::get(ObjectPtrTy, Params, false));
3028
3029  // struct _class_t {
3030  //   struct _class_t *isa;
3031  //   struct _class_t * const superclass;
3032  //   void *cache;
3033  //   IMP *vtable;
3034  //   struct class_ro_t *ro;
3035  // }
3036
3037  llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3038  ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3039                                       llvm::PointerType::getUnqual(ClassTyHolder),
3040                                       CachePtrTy,
3041                                       llvm::PointerType::getUnqual(ImpnfABITy),
3042                                       llvm::PointerType::getUnqual(
3043                                                                ClassRonfABITy),
3044                                       NULL);
3045  CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3046
3047  cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3048                                                                ClassnfABITy);
3049
3050  // LLVM for struct _class_t *
3051  ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3052
3053  // struct _category_t {
3054  //   const char * const name;
3055  //   struct _class_t *const cls;
3056  //   const struct _method_list_t * const instance_methods;
3057  //   const struct _method_list_t * const class_methods;
3058  //   const struct _protocol_list_t * const protocols;
3059  //   const struct _prop_list_t * const properties;
3060  // }
3061  CategorynfABITy = llvm::StructType::get(Int8PtrTy,
3062                                          ClassnfABIPtrTy,
3063                                          MethodListnfABIPtrTy,
3064                                          MethodListnfABIPtrTy,
3065                                          ProtocolListnfABIPtrTy,
3066                                          PropertyListPtrTy,
3067                                          NULL);
3068  CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
3069
3070}
3071
3072llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
3073  FinishNonFragileABIModule();
3074
3075  return NULL;
3076}
3077
3078void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
3079  // nonfragile abi has no module definition.
3080  std::vector<llvm::Constant*> Used;
3081  for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
3082       e = UsedGlobals.end(); i != e; ++i) {
3083    Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
3084  }
3085
3086  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
3087  llvm::GlobalValue *GV =
3088  new llvm::GlobalVariable(AT, false,
3089                           llvm::GlobalValue::AppendingLinkage,
3090                           llvm::ConstantArray::get(AT, Used),
3091                           "llvm.used",
3092                           &CGM.getModule());
3093
3094  GV->setSection("llvm.metadata");
3095
3096}
3097
3098// Metadata flags
3099enum MetaDataDlags {
3100  CLS = 0x0,
3101  CLS_META = 0x1,
3102  CLS_ROOT = 0x2,
3103  CLS_HIDDEN = 0x10,
3104  CLS_EXCEPTION = 0x20
3105};
3106/// BuildClassRoTInitializer - generate meta-data for:
3107/// struct _class_ro_t {
3108///   uint32_t const flags;
3109///   uint32_t const instanceStart;
3110///   uint32_t const instanceSize;
3111///   uint32_t const reserved;  // only when building for 64bit targets
3112///   const uint8_t * const ivarLayout;
3113///   const char *const name;
3114///   const struct _method_list_t * const baseMethods;
3115///   const struct _objc_protocol_list *const baseProtocols;
3116///   const struct _ivar_list_t *const ivars;
3117///   const uint8_t * const weakIvarLayout;
3118///   const struct _prop_list_t * const properties;
3119/// }
3120///
3121llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
3122                                                unsigned flags,
3123                                                unsigned InstanceStart,
3124                                                unsigned InstanceSize,
3125                                                const ObjCImplementationDecl *ID) {
3126  std::string ClassName = ID->getNameAsString();
3127  std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
3128  Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
3129  Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
3130  Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
3131  // FIXME. For 64bit targets add 0 here.
3132  Values[ 3] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
3133  Values[ 4] = GetClassName(ID->getIdentifier());
3134  Values[ 5] = llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
3135  Values[ 6] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
3136  Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
3137  Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
3138  Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
3139  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
3140                                                   Values);
3141  llvm::GlobalVariable *CLASS_RO_GV =
3142  new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
3143                           llvm::GlobalValue::InternalLinkage,
3144                           Init,
3145                           (flags & CLS_META) ?
3146                           std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
3147                           std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
3148                           &CGM.getModule());
3149  CLASS_RO_GV->setSection(".section __DATA,__data,regular,no_dead_strip");
3150  UsedGlobals.push_back(CLASS_RO_GV);
3151  return CLASS_RO_GV;
3152}
3153
3154/// BuildClassMetaData - This routine defines that to-level meta-data
3155/// for the given ClassName for:
3156/// struct _class_t {
3157///   struct _class_t *isa;
3158///   struct _class_t * const superclass;
3159///   void *cache;
3160///   IMP *vtable;
3161///   struct class_ro_t *ro;
3162/// }
3163///
3164void CGObjCNonFragileABIMac::BuildClassMetaData(std::string &ClassName,
3165                                                llvm::Constant *IsAGV,
3166                                                llvm::Constant *SuperClassGV,
3167                                                llvm::Constant *ClassRoGV) {
3168  std::vector<llvm::Constant*> Values(5);
3169  Values[0] = IsAGV;
3170  Values[1] = SuperClassGV;
3171  Values[2] = ObjCEmptyCacheVar;  // &ObjCEmptyCacheVar
3172  Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
3173  Values[4] = ClassRoGV;                 // &CLASS_RO_GV
3174  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
3175                                                   Values);
3176  llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(ClassName);
3177  if (GV)
3178    GV->setInitializer(Init);
3179  else
3180    GV =
3181    new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
3182                             llvm::GlobalValue::ExternalLinkage,
3183                             Init,
3184                             ClassName,
3185                             &CGM.getModule());
3186  GV->setSection(".section __DATA,__data,regular,no_dead_strip");
3187  UsedGlobals.push_back(GV);
3188  // FIXME! why?
3189  GV->setAlignment(32);
3190
3191}
3192
3193void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
3194  std::string ClassName = ID->getNameAsString();
3195  if (!ObjCEmptyCacheVar) {
3196    ObjCEmptyCacheVar = new llvm::GlobalVariable(
3197                                            ObjCTypes.CachePtrTy,
3198                                            false,
3199                                            llvm::GlobalValue::ExternalLinkage,
3200                                            0,
3201                                            "\01_objc_empty_cache",
3202                                            &CGM.getModule());
3203    UsedGlobals.push_back(ObjCEmptyCacheVar);
3204
3205    ObjCEmptyVtableVar = new llvm::GlobalVariable(
3206                            llvm::PointerType::getUnqual(
3207                                                  ObjCTypes.ImpnfABITy),
3208                            false,
3209                            llvm::GlobalValue::ExternalLinkage,
3210                            0,
3211                            "\01_objc_empty_vtable",
3212                            &CGM.getModule());
3213    UsedGlobals.push_back(ObjCEmptyVtableVar);
3214  }
3215  uint32_t InstanceStart =
3216    CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
3217  uint32_t InstanceSize = InstanceStart;
3218  uint32_t flags = CLS_META;
3219  std::string ObjCMetaClassName("\01_OBJC_METACLASS_$_");
3220  std::string ObjCClassName("\01_OBJC_CLASS_$_");
3221
3222  llvm::GlobalVariable *SuperClassGV, *IsAGV;
3223
3224  if (ID->getClassInterface() && !ID->getClassInterface()->getSuperClass()) {
3225    // class is root
3226    flags |= CLS_ROOT;
3227    std::string SuperClassName = ObjCClassName + ClassName;
3228    SuperClassGV = CGM.getModule().getGlobalVariable(SuperClassName);
3229    if (!SuperClassGV)
3230      SuperClassGV =
3231        new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
3232                                llvm::GlobalValue::ExternalLinkage,
3233                                 0,
3234                                 SuperClassName,
3235                                 &CGM.getModule());
3236    UsedGlobals.push_back(SuperClassGV);
3237    std::string IsAClassName = ObjCMetaClassName + ClassName;
3238    IsAGV = CGM.getModule().getGlobalVariable(IsAClassName);
3239    if (!IsAGV)
3240      IsAGV =
3241        new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
3242                                 llvm::GlobalValue::ExternalLinkage,
3243                                 0,
3244                                 IsAClassName,
3245                                 &CGM.getModule());
3246    UsedGlobals.push_back(IsAGV);
3247  } else {
3248    // Not a root.
3249    std::string RootClassName =
3250      ID->getClassInterface()->getSuperClass()->getNameAsString();
3251    std::string SuperClassName = ObjCMetaClassName + RootClassName;
3252    SuperClassGV = CGM.getModule().getGlobalVariable(SuperClassName);
3253    if (!SuperClassGV)
3254      SuperClassGV =
3255        new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
3256                                 llvm::GlobalValue::ExternalLinkage,
3257                                 0,
3258                                 SuperClassName,
3259                                 &CGM.getModule());
3260    UsedGlobals.push_back(SuperClassGV);
3261    IsAGV = SuperClassGV;
3262  }
3263  llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
3264                                                               InstanceStart,
3265                                                               InstanceSize,ID);
3266  std::string MetaClassName = ObjCMetaClassName + ClassName;
3267  BuildClassMetaData(MetaClassName, IsAGV, SuperClassGV, CLASS_RO_GV);
3268}
3269
3270/* *** */
3271
3272CodeGen::CGObjCRuntime *
3273CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
3274  return new CGObjCMac(CGM);
3275}
3276
3277CodeGen::CGObjCRuntime *
3278CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
3279  return new CGObjCNonFragileABIMac(CGM);
3280}
3281