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