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