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