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