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