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