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