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