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