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