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