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