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