1//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This provides Objective-C code generation targeting the Apple runtime.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGBlocks.h"
14#include "CGCleanup.h"
15#include "CGObjCRuntime.h"
16#include "CGRecordLayout.h"
17#include "CodeGenFunction.h"
18#include "CodeGenModule.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/Attr.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/Mangle.h"
24#include "clang/AST/RecordLayout.h"
25#include "clang/AST/StmtObjC.h"
26#include "clang/Basic/CodeGenOptions.h"
27#include "clang/Basic/LangOptions.h"
28#include "clang/CodeGen/CGFunctionInfo.h"
29#include "clang/CodeGen/ConstantInitBuilder.h"
30#include "llvm/ADT/CachedHashString.h"
31#include "llvm/ADT/DenseSet.h"
32#include "llvm/ADT/SetVector.h"
33#include "llvm/ADT/SmallPtrSet.h"
34#include "llvm/ADT/SmallString.h"
35#include "llvm/ADT/UniqueVector.h"
36#include "llvm/IR/DataLayout.h"
37#include "llvm/IR/InlineAsm.h"
38#include "llvm/IR/IntrinsicInst.h"
39#include "llvm/IR/LLVMContext.h"
40#include "llvm/IR/Module.h"
41#include "llvm/Support/ScopedPrinter.h"
42#include "llvm/Support/raw_ostream.h"
43#include <cstdio>
44
45using namespace clang;
46using namespace CodeGen;
47
48namespace {
49
50// FIXME: We should find a nicer way to make the labels for metadata, string
51// concatenation is lame.
52
53class ObjCCommonTypesHelper {
54protected:
55 llvm::LLVMContext &VMContext;
56
57private:
58 // The types of these functions don't really matter because we
59 // should always bitcast before calling them.
60
61 /// id objc_msgSend (id, SEL, ...)
62 ///
63 /// The default messenger, used for sends whose ABI is unchanged from
64 /// the all-integer/pointer case.
65 llvm::FunctionCallee getMessageSendFn() const {
66 // Add the non-lazy-bind attribute, since objc_msgSend is likely to
67 // be called a lot.
68 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
69 return CGM.CreateRuntimeFunction(
70 llvm::FunctionType::get(ObjectPtrTy, params, true), "objc_msgSend",
71 llvm::AttributeList::get(CGM.getLLVMContext(),
72 llvm::AttributeList::FunctionIndex,
73 llvm::Attribute::NonLazyBind));
74 }
75
76 /// void objc_msgSend_stret (id, SEL, ...)
77 ///
78 /// The messenger used when the return value is an aggregate returned
79 /// by indirect reference in the first argument, and therefore the
80 /// self and selector parameters are shifted over by one.
81 llvm::FunctionCallee getMessageSendStretFn() const {
82 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
83 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy,
84 params, true),
85 "objc_msgSend_stret");
86 }
87
88 /// [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
89 ///
90 /// The messenger used when the return value is returned on the x87
91 /// floating-point stack; without a special entrypoint, the nil case
92 /// would be unbalanced.
93 llvm::FunctionCallee getMessageSendFpretFn() const {
94 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
95 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.DoubleTy,
96 params, true),
97 "objc_msgSend_fpret");
98 }
99
100 /// _Complex long double objc_msgSend_fp2ret(id self, SEL op, ...)
101 ///
102 /// The messenger used when the return value is returned in two values on the
103 /// x87 floating point stack; without a special entrypoint, the nil case
104 /// would be unbalanced. Only used on 64-bit X86.
105 llvm::FunctionCallee getMessageSendFp2retFn() const {
106 llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
107 llvm::Type *longDoubleType = llvm::Type::getX86_FP80Ty(VMContext);
108 llvm::Type *resultType =
109 llvm::StructType::get(longDoubleType, longDoubleType);
110
111 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(resultType,
112 params, true),
113 "objc_msgSend_fp2ret");
114 }
115
116 /// id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
117 ///
118 /// The messenger used for super calls, which have different dispatch
119 /// semantics. The class passed is the superclass of the current
120 /// class.
121 llvm::FunctionCallee getMessageSendSuperFn() const {
122 llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy };
123 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
124 params, true),
125 "objc_msgSendSuper");
126 }
127
128 /// id objc_msgSendSuper2(struct objc_super *super, SEL op, ...)
129 ///
130 /// A slightly different messenger used for super calls. The class
131 /// passed is the current class.
132 llvm::FunctionCallee getMessageSendSuperFn2() const {
133 llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy };
134 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
135 params, true),
136 "objc_msgSendSuper2");
137 }
138
139 /// void objc_msgSendSuper_stret(void *stretAddr, struct objc_super *super,
140 /// SEL op, ...)
141 ///
142 /// The messenger used for super calls which return an aggregate indirectly.
143 llvm::FunctionCallee getMessageSendSuperStretFn() const {
144 llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy };
145 return CGM.CreateRuntimeFunction(
146 llvm::FunctionType::get(CGM.VoidTy, params, true),
147 "objc_msgSendSuper_stret");
148 }
149
150 /// void objc_msgSendSuper2_stret(void * stretAddr, struct objc_super *super,
151 /// SEL op, ...)
152 ///
153 /// objc_msgSendSuper_stret with the super2 semantics.
154 llvm::FunctionCallee getMessageSendSuperStretFn2() const {
155 llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy };
156 return CGM.CreateRuntimeFunction(
157 llvm::FunctionType::get(CGM.VoidTy, params, true),
158 "objc_msgSendSuper2_stret");
159 }
160
161 llvm::FunctionCallee getMessageSendSuperFpretFn() const {
162 // There is no objc_msgSendSuper_fpret? How can that work?
163 return getMessageSendSuperFn();
164 }
165
166 llvm::FunctionCallee getMessageSendSuperFpretFn2() const {
167 // There is no objc_msgSendSuper_fpret? How can that work?
168 return getMessageSendSuperFn2();
169 }
170
171protected:
172 CodeGen::CodeGenModule &CGM;
173
174public:
175 llvm::IntegerType *ShortTy, *IntTy, *LongTy;
176 llvm::PointerType *Int8PtrTy, *Int8PtrPtrTy;
177 llvm::Type *IvarOffsetVarTy;
178
179 /// ObjectPtrTy - LLVM type for object handles (typeof(id))
180 llvm::PointerType *ObjectPtrTy;
181
182 /// PtrObjectPtrTy - LLVM type for id *
183 llvm::PointerType *PtrObjectPtrTy;
184
185 /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
186 llvm::PointerType *SelectorPtrTy;
187
188private:
189 /// ProtocolPtrTy - LLVM type for external protocol handles
190 /// (typeof(Protocol))
191 llvm::Type *ExternalProtocolPtrTy;
192
193public:
194 llvm::Type *getExternalProtocolPtrTy() {
195 if (!ExternalProtocolPtrTy) {
196 // FIXME: It would be nice to unify this with the opaque type, so that the
197 // IR comes out a bit cleaner.
198 CodeGen::CodeGenTypes &Types = CGM.getTypes();
199 ASTContext &Ctx = CGM.getContext();
200 llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
201 ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
202 }
203
204 return ExternalProtocolPtrTy;
205 }
206
207 // SuperCTy - clang type for struct objc_super.
208 QualType SuperCTy;
209 // SuperPtrCTy - clang type for struct objc_super *.
210 QualType SuperPtrCTy;
211
212 /// SuperTy - LLVM type for struct objc_super.
213 llvm::StructType *SuperTy;
214 /// SuperPtrTy - LLVM type for struct objc_super *.
215 llvm::PointerType *SuperPtrTy;
216
217 /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
218 /// in GCC parlance).
219 llvm::StructType *PropertyTy;
220
221 /// PropertyListTy - LLVM type for struct objc_property_list
222 /// (_prop_list_t in GCC parlance).
223 llvm::StructType *PropertyListTy;
224 /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
225 llvm::PointerType *PropertyListPtrTy;
226
227 // MethodTy - LLVM type for struct objc_method.
228 llvm::StructType *MethodTy;
229
230 /// CacheTy - LLVM type for struct objc_cache.
231 llvm::Type *CacheTy;
232 /// CachePtrTy - LLVM type for struct objc_cache *.
233 llvm::PointerType *CachePtrTy;
234
235 llvm::FunctionCallee getGetPropertyFn() {
236 CodeGen::CodeGenTypes &Types = CGM.getTypes();
237 ASTContext &Ctx = CGM.getContext();
238 // id objc_getProperty (id, SEL, ptrdiff_t, bool)
239 CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
240 CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
241 CanQualType Params[] = {
242 IdType, SelType,
243 Ctx.getPointerDiffType()->getCanonicalTypeUnqualified(), Ctx.BoolTy};
244 llvm::FunctionType *FTy =
245 Types.GetFunctionType(
246 Types.arrangeBuiltinFunctionDeclaration(IdType, Params));
247 return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
248 }
249
250 llvm::FunctionCallee getSetPropertyFn() {
251 CodeGen::CodeGenTypes &Types = CGM.getTypes();
252 ASTContext &Ctx = CGM.getContext();
253 // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
254 CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
255 CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
256 CanQualType Params[] = {
257 IdType,
258 SelType,
259 Ctx.getPointerDiffType()->getCanonicalTypeUnqualified(),
260 IdType,
261 Ctx.BoolTy,
262 Ctx.BoolTy};
263 llvm::FunctionType *FTy =
264 Types.GetFunctionType(
265 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));
266 return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
267 }
268
269 llvm::FunctionCallee getOptimizedSetPropertyFn(bool atomic, bool copy) {
270 CodeGen::CodeGenTypes &Types = CGM.getTypes();
271 ASTContext &Ctx = CGM.getContext();
272 // void objc_setProperty_atomic(id self, SEL _cmd,
273 // id newValue, ptrdiff_t offset);
274 // void objc_setProperty_nonatomic(id self, SEL _cmd,
275 // id newValue, ptrdiff_t offset);
276 // void objc_setProperty_atomic_copy(id self, SEL _cmd,
277 // id newValue, ptrdiff_t offset);
278 // void objc_setProperty_nonatomic_copy(id self, SEL _cmd,
279 // id newValue, ptrdiff_t offset);
280
281 SmallVector<CanQualType,4> Params;
282 CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
283 CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
284 Params.push_back(IdType);
285 Params.push_back(SelType);
286 Params.push_back(IdType);
287 Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified());
288 llvm::FunctionType *FTy =
289 Types.GetFunctionType(
290 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));
291 const char *name;
292 if (atomic && copy)
293 name = "objc_setProperty_atomic_copy";
294 else if (atomic && !copy)
295 name = "objc_setProperty_atomic";
296 else if (!atomic && copy)
297 name = "objc_setProperty_nonatomic_copy";
298 else
299 name = "objc_setProperty_nonatomic";
300
301 return CGM.CreateRuntimeFunction(FTy, name);
302 }
303
304 llvm::FunctionCallee getCopyStructFn() {
305 CodeGen::CodeGenTypes &Types = CGM.getTypes();
306 ASTContext &Ctx = CGM.getContext();
307 // void objc_copyStruct (void *, const void *, size_t, bool, bool)
308 SmallVector<CanQualType,5> Params;
309 Params.push_back(Ctx.VoidPtrTy);
310 Params.push_back(Ctx.VoidPtrTy);
311 Params.push_back(Ctx.getSizeType());
312 Params.push_back(Ctx.BoolTy);
313 Params.push_back(Ctx.BoolTy);
314 llvm::FunctionType *FTy =
315 Types.GetFunctionType(
316 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));
317 return CGM.CreateRuntimeFunction(FTy, "objc_copyStruct");
318 }
319
320 /// This routine declares and returns address of:
321 /// void objc_copyCppObjectAtomic(
322 /// void *dest, const void *src,
323 /// void (*copyHelper) (void *dest, const void *source));
324 llvm::FunctionCallee getCppAtomicObjectFunction() {
325 CodeGen::CodeGenTypes &Types = CGM.getTypes();
326 ASTContext &Ctx = CGM.getContext();
327 /// void objc_copyCppObjectAtomic(void *dest, const void *src, void *helper);
328 SmallVector<CanQualType,3> Params;
329 Params.push_back(Ctx.VoidPtrTy);
330 Params.push_back(Ctx.VoidPtrTy);
331 Params.push_back(Ctx.VoidPtrTy);
332 llvm::FunctionType *FTy =
333 Types.GetFunctionType(
334 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));
335 return CGM.CreateRuntimeFunction(FTy, "objc_copyCppObjectAtomic");
336 }
337
338 llvm::FunctionCallee getEnumerationMutationFn() {
339 CodeGen::CodeGenTypes &Types = CGM.getTypes();
340 ASTContext &Ctx = CGM.getContext();
341 // void objc_enumerationMutation (id)
342 SmallVector<CanQualType,1> Params;
343 Params.push_back(Ctx.getCanonicalParamType(Ctx.getObjCIdType()));
344 llvm::FunctionType *FTy =
345 Types.GetFunctionType(
346 Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));
347 return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
348 }
349
350 llvm::FunctionCallee getLookUpClassFn() {
351 CodeGen::CodeGenTypes &Types = CGM.getTypes();
352 ASTContext &Ctx = CGM.getContext();
353 // Class objc_lookUpClass (const char *)
354 SmallVector<CanQualType,1> Params;
355 Params.push_back(
356 Ctx.getCanonicalType(Ctx.getPointerType(Ctx.CharTy.withConst())));
357 llvm::FunctionType *FTy =
358 Types.GetFunctionType(Types.arrangeBuiltinFunctionDeclaration(
359 Ctx.getCanonicalType(Ctx.getObjCClassType()),
360 Params));
361 return CGM.CreateRuntimeFunction(FTy, "objc_lookUpClass");
362 }
363
364 /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
365 llvm::FunctionCallee getGcReadWeakFn() {
366 // id objc_read_weak (id *)
367 llvm::Type *args[] = { ObjectPtrTy->getPointerTo() };
368 llvm::FunctionType *FTy =
369 llvm::FunctionType::get(ObjectPtrTy, args, false);
370 return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
371 }
372
373 /// GcAssignWeakFn -- LLVM objc_assign_weak function.
374 llvm::FunctionCallee getGcAssignWeakFn() {
375 // id objc_assign_weak (id, id *)
376 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
377 llvm::FunctionType *FTy =
378 llvm::FunctionType::get(ObjectPtrTy, args, false);
379 return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
380 }
381
382 /// GcAssignGlobalFn -- LLVM objc_assign_global function.
383 llvm::FunctionCallee getGcAssignGlobalFn() {
384 // id objc_assign_global(id, id *)
385 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
386 llvm::FunctionType *FTy =
387 llvm::FunctionType::get(ObjectPtrTy, args, false);
388 return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
389 }
390
391 /// GcAssignThreadLocalFn -- LLVM objc_assign_threadlocal function.
392 llvm::FunctionCallee getGcAssignThreadLocalFn() {
393 // id objc_assign_threadlocal(id src, id * dest)
394 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
395 llvm::FunctionType *FTy =
396 llvm::FunctionType::get(ObjectPtrTy, args, false);
397 return CGM.CreateRuntimeFunction(FTy, "objc_assign_threadlocal");
398 }
399
400 /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
401 llvm::FunctionCallee getGcAssignIvarFn() {
402 // id objc_assign_ivar(id, id *, ptrdiff_t)
403 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo(),
404 CGM.PtrDiffTy };
405 llvm::FunctionType *FTy =
406 llvm::FunctionType::get(ObjectPtrTy, args, false);
407 return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
408 }
409
410 /// GcMemmoveCollectableFn -- LLVM objc_memmove_collectable function.
411 llvm::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.
419 llvm::FunctionCallee getGcAssignStrongCastFn() {
420 // id objc_assign_strongCast(id, id *)
421 llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
422 llvm::FunctionType *FTy =
423 llvm::FunctionType::get(ObjectPtrTy, args, false);
424 return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
425 }
426
427 /// ExceptionThrowFn - LLVM objc_exception_throw function.
428 llvm::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.
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.
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.
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
461 llvm::FunctionCallee getSendFn(bool IsSuper) const {
462 return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
463 }
464
465 llvm::FunctionCallee getSendFn2(bool IsSuper) const {
466 return IsSuper ? getMessageSendSuperFn2() : getMessageSendFn();
467 }
468
469 llvm::FunctionCallee getSendStretFn(bool IsSuper) const {
470 return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
471 }
472
473 llvm::FunctionCallee getSendStretFn2(bool IsSuper) const {
474 return IsSuper ? getMessageSendSuperStretFn2() : getMessageSendStretFn();
475 }
476
477 llvm::FunctionCallee getSendFpretFn(bool IsSuper) const {
478 return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
479 }
480
481 llvm::FunctionCallee getSendFpretFn2(bool IsSuper) const {
482 return IsSuper ? getMessageSendSuperFpretFn2() : getMessageSendFpretFn();
483 }
484
485 llvm::FunctionCallee getSendFp2retFn(bool IsSuper) const {
486 return IsSuper ? getMessageSendSuperFn() : getMessageSendFp2retFn();
487 }
488
489 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.
498class ObjCTypesHelper : public ObjCCommonTypesHelper {
499public:
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.
555 llvm::FunctionCallee getExceptionTryEnterFn() {
556 llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
557 return CGM.CreateRuntimeFunction(
558 llvm::FunctionType::get(CGM.VoidTy, params, false),
559 "objc_exception_try_enter");
560 }
561
562 /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
563 llvm::FunctionCallee getExceptionTryExitFn() {
564 llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
565 return CGM.CreateRuntimeFunction(
566 llvm::FunctionType::get(CGM.VoidTy, params, false),
567 "objc_exception_try_exit");
568 }
569
570 /// ExceptionExtractFn - LLVM objc_exception_extract function.
571 llvm::FunctionCallee getExceptionExtractFn() {
572 llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
573 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
574 params, false),
575 "objc_exception_extract");
576 }
577
578 /// ExceptionMatchFn - LLVM objc_exception_match function.
579 llvm::FunctionCallee getExceptionMatchFn() {
580 llvm::Type *params[] = { ClassPtrTy, ObjectPtrTy };
581 return CGM.CreateRuntimeFunction(
582 llvm::FunctionType::get(CGM.Int32Ty, params, false),
583 "objc_exception_match");
584 }
585
586 /// SetJmpFn - LLVM _setjmp function.
587 llvm::FunctionCallee getSetJmpFn() {
588 // This is specifically the prototype for x86.
589 llvm::Type *params[] = { CGM.Int32Ty->getPointerTo() };
590 return CGM.CreateRuntimeFunction(
591 llvm::FunctionType::get(CGM.Int32Ty, params, false), "_setjmp",
592 llvm::AttributeList::get(CGM.getLLVMContext(),
593 llvm::AttributeList::FunctionIndex,
594 llvm::Attribute::NonLazyBind));
595 }
596
597public:
598 ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
599};
600
601/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
602/// modern abi
603class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
604public:
605 // MethodListnfABITy - LLVM for struct _method_list_t
606 llvm::StructType *MethodListnfABITy;
607
608 // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
609 llvm::PointerType *MethodListnfABIPtrTy;
610
611 // ProtocolnfABITy = LLVM for struct _protocol_t
612 llvm::StructType *ProtocolnfABITy;
613
614 // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
615 llvm::PointerType *ProtocolnfABIPtrTy;
616
617 // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
618 llvm::StructType *ProtocolListnfABITy;
619
620 // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
621 llvm::PointerType *ProtocolListnfABIPtrTy;
622
623 // ClassnfABITy - LLVM for struct _class_t
624 llvm::StructType *ClassnfABITy;
625
626 // ClassnfABIPtrTy - LLVM for struct _class_t*
627 llvm::PointerType *ClassnfABIPtrTy;
628
629 // IvarnfABITy - LLVM for struct _ivar_t
630 llvm::StructType *IvarnfABITy;
631
632 // IvarListnfABITy - LLVM for struct _ivar_list_t
633 llvm::StructType *IvarListnfABITy;
634
635 // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
636 llvm::PointerType *IvarListnfABIPtrTy;
637
638 // ClassRonfABITy - LLVM for struct _class_ro_t
639 llvm::StructType *ClassRonfABITy;
640
641 // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
642 llvm::PointerType *ImpnfABITy;
643
644 // CategorynfABITy - LLVM for struct _category_t
645 llvm::StructType *CategorynfABITy;
646
647 // New types for nonfragile abi messaging.
648
649 // MessageRefTy - LLVM for:
650 // struct _message_ref_t {
651 // IMP messenger;
652 // SEL name;
653 // };
654 llvm::StructType *MessageRefTy;
655 // MessageRefCTy - clang type for struct _message_ref_t
656 QualType MessageRefCTy;
657
658 // MessageRefPtrTy - LLVM for struct _message_ref_t*
659 llvm::Type *MessageRefPtrTy;
660 // MessageRefCPtrTy - clang type for struct _message_ref_t*
661 QualType MessageRefCPtrTy;
662
663 // SuperMessageRefTy - LLVM for:
664 // struct _super_message_ref_t {
665 // SUPER_IMP messenger;
666 // SEL name;
667 // };
668 llvm::StructType *SuperMessageRefTy;
669
670 // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
671 llvm::PointerType *SuperMessageRefPtrTy;
672
673 llvm::FunctionCallee getMessageSendFixupFn() {
674 // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
675 llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
676 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
677 params, true),
678 "objc_msgSend_fixup");
679 }
680
681 llvm::FunctionCallee getMessageSendFpretFixupFn() {
682 // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
683 llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
684 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
685 params, true),
686 "objc_msgSend_fpret_fixup");
687 }
688
689 llvm::FunctionCallee getMessageSendStretFixupFn() {
690 // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
691 llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
692 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
693 params, true),
694 "objc_msgSend_stret_fixup");
695 }
696
697 llvm::FunctionCallee getMessageSendSuper2FixupFn() {
698 // id objc_msgSendSuper2_fixup (struct objc_super *,
699 // struct _super_message_ref_t*, ...)
700 llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy };
701 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
702 params, true),
703 "objc_msgSendSuper2_fixup");
704 }
705
706 llvm::FunctionCallee getMessageSendSuper2StretFixupFn() {
707 // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
708 // struct _super_message_ref_t*, ...)
709 llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy };
710 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
711 params, true),
712 "objc_msgSendSuper2_stret_fixup");
713 }
714
715 llvm::FunctionCallee getObjCEndCatchFn() {
716 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy, false),
717 "objc_end_catch");
718 }
719
720 llvm::FunctionCallee getObjCBeginCatchFn() {
721 llvm::Type *params[] = { Int8PtrTy };
722 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
723 params, false),
724 "objc_begin_catch");
725 }
726
727 /// Class objc_loadClassref (void *)
728 ///
729 /// Loads from a classref. For Objective-C stub classes, this invokes the
730 /// initialization callback stored inside the stub. For all other classes
731 /// this simply dereferences the pointer.
732 llvm::FunctionCallee getLoadClassrefFn() const {
733 // Add the non-lazy-bind attribute, since objc_loadClassref is likely to
734 // be called a lot.
735 //
736 // Also it is safe to make it readnone, since we never load or store the
737 // classref except by calling this function.
738 llvm::Type *params[] = { Int8PtrPtrTy };
739 llvm::FunctionCallee F = CGM.CreateRuntimeFunction(
740 llvm::FunctionType::get(ClassnfABIPtrTy, params, false),
741 "objc_loadClassref",
742 llvm::AttributeList::get(CGM.getLLVMContext(),
743 llvm::AttributeList::FunctionIndex,
744 {llvm::Attribute::NonLazyBind,
745 llvm::Attribute::ReadNone,
746 llvm::Attribute::NoUnwind}));
747 if (!CGM.getTriple().isOSBinFormatCOFF())
748 cast<llvm::Function>(F.getCallee())->setLinkage(
749 llvm::Function::ExternalWeakLinkage);
750
751 return F;
752 }
753
754 llvm::StructType *EHTypeTy;
755 llvm::Type *EHTypePtrTy;
756
757 ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
758};
759
760enum class ObjCLabelType {
761 ClassName,
762 MethodVarName,
763 MethodVarType,
764 PropertyName,
765};
766
767class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
768public:
769 class SKIP_SCAN {
770 public:
771 unsigned skip;
772 unsigned scan;
773 SKIP_SCAN(unsigned _skip = 0, unsigned _scan = 0)
774 : skip(_skip), scan(_scan) {}
775 };
776
777 /// opcode for captured block variables layout 'instructions'.
778 /// In the following descriptions, 'I' is the value of the immediate field.
779 /// (field following the opcode).
780 ///
781 enum BLOCK_LAYOUT_OPCODE {
782 /// An operator which affects how the following layout should be
783 /// interpreted.
784 /// I == 0: Halt interpretation and treat everything else as
785 /// a non-pointer. Note that this instruction is equal
786 /// to '\0'.
787 /// I != 0: Currently unused.
788 BLOCK_LAYOUT_OPERATOR = 0,
789
790 /// The next I+1 bytes do not contain a value of object pointer type.
791 /// Note that this can leave the stream unaligned, meaning that
792 /// subsequent word-size instructions do not begin at a multiple of
793 /// the pointer size.
794 BLOCK_LAYOUT_NON_OBJECT_BYTES = 1,
795
796 /// The next I+1 words do not contain a value of object pointer type.
797 /// This is simply an optimized version of BLOCK_LAYOUT_BYTES for
798 /// when the required skip quantity is a multiple of the pointer size.
799 BLOCK_LAYOUT_NON_OBJECT_WORDS = 2,
800
801 /// The next I+1 words are __strong pointers to Objective-C
802 /// objects or blocks.
803 BLOCK_LAYOUT_STRONG = 3,
804
805 /// The next I+1 words are pointers to __block variables.
806 BLOCK_LAYOUT_BYREF = 4,
807
808 /// The next I+1 words are __weak pointers to Objective-C
809 /// objects or blocks.
810 BLOCK_LAYOUT_WEAK = 5,
811
812 /// The next I+1 words are __unsafe_unretained pointers to
813 /// Objective-C objects or blocks.
814 BLOCK_LAYOUT_UNRETAINED = 6
815
816 /// The next I+1 words are block or object pointers with some
817 /// as-yet-unspecified ownership semantics. If we add more
818 /// flavors of ownership semantics, values will be taken from
819 /// this range.
820 ///
821 /// This is included so that older tools can at least continue
822 /// processing the layout past such things.
823 //BLOCK_LAYOUT_OWNERSHIP_UNKNOWN = 7..10,
824
825 /// All other opcodes are reserved. Halt interpretation and
826 /// treat everything else as opaque.
827 };
828
829 class RUN_SKIP {
830 public:
831 enum BLOCK_LAYOUT_OPCODE opcode;
832 CharUnits block_var_bytepos;
833 CharUnits block_var_size;
834 RUN_SKIP(enum BLOCK_LAYOUT_OPCODE Opcode = BLOCK_LAYOUT_OPERATOR,
835 CharUnits BytePos = CharUnits::Zero(),
836 CharUnits Size = CharUnits::Zero())
837 : opcode(Opcode), block_var_bytepos(BytePos), block_var_size(Size) {}
838
839 // Allow sorting based on byte pos.
840 bool operator<(const RUN_SKIP &b) const {
841 return block_var_bytepos < b.block_var_bytepos;
842 }
843 };
844
845protected:
846 llvm::LLVMContext &VMContext;
847 // FIXME! May not be needing this after all.
848 unsigned ObjCABI;
849
850 // arc/mrr layout of captured block literal variables.
851 SmallVector<RUN_SKIP, 16> RunSkipBlockVars;
852
853 /// LazySymbols - Symbols to generate a lazy reference for. See
854 /// DefinedSymbols and FinishModule().
855 llvm::SetVector<IdentifierInfo*> LazySymbols;
856
857 /// DefinedSymbols - External symbols which are defined by this
858 /// module. The symbols in this list and LazySymbols are used to add
859 /// special linker symbols which ensure that Objective-C modules are
860 /// linked properly.
861 llvm::SetVector<IdentifierInfo*> DefinedSymbols;
862
863 /// ClassNames - uniqued class names.
864 llvm::StringMap<llvm::GlobalVariable*> ClassNames;
865
866 /// MethodVarNames - uniqued method variable names.
867 llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
868
869 /// DefinedCategoryNames - list of category names in form Class_Category.
870 llvm::SmallSetVector<llvm::CachedHashString, 16> DefinedCategoryNames;
871
872 /// MethodVarTypes - uniqued method type signatures. We have to use
873 /// a StringMap here because have no other unique reference.
874 llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
875
876 /// MethodDefinitions - map of methods which have been defined in
877 /// this translation unit.
878 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
879
880 /// DirectMethodDefinitions - map of direct methods which have been defined in
881 /// this translation unit.
882 llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> DirectMethodDefinitions;
883
884 /// PropertyNames - uniqued method variable names.
885 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
886
887 /// ClassReferences - uniqued class references.
888 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
889
890 /// SelectorReferences - uniqued selector references.
891 llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
892
893 /// Protocols - Protocols for which an objc_protocol structure has
894 /// been emitted. Forward declarations are handled by creating an
895 /// empty structure whose initializer is filled in when/if defined.
896 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
897
898 /// DefinedProtocols - Protocols which have actually been
899 /// defined. We should not need this, see FIXME in GenerateProtocol.
900 llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
901
902 /// DefinedClasses - List of defined classes.
903 SmallVector<llvm::GlobalValue*, 16> DefinedClasses;
904
905 /// ImplementedClasses - List of @implemented classes.
906 SmallVector<const ObjCInterfaceDecl*, 16> ImplementedClasses;
907
908 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
909 SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyClasses;
910
911 /// DefinedCategories - List of defined categories.
912 SmallVector<llvm::GlobalValue*, 16> DefinedCategories;
913
914 /// DefinedStubCategories - List of defined categories on class stubs.
915 SmallVector<llvm::GlobalValue*, 16> DefinedStubCategories;
916
917 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
918 SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyCategories;
919
920 /// Cached reference to the class for constant strings. This value has type
921 /// int * but is actually an Obj-C class pointer.
922 llvm::WeakTrackingVH ConstantStringClassRef;
923
924 /// The LLVM type corresponding to NSConstantString.
925 llvm::StructType *NSConstantStringType = nullptr;
926
927 llvm::StringMap<llvm::GlobalVariable *> NSConstantStringMap;
928
929 /// GetMethodVarName - Return a unique constant for the given
930 /// selector's name. The return value has type char *.
931 llvm::Constant *GetMethodVarName(Selector Sel);
932 llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
933
934 /// GetMethodVarType - Return a unique constant for the given
935 /// method's type encoding string. The return value has type char *.
936
937 // FIXME: This is a horrible name.
938 llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D,
939 bool Extended = false);
940 llvm::Constant *GetMethodVarType(const FieldDecl *D);
941
942 /// GetPropertyName - Return a unique constant for the given
943 /// name. The return value has type char *.
944 llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
945
946 // FIXME: This can be dropped once string functions are unified.
947 llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
948 const Decl *Container);
949
950 /// GetClassName - Return a unique constant for the given selector's
951 /// runtime name (which may change via use of objc_runtime_name attribute on
952 /// class or protocol definition. The return value has type char *.
953 llvm::Constant *GetClassName(StringRef RuntimeName);
954
955 llvm::Function *GetMethodDefinition(const ObjCMethodDecl *MD);
956
957 /// BuildIvarLayout - Builds ivar layout bitmap for the class
958 /// implementation for the __strong or __weak case.
959 ///
960 /// \param hasMRCWeakIvars - Whether we are compiling in MRC and there
961 /// are any weak ivars defined directly in the class. Meaningless unless
962 /// building a weak layout. Does not guarantee that the layout will
963 /// actually have any entries, because the ivar might be under-aligned.
964 llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
965 CharUnits beginOffset,
966 CharUnits endOffset,
967 bool forStrongLayout,
968 bool hasMRCWeakIvars);
969
970 llvm::Constant *BuildStrongIvarLayout(const ObjCImplementationDecl *OI,
971 CharUnits beginOffset,
972 CharUnits endOffset) {
973 return BuildIvarLayout(OI, beginOffset, endOffset, true, false);
974 }
975
976 llvm::Constant *BuildWeakIvarLayout(const ObjCImplementationDecl *OI,
977 CharUnits beginOffset,
978 CharUnits endOffset,
979 bool hasMRCWeakIvars) {
980 return BuildIvarLayout(OI, beginOffset, endOffset, false, hasMRCWeakIvars);
981 }
982
983 Qualifiers::ObjCLifetime getBlockCaptureLifetime(QualType QT, bool ByrefLayout);
984
985 void UpdateRunSkipBlockVars(bool IsByref,
986 Qualifiers::ObjCLifetime LifeTime,
987 CharUnits FieldOffset,
988 CharUnits FieldSize);
989
990 void BuildRCBlockVarRecordLayout(const RecordType *RT,
991 CharUnits BytePos, bool &HasUnion,
992 bool ByrefLayout=false);
993
994 void BuildRCRecordLayout(const llvm::StructLayout *RecLayout,
995 const RecordDecl *RD,
996 ArrayRef<const FieldDecl*> RecFields,
997 CharUnits BytePos, bool &HasUnion,
998 bool ByrefLayout);
999
1000 uint64_t InlineLayoutInstruction(SmallVectorImpl<unsigned char> &Layout);
1001
1002 llvm::Constant *getBitmapBlockLayout(bool ComputeByrefLayout);
1003
1004 /// GetIvarLayoutName - Returns a unique constant for the given
1005 /// ivar layout bitmap.
1006 llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
1007 const ObjCCommonTypesHelper &ObjCTypes);
1008
1009 /// EmitPropertyList - Emit the given property list. The return
1010 /// value has type PropertyListPtrTy.
1011 llvm::Constant *EmitPropertyList(Twine Name,
1012 const Decl *Container,
1013 const ObjCContainerDecl *OCD,
1014 const ObjCCommonTypesHelper &ObjCTypes,
1015 bool IsClassProperty);
1016
1017 /// EmitProtocolMethodTypes - Generate the array of extended method type
1018 /// strings. The return value has type Int8PtrPtrTy.
1019 llvm::Constant *EmitProtocolMethodTypes(Twine Name,
1020 ArrayRef<llvm::Constant*> MethodTypes,
1021 const ObjCCommonTypesHelper &ObjCTypes);
1022
1023 /// GetProtocolRef - Return a reference to the internal protocol
1024 /// description, creating an empty one if it has not been
1025 /// defined. The return value has type ProtocolPtrTy.
1026 llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
1027
1028 /// Return a reference to the given Class using runtime calls rather than
1029 /// by a symbol reference.
1030 llvm::Value *EmitClassRefViaRuntime(CodeGenFunction &CGF,
1031 const ObjCInterfaceDecl *ID,
1032 ObjCCommonTypesHelper &ObjCTypes);
1033
1034 std::string GetSectionName(StringRef Section, StringRef MachOAttributes);
1035
1036public:
1037 /// CreateMetadataVar - Create a global variable with internal
1038 /// linkage for use by the Objective-C runtime.
1039 ///
1040 /// This is a convenience wrapper which not only creates the
1041 /// variable, but also sets the section and alignment and adds the
1042 /// global to the "llvm.used" list.
1043 ///
1044 /// \param Name - The variable name.
1045 /// \param Init - The variable initializer; this is also used to
1046 /// define the type of the variable.
1047 /// \param Section - The section the variable should go into, or empty.
1048 /// \param Align - The alignment for the variable, or 0.
1049 /// \param AddToUsed - Whether the variable should be added to
1050 /// "llvm.used".
1051 llvm::GlobalVariable *CreateMetadataVar(Twine Name,
1052 ConstantStructBuilder &Init,
1053 StringRef Section, CharUnits Align,
1054 bool AddToUsed);
1055 llvm::GlobalVariable *CreateMetadataVar(Twine Name,
1056 llvm::Constant *Init,
1057 StringRef Section, CharUnits Align,
1058 bool AddToUsed);
1059
1060 llvm::GlobalVariable *CreateCStringLiteral(StringRef Name,
1061 ObjCLabelType LabelType,
1062 bool ForceNonFragileABI = false,
1063 bool NullTerminate = true);
1064
1065protected:
1066 CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1067 ReturnValueSlot Return,
1068 QualType ResultType,
1069 Selector Sel,
1070 llvm::Value *Arg0,
1071 QualType Arg0Ty,
1072 bool IsSuper,
1073 const CallArgList &CallArgs,
1074 const ObjCMethodDecl *OMD,
1075 const ObjCInterfaceDecl *ClassReceiver,
1076 const ObjCCommonTypesHelper &ObjCTypes);
1077
1078 /// EmitImageInfo - Emit the image info marker used to encode some module
1079 /// level information.
1080 void EmitImageInfo();
1081
1082public:
1083 CGObjCCommonMac(CodeGen::CodeGenModule &cgm)
1084 : CGObjCRuntime(cgm), VMContext(cgm.getLLVMContext()) {}
1085
1086 bool isNonFragileABI() const {
1087 return ObjCABI == 2;
1088 }
1089
1090 ConstantAddress GenerateConstantString(const StringLiteral *SL) override;
1091 ConstantAddress GenerateConstantNSString(const StringLiteral *SL);
1092
1093 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
1094 const ObjCContainerDecl *CD=nullptr) override;
1095
1096 llvm::Function *GenerateDirectMethod(const ObjCMethodDecl *OMD,
1097 const ObjCContainerDecl *CD);
1098
1099 void GenerateDirectMethodPrologue(CodeGenFunction &CGF, llvm::Function *Fn,
1100 const ObjCMethodDecl *OMD,
1101 const ObjCContainerDecl *CD) override;
1102
1103 void GenerateProtocol(const ObjCProtocolDecl *PD) override;
1104
1105 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1106 /// object for the given declaration, emitting it if needed. These
1107 /// forward references will be filled in with empty bodies if no
1108 /// definition is seen. The return value has type ProtocolPtrTy.
1109 virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
1110
1111 virtual llvm::Constant *getNSConstantStringClassRef() = 0;
1112
1113 llvm::Constant *BuildGCBlockLayout(CodeGen::CodeGenModule &CGM,
1114 const CGBlockInfo &blockInfo) override;
1115 llvm::Constant *BuildRCBlockLayout(CodeGen::CodeGenModule &CGM,
1116 const CGBlockInfo &blockInfo) override;
1117 std::string getRCBlockLayoutStr(CodeGen::CodeGenModule &CGM,
1118 const CGBlockInfo &blockInfo) override;
1119
1120 llvm::Constant *BuildByrefLayout(CodeGen::CodeGenModule &CGM,
1121 QualType T) override;
1122
1123private:
1124 void fillRunSkipBlockVars(CodeGenModule &CGM, const CGBlockInfo &blockInfo);
1125};
1126
1127namespace {
1128
1129enum class MethodListType {
1130 CategoryInstanceMethods,
1131 CategoryClassMethods,
1132 InstanceMethods,
1133 ClassMethods,
1134 ProtocolInstanceMethods,
1135 ProtocolClassMethods,
1136 OptionalProtocolInstanceMethods,
1137 OptionalProtocolClassMethods,
1138};
1139
1140/// A convenience class for splitting the methods of a protocol into
1141/// the four interesting groups.
1142class ProtocolMethodLists {
1143public:
1144 enum Kind {
1145 RequiredInstanceMethods,
1146 RequiredClassMethods,
1147 OptionalInstanceMethods,
1148 OptionalClassMethods
1149 };
1150 enum {
1151 NumProtocolMethodLists = 4
1152 };
1153
1154 static MethodListType getMethodListKind(Kind kind) {
1155 switch (kind) {
1156 case RequiredInstanceMethods:
1157 return MethodListType::ProtocolInstanceMethods;
1158 case RequiredClassMethods:
1159 return MethodListType::ProtocolClassMethods;
1160 case OptionalInstanceMethods:
1161 return MethodListType::OptionalProtocolInstanceMethods;
1162 case OptionalClassMethods:
1163 return MethodListType::OptionalProtocolClassMethods;
1164 }
1165 llvm_unreachable("bad kind");
1166 }
1167
1168 SmallVector<const ObjCMethodDecl *, 4> Methods[NumProtocolMethodLists];
1169
1170 static ProtocolMethodLists get(const ObjCProtocolDecl *PD) {
1171 ProtocolMethodLists result;
1172
1173 for (auto MD : PD->methods()) {
1174 size_t index = (2 * size_t(MD->isOptional()))
1175 + (size_t(MD->isClassMethod()));
1176 result.Methods[index].push_back(MD);
1177 }
1178
1179 return result;
1180 }
1181
1182 template <class Self>
1183 SmallVector<llvm::Constant*, 8> emitExtendedTypesArray(Self *self) const {
1184 // In both ABIs, the method types list is parallel with the
1185 // concatenation of the methods arrays in the following order:
1186 // instance methods
1187 // class methods
1188 // optional instance methods
1189 // optional class methods
1190 SmallVector<llvm::Constant*, 8> result;
1191
1192 // Methods is already in the correct order for both ABIs.
1193 for (auto &list : Methods) {
1194 for (auto MD : list) {
1195 result.push_back(self->GetMethodVarType(MD, true));
1196 }
1197 }
1198
1199 return result;
1200 }
1201
1202 template <class Self>
1203 llvm::Constant *emitMethodList(Self *self, const ObjCProtocolDecl *PD,
1204 Kind kind) const {
1205 return self->emitMethodList(PD->getObjCRuntimeNameAsString(),
1206 getMethodListKind(kind), Methods[kind]);
1207 }
1208};
1209
1210} // end anonymous namespace
1211
1212class CGObjCMac : public CGObjCCommonMac {
1213private:
1214 friend ProtocolMethodLists;
1215
1216 ObjCTypesHelper ObjCTypes;
1217
1218 /// EmitModuleInfo - Another marker encoding module level
1219 /// information.
1220 void EmitModuleInfo();
1221
1222 /// EmitModuleSymols - Emit module symbols, the list of defined
1223 /// classes and categories. The result has type SymtabPtrTy.
1224 llvm::Constant *EmitModuleSymbols();
1225
1226 /// FinishModule - Write out global data structures at the end of
1227 /// processing a translation unit.
1228 void FinishModule();
1229
1230 /// EmitClassExtension - Generate the class extension structure used
1231 /// to store the weak ivar layout and properties. The return value
1232 /// has type ClassExtensionPtrTy.
1233 llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID,
1234 CharUnits instanceSize,
1235 bool hasMRCWeakIvars,
1236 bool isMetaclass);
1237
1238 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1239 /// for the given class.
1240 llvm::Value *EmitClassRef(CodeGenFunction &CGF,
1241 const ObjCInterfaceDecl *ID);
1242
1243 llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF,
1244 IdentifierInfo *II);
1245
1246 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
1247
1248 /// EmitSuperClassRef - Emits reference to class's main metadata class.
1249 llvm::Value *EmitSuperClassRef(const ObjCInterfaceDecl *ID);
1250
1251 /// EmitIvarList - Emit the ivar list for the given
1252 /// implementation. If ForClass is true the list of class ivars
1253 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1254 /// interface ivars will be emitted. The return value has type
1255 /// IvarListPtrTy.
1256 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
1257 bool ForClass);
1258
1259 /// EmitMetaClass - Emit a forward reference to the class structure
1260 /// for the metaclass of the given interface. The return value has
1261 /// type ClassPtrTy.
1262 llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
1263
1264 /// EmitMetaClass - Emit a class structure for the metaclass of the
1265 /// given implementation. The return value has type ClassPtrTy.
1266 llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
1267 llvm::Constant *Protocols,
1268 ArrayRef<const ObjCMethodDecl *> Methods);
1269
1270 void emitMethodConstant(ConstantArrayBuilder &builder,
1271 const ObjCMethodDecl *MD);
1272
1273 void emitMethodDescriptionConstant(ConstantArrayBuilder &builder,
1274 const ObjCMethodDecl *MD);
1275
1276 /// EmitMethodList - Emit the method list for the given
1277 /// implementation. The return value has type MethodListPtrTy.
1278 llvm::Constant *emitMethodList(Twine Name, MethodListType MLT,
1279 ArrayRef<const ObjCMethodDecl *> Methods);
1280
1281 /// GetOrEmitProtocol - Get the protocol object for the given
1282 /// declaration, emitting it if necessary. The return value has type
1283 /// ProtocolPtrTy.
1284 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override;
1285
1286 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1287 /// object for the given declaration, emitting it if needed. These
1288 /// forward references will be filled in with empty bodies if no
1289 /// definition is seen. The return value has type ProtocolPtrTy.
1290 llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) override;
1291
1292 /// EmitProtocolExtension - Generate the protocol extension
1293 /// structure used to store optional instance and class methods, and
1294 /// protocol properties. The return value has type
1295 /// ProtocolExtensionPtrTy.
1296 llvm::Constant *
1297 EmitProtocolExtension(const ObjCProtocolDecl *PD,
1298 const ProtocolMethodLists &methodLists);
1299
1300 /// EmitProtocolList - Generate the list of referenced
1301 /// protocols. The return value has type ProtocolListPtrTy.
1302 llvm::Constant *EmitProtocolList(Twine Name,
1303 ObjCProtocolDecl::protocol_iterator begin,
1304 ObjCProtocolDecl::protocol_iterator end);
1305
1306 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1307 /// for the given selector.
1308 llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel);
1309 Address EmitSelectorAddr(Selector Sel);
1310
1311public:
1312 CGObjCMac(CodeGen::CodeGenModule &cgm);
1313
1314 llvm::Constant *getNSConstantStringClassRef() override;
1315
1316 llvm::Function *ModuleInitFunction() override;
1317
1318 CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1319 ReturnValueSlot Return,
1320 QualType ResultType,
1321 Selector Sel, llvm::Value *Receiver,
1322 const CallArgList &CallArgs,
1323 const ObjCInterfaceDecl *Class,
1324 const ObjCMethodDecl *Method) override;
1325
1326 CodeGen::RValue
1327 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1328 ReturnValueSlot Return, QualType ResultType,
1329 Selector Sel, const ObjCInterfaceDecl *Class,
1330 bool isCategoryImpl, llvm::Value *Receiver,
1331 bool IsClassMessage, const CallArgList &CallArgs,
1332 const ObjCMethodDecl *Method) override;
1333
1334 llvm::Value *GetClass(CodeGenFunction &CGF,
1335 const ObjCInterfaceDecl *ID) override;
1336
1337 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
1338 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
1339
1340 /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1341 /// untyped one.
1342 llvm::Value *GetSelector(CodeGenFunction &CGF,
1343 const ObjCMethodDecl *Method) override;
1344
1345 llvm::Constant *GetEHType(QualType T) override;
1346
1347 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
1348
1349 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
1350
1351 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override {}
1352
1353 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1354 const ObjCProtocolDecl *PD) override;
1355
1356 llvm::FunctionCallee GetPropertyGetFunction() override;
1357 llvm::FunctionCallee GetPropertySetFunction() override;
1358 llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
1359 bool copy) override;
1360 llvm::FunctionCallee GetGetStructFunction() override;
1361 llvm::FunctionCallee GetSetStructFunction() override;
1362 llvm::FunctionCallee GetCppAtomicObjectGetFunction() override;
1363 llvm::FunctionCallee GetCppAtomicObjectSetFunction() override;
1364 llvm::FunctionCallee EnumerationMutationFunction() override;
1365
1366 void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
1367 const ObjCAtTryStmt &S) override;
1368 void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1369 const ObjCAtSynchronizedStmt &S) override;
1370 void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const Stmt &S);
1371 void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S,
1372 bool ClearInsertionPoint=true) override;
1373 llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
1374 Address AddrWeakObj) override;
1375 void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1376 llvm::Value *src, Address dst) override;
1377 void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1378 llvm::Value *src, Address dest,
1379 bool threadlocal = false) override;
1380 void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1381 llvm::Value *src, Address dest,
1382 llvm::Value *ivarOffset) override;
1383 void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1384 llvm::Value *src, Address dest) override;
1385 void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
1386 Address dest, Address src,
1387 llvm::Value *size) override;
1388
1389 LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy,
1390 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
1391 unsigned CVRQualifiers) override;
1392 llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
1393 const ObjCInterfaceDecl *Interface,
1394 const ObjCIvarDecl *Ivar) override;
1395};
1396
1397class CGObjCNonFragileABIMac : public CGObjCCommonMac {
1398private:
1399 friend ProtocolMethodLists;
1400 ObjCNonFragileABITypesHelper ObjCTypes;
1401 llvm::GlobalVariable* ObjCEmptyCacheVar;
1402 llvm::Constant* ObjCEmptyVtableVar;
1403
1404 /// SuperClassReferences - uniqued super class references.
1405 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
1406
1407 /// MetaClassReferences - uniqued meta class references.
1408 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
1409
1410 /// EHTypeReferences - uniqued class ehtype references.
1411 llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
1412
1413 /// VTableDispatchMethods - List of methods for which we generate
1414 /// vtable-based message dispatch.
1415 llvm::DenseSet<Selector> VTableDispatchMethods;
1416
1417 /// DefinedMetaClasses - List of defined meta-classes.
1418 std::vector<llvm::GlobalValue*> DefinedMetaClasses;
1419
1420 /// isVTableDispatchedSelector - Returns true if SEL is a
1421 /// vtable-based selector.
1422 bool isVTableDispatchedSelector(Selector Sel);
1423
1424 /// FinishNonFragileABIModule - Write out global data structures at the end of
1425 /// processing a translation unit.
1426 void FinishNonFragileABIModule();
1427
1428 /// AddModuleClassList - Add the given list of class pointers to the
1429 /// module with the provided symbol and section names.
1430 void AddModuleClassList(ArrayRef<llvm::GlobalValue *> Container,
1431 StringRef SymbolName, StringRef SectionName);
1432
1433 llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1434 unsigned InstanceStart,
1435 unsigned InstanceSize,
1436 const ObjCImplementationDecl *ID);
1437 llvm::GlobalVariable *BuildClassObject(const ObjCInterfaceDecl *CI,
1438 bool isMetaclass,
1439 llvm::Constant *IsAGV,
1440 llvm::Constant *SuperClassGV,
1441 llvm::Constant *ClassRoGV,
1442 bool HiddenVisibility);
1443
1444 void emitMethodConstant(ConstantArrayBuilder &builder,
1445 const ObjCMethodDecl *MD,
1446 bool forProtocol);
1447
1448 /// Emit the method list for the given implementation. The return value
1449 /// has type MethodListnfABITy.
1450 llvm::Constant *emitMethodList(Twine Name, MethodListType MLT,
1451 ArrayRef<const ObjCMethodDecl *> Methods);
1452
1453 /// EmitIvarList - Emit the ivar list for the given
1454 /// implementation. If ForClass is true the list of class ivars
1455 /// (i.e. metaclass ivars) is emitted, otherwise the list of
1456 /// interface ivars will be emitted. The return value has type
1457 /// IvarListnfABIPtrTy.
1458 llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
1459
1460 llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
1461 const ObjCIvarDecl *Ivar,
1462 unsigned long int offset);
1463
1464 /// GetOrEmitProtocol - Get the protocol object for the given
1465 /// declaration, emitting it if necessary. The return value has type
1466 /// ProtocolPtrTy.
1467 llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override;
1468
1469 /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1470 /// object for the given declaration, emitting it if needed. These
1471 /// forward references will be filled in with empty bodies if no
1472 /// definition is seen. The return value has type ProtocolPtrTy.
1473 llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) override;
1474
1475 /// EmitProtocolList - Generate the list of referenced
1476 /// protocols. The return value has type ProtocolListPtrTy.
1477 llvm::Constant *EmitProtocolList(Twine Name,
1478 ObjCProtocolDecl::protocol_iterator begin,
1479 ObjCProtocolDecl::protocol_iterator end);
1480
1481 CodeGen::RValue EmitVTableMessageSend(CodeGen::CodeGenFunction &CGF,
1482 ReturnValueSlot Return,
1483 QualType ResultType,
1484 Selector Sel,
1485 llvm::Value *Receiver,
1486 QualType Arg0Ty,
1487 bool IsSuper,
1488 const CallArgList &CallArgs,
1489 const ObjCMethodDecl *Method);
1490
1491 /// GetClassGlobal - Return the global variable for the Objective-C
1492 /// class of the given name.
1493 llvm::Constant *GetClassGlobal(StringRef Name,
1494 ForDefinition_t IsForDefinition,
1495 bool Weak = false, bool DLLImport = false);
1496 llvm::Constant *GetClassGlobal(const ObjCInterfaceDecl *ID,
1497 bool isMetaclass,
1498 ForDefinition_t isForDefinition);
1499
1500 llvm::Constant *GetClassGlobalForClassRef(const ObjCInterfaceDecl *ID);
1501
1502 llvm::Value *EmitLoadOfClassRef(CodeGenFunction &CGF,
1503 const ObjCInterfaceDecl *ID,
1504 llvm::GlobalVariable *Entry);
1505
1506 /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1507 /// for the given class reference.
1508 llvm::Value *EmitClassRef(CodeGenFunction &CGF,
1509 const ObjCInterfaceDecl *ID);
1510
1511 llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF,
1512 IdentifierInfo *II,
1513 const ObjCInterfaceDecl *ID);
1514
1515 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
1516
1517 /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1518 /// for the given super class reference.
1519 llvm::Value *EmitSuperClassRef(CodeGenFunction &CGF,
1520 const ObjCInterfaceDecl *ID);
1521
1522 /// EmitMetaClassRef - Return a Value * of the address of _class_t
1523 /// meta-data
1524 llvm::Value *EmitMetaClassRef(CodeGenFunction &CGF,
1525 const ObjCInterfaceDecl *ID, bool Weak);
1526
1527 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1528 /// the given ivar.
1529 ///
1530 llvm::GlobalVariable * ObjCIvarOffsetVariable(
1531 const ObjCInterfaceDecl *ID,
1532 const ObjCIvarDecl *Ivar);
1533
1534 /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1535 /// for the given selector.
1536 llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel);
1537 Address EmitSelectorAddr(Selector Sel);
1538
1539 /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
1540 /// interface. The return value has type EHTypePtrTy.
1541 llvm::Constant *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1542 ForDefinition_t IsForDefinition);
1543
1544 StringRef getMetaclassSymbolPrefix() const { return "OBJC_METACLASS_$_"; }
1545
1546 StringRef getClassSymbolPrefix() const { return "OBJC_CLASS_$_"; }
1547
1548 void GetClassSizeInfo(const ObjCImplementationDecl *OID,
1549 uint32_t &InstanceStart,
1550 uint32_t &InstanceSize);
1551
1552 // Shamelessly stolen from Analysis/CFRefCount.cpp
1553 Selector GetNullarySelector(const char* name) const {
1554 IdentifierInfo* II = &CGM.getContext().Idents.get(name);
1555 return CGM.getContext().Selectors.getSelector(0, &II);
1556 }
1557
1558 Selector GetUnarySelector(const char* name) const {
1559 IdentifierInfo* II = &CGM.getContext().Idents.get(name);
1560 return CGM.getContext().Selectors.getSelector(1, &II);
1561 }
1562
1563 /// ImplementationIsNonLazy - Check whether the given category or
1564 /// class implementation is "non-lazy".
1565 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const;
1566
1567 bool IsIvarOffsetKnownIdempotent(const CodeGen::CodeGenFunction &CGF,
1568 const ObjCIvarDecl *IV) {
1569 // Annotate the load as an invariant load iff inside an instance method
1570 // and ivar belongs to instance method's class and one of its super class.
1571 // This check is needed because the ivar offset is a lazily
1572 // initialised value that may depend on objc_msgSend to perform a fixup on
1573 // the first message dispatch.
1574 //
1575 // An additional opportunity to mark the load as invariant arises when the
1576 // base of the ivar access is a parameter to an Objective C method.
1577 // However, because the parameters are not available in the current
1578 // interface, we cannot perform this check.
1579 //
1580 // Note that for direct methods, because objc_msgSend is skipped,
1581 // and that the method may be inlined, this optimization actually
1582 // can't be performed.
1583 if (const ObjCMethodDecl *MD =
1584 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurFuncDecl))
1585 if (MD->isInstanceMethod() && !MD->isDirectMethod())
1586 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
1587 return IV->getContainingInterface()->isSuperClassOf(ID);
1588 return false;
1589 }
1590
1591 bool isClassLayoutKnownStatically(const ObjCInterfaceDecl *ID) {
1592 // NSObject is a fixed size. If we can see the @implementation of a class
1593 // which inherits from NSObject then we know that all it's offsets also must
1594 // be fixed. FIXME: Can we do this if see a chain of super classes with
1595 // implementations leading to NSObject?
1596 return ID->getImplementation() && ID->getSuperClass() &&
1597 ID->getSuperClass()->getName() == "NSObject";
1598 }
1599
1600public:
1601 CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
1602
1603 llvm::Constant *getNSConstantStringClassRef() override;
1604
1605 llvm::Function *ModuleInitFunction() override;
1606
1607 CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1608 ReturnValueSlot Return,
1609 QualType ResultType, Selector Sel,
1610 llvm::Value *Receiver,
1611 const CallArgList &CallArgs,
1612 const ObjCInterfaceDecl *Class,
1613 const ObjCMethodDecl *Method) override;
1614
1615 CodeGen::RValue
1616 GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1617 ReturnValueSlot Return, QualType ResultType,
1618 Selector Sel, const ObjCInterfaceDecl *Class,
1619 bool isCategoryImpl, llvm::Value *Receiver,
1620 bool IsClassMessage, const CallArgList &CallArgs,
1621 const ObjCMethodDecl *Method) override;
1622
1623 llvm::Value *GetClass(CodeGenFunction &CGF,
1624 const ObjCInterfaceDecl *ID) override;
1625
1626 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override
1627 { return EmitSelector(CGF, Sel); }
1628 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override
1629 { return EmitSelectorAddr(Sel); }
1630
1631 /// The NeXT/Apple runtimes do not support typed selectors; just emit an
1632 /// untyped one.
1633 llvm::Value *GetSelector(CodeGenFunction &CGF,
1634 const ObjCMethodDecl *Method) override
1635 { return EmitSelector(CGF, Method->getSelector()); }
1636
1637 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
1638
1639 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
1640
1641 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override {}
1642
1643 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1644 const ObjCProtocolDecl *PD) override;
1645
1646 llvm::Constant *GetEHType(QualType T) override;
1647
1648 llvm::FunctionCallee GetPropertyGetFunction() override {
1649 return ObjCTypes.getGetPropertyFn();
1650 }
1651 llvm::FunctionCallee GetPropertySetFunction() override {
1652 return ObjCTypes.getSetPropertyFn();
1653 }
1654
1655 llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
1656 bool copy) override {
1657 return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy);
1658 }
1659
1660 llvm::FunctionCallee GetSetStructFunction() override {
1661 return ObjCTypes.getCopyStructFn();
1662 }
1663
1664 llvm::FunctionCallee GetGetStructFunction() override {
1665 return ObjCTypes.getCopyStructFn();
1666 }
1667
1668 llvm::FunctionCallee GetCppAtomicObjectSetFunction() override {
1669 return ObjCTypes.getCppAtomicObjectFunction();
1670 }
1671
1672 llvm::FunctionCallee GetCppAtomicObjectGetFunction() override {
1673 return ObjCTypes.getCppAtomicObjectFunction();
1674 }
1675
1676 llvm::FunctionCallee EnumerationMutationFunction() override {
1677 return ObjCTypes.getEnumerationMutationFn();
1678 }
1679
1680 void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
1681 const ObjCAtTryStmt &S) override;
1682 void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1683 const ObjCAtSynchronizedStmt &S) override;
1684 void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S,
1685 bool ClearInsertionPoint=true) override;
1686 llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
1687 Address AddrWeakObj) override;
1688 void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1689 llvm::Value *src, Address edst) override;
1690 void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1691 llvm::Value *src, Address dest,
1692 bool threadlocal = false) override;
1693 void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1694 llvm::Value *src, Address dest,
1695 llvm::Value *ivarOffset) override;
1696 void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1697 llvm::Value *src, Address dest) override;
1698 void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
1699 Address dest, Address src,
1700 llvm::Value *size) override;
1701 LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy,
1702 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
1703 unsigned CVRQualifiers) override;
1704 llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
1705 const ObjCInterfaceDecl *Interface,
1706 const ObjCIvarDecl *Ivar) override;
1707};
1708
1709/// A helper class for performing the null-initialization of a return
1710/// value.
1711struct NullReturnState {
1712 llvm::BasicBlock *NullBB;
1713 NullReturnState() : NullBB(nullptr) {}
1714
1715 /// Perform a null-check of the given receiver.
1716 void init(CodeGenFunction &CGF, llvm::Value *receiver) {
1717 // Make blocks for the null-receiver and call edges.
1718 NullBB = CGF.createBasicBlock("msgSend.null-receiver");
1719 llvm::BasicBlock *callBB = CGF.createBasicBlock("msgSend.call");
1720
1721 // Check for a null receiver and, if there is one, jump to the
1722 // null-receiver block. There's no point in trying to avoid it:
1723 // we're always going to put *something* there, because otherwise
1724 // we shouldn't have done this null-check in the first place.
1725 llvm::Value *isNull = CGF.Builder.CreateIsNull(receiver);
1726 CGF.Builder.CreateCondBr(isNull, NullBB, callBB);
1727
1728 // Otherwise, start performing the call.
1729 CGF.EmitBlock(callBB);
1730 }
1731
1732 /// Complete the null-return operation. It is valid to call this
1733 /// regardless of whether 'init' has been called.
1734 RValue complete(CodeGenFunction &CGF,
1735 ReturnValueSlot returnSlot,
1736 RValue result,
1737 QualType resultType,
1738 const CallArgList &CallArgs,
1739 const ObjCMethodDecl *Method) {
1740 // If we never had to do a null-check, just use the raw result.
1741 if (!NullBB) return result;
1742
1743 // The continuation block. This will be left null if we don't have an
1744 // IP, which can happen if the method we're calling is marked noreturn.
1745 llvm::BasicBlock *contBB = nullptr;
1746
1747 // Finish the call path.
1748 llvm::BasicBlock *callBB = CGF.Builder.GetInsertBlock();
1749 if (callBB) {
1750 contBB = CGF.createBasicBlock("msgSend.cont");
1751 CGF.Builder.CreateBr(contBB);
1752 }
1753
1754 // Okay, start emitting the null-receiver block.
1755 CGF.EmitBlock(NullBB);
1756
1757 // Release any consumed arguments we've got.
1758 if (Method) {
1759 CallArgList::const_iterator I = CallArgs.begin();
1760 for (ObjCMethodDecl::param_const_iterator i = Method->param_begin(),
1761 e = Method->param_end(); i != e; ++i, ++I) {
1762 const ParmVarDecl *ParamDecl = (*i);
1763 if (ParamDecl->hasAttr<NSConsumedAttr>()) {
1764 RValue RV = I->getRValue(CGF);
1765 assert(RV.isScalar() &&
1766 "NullReturnState::complete - arg not on object");
1767 CGF.EmitARCRelease(RV.getScalarVal(), ARCImpreciseLifetime);
1768 } else {
1769 QualType QT = ParamDecl->getType();
1770 auto *RT = QT->getAs<RecordType>();
1771 if (RT && RT->getDecl()->isParamDestroyedInCallee()) {
1772 RValue RV = I->getRValue(CGF);
1773 QualType::DestructionKind DtorKind = QT.isDestructedType();
1774 switch (DtorKind) {
1775 case QualType::DK_cxx_destructor:
1776 CGF.destroyCXXObject(CGF, RV.getAggregateAddress(), QT);
1777 break;
1778 case QualType::DK_nontrivial_c_struct:
1779 CGF.destroyNonTrivialCStruct(CGF, RV.getAggregateAddress(), QT);
1780 break;
1781 default:
1782 llvm_unreachable("unexpected dtor kind");
1783 break;
1784 }
1785 }
1786 }
1787 }
1788 }
1789
1790 // The phi code below assumes that we haven't needed any control flow yet.
1791 assert(CGF.Builder.GetInsertBlock() == NullBB);
1792
1793 // If we've got a void return, just jump to the continuation block.
1794 if (result.isScalar() && resultType->isVoidType()) {
1795 // No jumps required if the message-send was noreturn.
1796 if (contBB) CGF.EmitBlock(contBB);
1797 return result;
1798 }
1799
1800 // If we've got a scalar return, build a phi.
1801 if (result.isScalar()) {
1802 // Derive the null-initialization value.
1803 llvm::Value *null =
1804 CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(resultType), resultType);
1805
1806 // If no join is necessary, just flow out.
1807 if (!contBB) return RValue::get(null);
1808
1809 // Otherwise, build a phi.
1810 CGF.EmitBlock(contBB);
1811 llvm::PHINode *phi = CGF.Builder.CreatePHI(null->getType(), 2);
1812 phi->addIncoming(result.getScalarVal(), callBB);
1813 phi->addIncoming(null, NullBB);
1814 return RValue::get(phi);
1815 }
1816
1817 // If we've got an aggregate return, null the buffer out.
1818 // FIXME: maybe we should be doing things differently for all the
1819 // cases where the ABI has us returning (1) non-agg values in
1820 // memory or (2) agg values in registers.
1821 if (result.isAggregate()) {
1822 assert(result.isAggregate() && "null init of non-aggregate result?");
1823 if (!returnSlot.isUnused())
1824 CGF.EmitNullInitialization(result.getAggregateAddress(), resultType);
1825 if (contBB) CGF.EmitBlock(contBB);
1826 return result;
1827 }
1828
1829 // Complex types.
1830 CGF.EmitBlock(contBB);
1831 CodeGenFunction::ComplexPairTy callResult = result.getComplexVal();
1832
1833 // Find the scalar type and its zero value.
1834 llvm::Type *scalarTy = callResult.first->getType();
1835 llvm::Constant *scalarZero = llvm::Constant::getNullValue(scalarTy);
1836
1837 // Build phis for both coordinates.
1838 llvm::PHINode *real = CGF.Builder.CreatePHI(scalarTy, 2);
1839 real->addIncoming(callResult.first, callBB);
1840 real->addIncoming(scalarZero, NullBB);
1841 llvm::PHINode *imag = CGF.Builder.CreatePHI(scalarTy, 2);
1842 imag->addIncoming(callResult.second, callBB);
1843 imag->addIncoming(scalarZero, NullBB);
1844 return RValue::getComplex(real, imag);
1845 }
1846};
1847
1848} // end anonymous namespace
1849
1850/* *** Helper Functions *** */
1851
1852/// getConstantGEP() - Help routine to construct simple GEPs.
1853static llvm::Constant *getConstantGEP(llvm::LLVMContext &VMContext,
1854 llvm::GlobalVariable *C, unsigned idx0,
1855 unsigned idx1) {
1856 llvm::Value *Idxs[] = {
1857 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx0),
1858 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx1)
1859 };
1860 return llvm::ConstantExpr::getGetElementPtr(C->getValueType(), C, Idxs);
1861}
1862
1863/// hasObjCExceptionAttribute - Return true if this class or any super
1864/// class has the __objc_exception__ attribute.
1865static bool hasObjCExceptionAttribute(ASTContext &Context,
1866 const ObjCInterfaceDecl *OID) {
1867 if (OID->hasAttr<ObjCExceptionAttr>())
1868 return true;
1869 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1870 return hasObjCExceptionAttribute(Context, Super);
1871 return false;
1872}
1873
1874static llvm::GlobalValue::LinkageTypes
1875getLinkageTypeForObjCMetadata(CodeGenModule &CGM, StringRef Section) {
1876 if (CGM.getTriple().isOSBinFormatMachO() &&
1877 (Section.empty() || Section.startswith("__DATA")))
1878 return llvm::GlobalValue::InternalLinkage;
1879 return llvm::GlobalValue::PrivateLinkage;
1880}
1881
1882/// A helper function to create an internal or private global variable.
1883static llvm::GlobalVariable *
1884finishAndCreateGlobal(ConstantInitBuilder::StructBuilder &Builder,
1885 const llvm::Twine &Name, CodeGenModule &CGM) {
1886 std::string SectionName;
1887 if (CGM.getTriple().isOSBinFormatMachO())
1888 SectionName = "__DATA, __objc_const";
1889 auto *GV = Builder.finishAndCreateGlobal(
1890 Name, CGM.getPointerAlign(), /*constant*/ false,
1891 getLinkageTypeForObjCMetadata(CGM, SectionName));
1892 GV->setSection(SectionName);
1893 return GV;
1894}
1895
1896/* *** CGObjCMac Public Interface *** */
1897
1898CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1899 ObjCTypes(cgm) {
1900 ObjCABI = 1;
1901 EmitImageInfo();
1902}
1903
1904/// GetClass - Return a reference to the class for the given interface
1905/// decl.
1906llvm::Value *CGObjCMac::GetClass(CodeGenFunction &CGF,
1907 const ObjCInterfaceDecl *ID) {
1908 return EmitClassRef(CGF, ID);
1909}
1910
1911/// GetSelector - Return the pointer to the unique'd string for this selector.
1912llvm::Value *CGObjCMac::GetSelector(CodeGenFunction &CGF, Selector Sel) {
1913 return EmitSelector(CGF, Sel);
1914}
1915Address CGObjCMac::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
1916 return EmitSelectorAddr(Sel);
1917}
1918llvm::Value *CGObjCMac::GetSelector(CodeGenFunction &CGF, const ObjCMethodDecl
1919 *Method) {
1920 return EmitSelector(CGF, Method->getSelector());
1921}
1922
1923llvm::Constant *CGObjCMac::GetEHType(QualType T) {
1924 if (T->isObjCIdType() ||
1925 T->isObjCQualifiedIdType()) {
1926 return CGM.GetAddrOfRTTIDescriptor(
1927 CGM.getContext().getObjCIdRedefinitionType(), /*ForEH=*/true);
1928 }
1929 if (T->isObjCClassType() ||
1930 T->isObjCQualifiedClassType()) {
1931 return CGM.GetAddrOfRTTIDescriptor(
1932 CGM.getContext().getObjCClassRedefinitionType(), /*ForEH=*/true);
1933 }
1934 if (T->isObjCObjectPointerType())
1935 return CGM.GetAddrOfRTTIDescriptor(T, /*ForEH=*/true);
1936
1937 llvm_unreachable("asking for catch type for ObjC type in fragile runtime");
1938}
1939
1940/// Generate a constant CFString object.
1941/*
1942 struct __builtin_CFString {
1943 const int *isa; // point to __CFConstantStringClassReference
1944 int flags;
1945 const char *str;
1946 long length;
1947 };
1948*/
1949
1950/// or Generate a constant NSString object.
1951/*
1952 struct __builtin_NSString {
1953 const int *isa; // point to __NSConstantStringClassReference
1954 const char *str;
1955 unsigned int length;
1956 };
1957*/
1958
1959ConstantAddress
1960CGObjCCommonMac::GenerateConstantString(const StringLiteral *SL) {
1961 return (!CGM.getLangOpts().NoConstantCFStrings
1962 ? CGM.GetAddrOfConstantCFString(SL)
1963 : GenerateConstantNSString(SL));
1964}
1965
1966static llvm::StringMapEntry<llvm::GlobalVariable *> &
1967GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
1968 const StringLiteral *Literal, unsigned &StringLength) {
1969 StringRef String = Literal->getString();
1970 StringLength = String.size();
1971 return *Map.insert(std::make_pair(String, nullptr)).first;
1972}
1973
1974llvm::Constant *CGObjCMac::getNSConstantStringClassRef() {
1975 if (llvm::Value *V = ConstantStringClassRef)
1976 return cast<llvm::Constant>(V);
1977
1978 auto &StringClass = CGM.getLangOpts().ObjCConstantStringClass;
1979 std::string str =
1980 StringClass.empty() ? "_NSConstantStringClassReference"
1981 : "_" + StringClass + "ClassReference";
1982
1983 llvm::Type *PTy = llvm::ArrayType::get(CGM.IntTy, 0);
1984 auto GV = CGM.CreateRuntimeVariable(PTy, str);
1985 auto V = llvm::ConstantExpr::getBitCast(GV, CGM.IntTy->getPointerTo());
1986 ConstantStringClassRef = V;
1987 return V;
1988}
1989
1990llvm::Constant *CGObjCNonFragileABIMac::getNSConstantStringClassRef() {
1991 if (llvm::Value *V = ConstantStringClassRef)
1992 return cast<llvm::Constant>(V);
1993
1994 auto &StringClass = CGM.getLangOpts().ObjCConstantStringClass;
1995 std::string str =
1996 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
1997 : "OBJC_CLASS_$_" + StringClass;
1998 llvm::Constant *GV = GetClassGlobal(str, NotForDefinition);
1999
2000 // Make sure the result is of the correct type.
2001 auto V = llvm::ConstantExpr::getBitCast(GV, CGM.IntTy->getPointerTo());
2002
2003 ConstantStringClassRef = V;
2004 return V;
2005}
2006
2007ConstantAddress
2008CGObjCCommonMac::GenerateConstantNSString(const StringLiteral *Literal) {
2009 unsigned StringLength = 0;
2010 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2011 GetConstantStringEntry(NSConstantStringMap, Literal, StringLength);
2012
2013 if (auto *C = Entry.second)
2014 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
2015
2016 // If we don't already have it, get _NSConstantStringClassReference.
2017 llvm::Constant *Class = getNSConstantStringClassRef();
2018
2019 // If we don't already have it, construct the type for a constant NSString.
2020 if (!NSConstantStringType) {
2021 NSConstantStringType =
2022 llvm::StructType::create({
2023 CGM.Int32Ty->getPointerTo(),
2024 CGM.Int8PtrTy,
2025 CGM.IntTy
2026 }, "struct.__builtin_NSString");
2027 }
2028
2029 ConstantInitBuilder Builder(CGM);
2030 auto Fields = Builder.beginStruct(NSConstantStringType);
2031
2032 // Class pointer.
2033 Fields.add(Class);
2034
2035 // String pointer.
2036 llvm::Constant *C =
2037 llvm::ConstantDataArray::getString(VMContext, Entry.first());
2038
2039 llvm::GlobalValue::LinkageTypes Linkage = llvm::GlobalValue::PrivateLinkage;
2040 bool isConstant = !CGM.getLangOpts().WritableStrings;
2041
2042 auto *GV = new llvm::GlobalVariable(CGM.getModule(), C->getType(), isConstant,
2043 Linkage, C, ".str");
2044 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2045 // Don't enforce the target's minimum global alignment, since the only use
2046 // of the string is via this class initializer.
2047 GV->setAlignment(llvm::Align(1));
2048 Fields.addBitCast(GV, CGM.Int8PtrTy);
2049
2050 // String length.
2051 Fields.addInt(CGM.IntTy, StringLength);
2052
2053 // The struct.
2054 CharUnits Alignment = CGM.getPointerAlign();
2055 GV = Fields.finishAndCreateGlobal("_unnamed_nsstring_", Alignment,
2056 /*constant*/ true,
2057 llvm::GlobalVariable::PrivateLinkage);
2058 const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
2059 const char *NSStringNonFragileABISection =
2060 "__DATA,__objc_stringobj,regular,no_dead_strip";
2061 // FIXME. Fix section.
2062 GV->setSection(CGM.getLangOpts().ObjCRuntime.isNonFragile()
2063 ? NSStringNonFragileABISection
2064 : NSStringSection);
2065 Entry.second = GV;
2066
2067 return ConstantAddress(GV, Alignment);
2068}
2069
2070enum {
2071 kCFTaggedObjectID_Integer = (1 << 1) + 1
2072};
2073
2074/// Generates a message send where the super is the receiver. This is
2075/// a message send to self with special delivery semantics indicating
2076/// which class's method should be called.
2077CodeGen::RValue
2078CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
2079 ReturnValueSlot Return,
2080 QualType ResultType,
2081 Selector Sel,
2082 const ObjCInterfaceDecl *Class,
2083 bool isCategoryImpl,
2084 llvm::Value *Receiver,
2085 bool IsClassMessage,
2086 const CodeGen::CallArgList &CallArgs,
2087 const ObjCMethodDecl *Method) {
2088 // Create and init a super structure; this is a (receiver, class)
2089 // pair we will pass to objc_msgSendSuper.
2090 Address ObjCSuper =
2091 CGF.CreateTempAlloca(ObjCTypes.SuperTy, CGF.getPointerAlign(),
2092 "objc_super");
2093 llvm::Value *ReceiverAsObject =
2094 CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
2095 CGF.Builder.CreateStore(ReceiverAsObject,
2096 CGF.Builder.CreateStructGEP(ObjCSuper, 0));
2097
2098 // If this is a class message the metaclass is passed as the target.
2099 llvm::Type *ClassTyPtr = llvm::PointerType::getUnqual(ObjCTypes.ClassTy);
2100 llvm::Value *Target;
2101 if (IsClassMessage) {
2102 if (isCategoryImpl) {
2103 // Message sent to 'super' in a class method defined in a category
2104 // implementation requires an odd treatment.
2105 // If we are in a class method, we must retrieve the
2106 // _metaclass_ for the current class, pointed at by
2107 // the class's "isa" pointer. The following assumes that
2108 // isa" is the first ivar in a class (which it must be).
2109 Target = EmitClassRef(CGF, Class->getSuperClass());
2110 Target = CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, Target, 0);
2111 Target = CGF.Builder.CreateAlignedLoad(ClassTyPtr, Target,
2112 CGF.getPointerAlign());
2113 } else {
2114 llvm::Constant *MetaClassPtr = EmitMetaClassRef(Class);
2115 llvm::Value *SuperPtr =
2116 CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, MetaClassPtr, 1);
2117 llvm::Value *Super = CGF.Builder.CreateAlignedLoad(ClassTyPtr, SuperPtr,
2118 CGF.getPointerAlign());
2119 Target = Super;
2120 }
2121 } else if (isCategoryImpl)
2122 Target = EmitClassRef(CGF, Class->getSuperClass());
2123 else {
2124 llvm::Value *ClassPtr = EmitSuperClassRef(Class);
2125 ClassPtr = CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, ClassPtr, 1);
2126 Target = CGF.Builder.CreateAlignedLoad(ClassTyPtr, ClassPtr,
2127 CGF.getPointerAlign());
2128 }
2129 // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
2130 // ObjCTypes types.
2131 llvm::Type *ClassTy =
2132 CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
2133 Target = CGF.Builder.CreateBitCast(Target, ClassTy);
2134 CGF.Builder.CreateStore(Target, CGF.Builder.CreateStructGEP(ObjCSuper, 1));
2135 return EmitMessageSend(CGF, Return, ResultType, Sel, ObjCSuper.getPointer(),
2136 ObjCTypes.SuperPtrCTy, true, CallArgs, Method, Class,
2137 ObjCTypes);
2138}
2139
2140/// Generate code for a message send expression.
2141CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
2142 ReturnValueSlot Return,
2143 QualType ResultType,
2144 Selector Sel,
2145 llvm::Value *Receiver,
2146 const CallArgList &CallArgs,
2147 const ObjCInterfaceDecl *Class,
2148 const ObjCMethodDecl *Method) {
2149 return EmitMessageSend(CGF, Return, ResultType, Sel, Receiver,
2150 CGF.getContext().getObjCIdType(), false, CallArgs,
2151 Method, Class, ObjCTypes);
2152}
2153
2154static bool isWeakLinkedClass(const ObjCInterfaceDecl *ID) {
2155 do {
2156 if (ID->isWeakImported())
2157 return true;
2158 } while ((ID = ID->getSuperClass()));
2159
2160 return false;
2161}
2162
2163CodeGen::RValue
2164CGObjCCommonMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
2165 ReturnValueSlot Return,
2166 QualType ResultType,
2167 Selector Sel,
2168 llvm::Value *Arg0,
2169 QualType Arg0Ty,
2170 bool IsSuper,
2171 const CallArgList &CallArgs,
2172 const ObjCMethodDecl *Method,
2173 const ObjCInterfaceDecl *ClassReceiver,
2174 const ObjCCommonTypesHelper &ObjCTypes) {
2175 CodeGenTypes &Types = CGM.getTypes();
2176 auto selTy = CGF.getContext().getObjCSelType();
2177 llvm::Value *SelValue;
2178
2179 if (Method && Method->isDirectMethod()) {
2180 // Direct methods will synthesize the proper `_cmd` internally,
2181 // so just don't bother with setting the `_cmd` argument.
2182 assert(!IsSuper);
2183 SelValue = llvm::UndefValue::get(Types.ConvertType(selTy));
2184 } else {
2185 SelValue = GetSelector(CGF, Sel);
2186 }
2187
2188 CallArgList ActualArgs;
2189 if (!IsSuper)
2190 Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy);
2191 ActualArgs.add(RValue::get(Arg0), Arg0Ty);
2192 ActualArgs.add(RValue::get(SelValue), selTy);
2193 ActualArgs.addFrom(CallArgs);
2194
2195 // If we're calling a method, use the formal signature.
2196 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
2197
2198 if (Method)
2199 assert(CGM.getContext().getCanonicalType(Method->getReturnType()) ==
2200 CGM.getContext().getCanonicalType(ResultType) &&
2201 "Result type mismatch!");
2202
2203 bool ReceiverCanBeNull = true;
2204
2205 // Super dispatch assumes that self is non-null; even the messenger
2206 // doesn't have a null check internally.
2207 if (IsSuper) {
2208 ReceiverCanBeNull = false;
2209
2210 // If this is a direct dispatch of a class method, check whether the class,
2211 // or anything in its hierarchy, was weak-linked.
2212 } else if (ClassReceiver && Method && Method->isClassMethod()) {
2213 ReceiverCanBeNull = isWeakLinkedClass(ClassReceiver);
2214
2215 // If we're emitting a method, and self is const (meaning just ARC, for now),
2216 // and the receiver is a load of self, then self is a valid object.
2217 } else if (auto CurMethod =
2218 dyn_cast_or_null<ObjCMethodDecl>(CGF.