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