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