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