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