1//===---- CGObjC.cpp - Emit LLVM Code for Objective-C ---------------------===//
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 contains code to emit Objective-C code as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGDebugInfo.h"
14#include "CGObjCRuntime.h"
15#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
17#include "CodeGenPGO.h"
18#include "ConstantEmitter.h"
19#include "TargetInfo.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/Attr.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/NSAPI.h"
24#include "clang/AST/StmtObjC.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/CodeGen/CGFunctionInfo.h"
27#include "clang/CodeGen/CodeGenABITypes.h"
28#include "llvm/Analysis/ObjCARCUtil.h"
29#include "llvm/BinaryFormat/MachO.h"
30#include "llvm/IR/Constants.h"
31#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/InlineAsm.h"
33#include <optional>
34using namespace clang;
35using namespace CodeGen;
36
37typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
38static TryEmitResult
39tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
40static RValue AdjustObjCObjectType(CodeGenFunction &CGF,
41 QualType ET,
42 RValue Result);
43
44/// Given the address of a variable of pointer type, find the correct
45/// null to store into it.
46static llvm::Constant *getNullForVariable(Address addr) {
47 llvm::Type *type = addr.getElementType();
48 return llvm::ConstantPointerNull::get(T: cast<llvm::PointerType>(Val: type));
49}
50
51/// Emits an instance of NSConstantString representing the object.
52llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
53{
54 llvm::Constant *C =
55 CGM.getObjCRuntime().GenerateConstantString(E->getString()).getPointer();
56 return C;
57}
58
59/// EmitObjCBoxedExpr - This routine generates code to call
60/// the appropriate expression boxing method. This will either be
61/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:],
62/// or [NSValue valueWithBytes:objCType:].
63///
64llvm::Value *
65CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
66 // If decided in Sema constant initializers are supported by the runtime, not
67 // disabled, and the contents can be emitted as a constant NSNumber subclass;
68 // use the ConstEmitter
69 if (E->isExpressibleAsConstantInitializer()) {
70 ConstantEmitter ConstEmitter(CGM);
71 return ConstEmitter.tryEmitAbstract(E, T: E->getType());
72 }
73
74 // Generate the correct selector for this literal's concrete type.
75 // Get the method.
76 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
77 const Expr *SubExpr = E->getSubExpr();
78
79 if (E->isExpressibleAsConstantInitializer()) {
80 ConstantEmitter ConstEmitter(CGM);
81 return ConstEmitter.tryEmitAbstract(E, T: E->getType());
82 }
83
84 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
85 Selector Sel = BoxingMethod->getSelector();
86
87 // Generate a reference to the class pointer, which will be the receiver.
88 // Assumes that the method was introduced in the class that should be
89 // messaged (avoids pulling it out of the result type).
90 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
91 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
92 llvm::Value *Receiver = Runtime.GetClass(CGF&: *this, OID: ClassDecl);
93
94 CallArgList Args;
95 const ParmVarDecl *ArgDecl = *BoxingMethod->param_begin();
96 QualType ArgQT = ArgDecl->getType().getUnqualifiedType();
97
98 // ObjCBoxedExpr supports boxing of structs and unions
99 // via [NSValue valueWithBytes:objCType:]
100 const QualType ValueType(SubExpr->getType().getCanonicalType());
101 if (ValueType->isObjCBoxableRecordType()) {
102 // Emit CodeGen for first parameter
103 // and cast value to correct type
104 Address Temporary = CreateMemTemp(T: SubExpr->getType());
105 EmitAnyExprToMem(E: SubExpr, Location: Temporary, Quals: Qualifiers(), /*isInit*/ IsInitializer: true);
106 llvm::Value *BitCast = Builder.CreateBitCast(
107 V: Temporary.emitRawPointer(CGF&: *this), DestTy: ConvertType(T: ArgQT));
108 Args.add(rvalue: RValue::get(V: BitCast), type: ArgQT);
109
110 // Create char array to store type encoding
111 std::string Str;
112 getContext().getObjCEncodingForType(T: ValueType, S&: Str);
113 llvm::Constant *GV = CGM.GetAddrOfConstantCString(Str).getPointer();
114
115 // Cast type encoding to correct type
116 const ParmVarDecl *EncodingDecl = BoxingMethod->parameters()[1];
117 QualType EncodingQT = EncodingDecl->getType().getUnqualifiedType();
118 llvm::Value *Cast = Builder.CreateBitCast(V: GV, DestTy: ConvertType(T: EncodingQT));
119
120 Args.add(rvalue: RValue::get(V: Cast), type: EncodingQT);
121 } else {
122 Args.add(rvalue: EmitAnyExpr(E: SubExpr), type: ArgQT);
123 }
124
125 RValue result = Runtime.GenerateMessageSend(
126 CGF&: *this, ReturnSlot: ReturnValueSlot(), ResultType: BoxingMethod->getReturnType(), Sel, Receiver,
127 CallArgs: Args, Class: ClassDecl, Method: BoxingMethod);
128 return Builder.CreateBitCast(V: result.getScalarVal(),
129 DestTy: ConvertType(T: E->getType()));
130}
131
132llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
133 const ObjCMethodDecl *MethodWithObjects) {
134 ASTContext &Context = CGM.getContext();
135 const ObjCDictionaryLiteral *DLE = nullptr;
136 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(Val: E);
137 if (!ALE)
138 DLE = cast<ObjCDictionaryLiteral>(Val: E);
139
140 const bool CanBeExpressedAsConstant =
141 ALE ? ALE->isExpressibleAsConstantInitializer()
142 : DLE->isExpressibleAsConstantInitializer();
143 if (CanBeExpressedAsConstant) {
144 ConstantEmitter ConstEmitter(CGM);
145 return ConstEmitter.tryEmitAbstract(E, T: E->getType());
146 }
147
148 // Optimize empty collections by referencing constants, when available and
149 // constant initializers aren't supported
150 uint64_t NumElements = ALE ? ALE->getNumElements() : DLE->getNumElements();
151
152 if (NumElements == 0 && CGM.getLangOpts().ObjCRuntime.hasEmptyCollections()) {
153 StringRef ConstantName = ALE ? "__NSArray0__" : "__NSDictionary0__";
154 QualType IdTy(CGM.getContext().getObjCIdType());
155 llvm::Constant *Constant =
156 CGM.CreateRuntimeVariable(Ty: ConvertType(T: IdTy), Name: ConstantName);
157 LValue LV = MakeNaturalAlignAddrLValue(V: Constant, T: IdTy);
158 llvm::Value *Ptr = EmitLoadOfScalar(lvalue: LV, Loc: E->getBeginLoc());
159 cast<llvm::LoadInst>(Val: Ptr)->setMetadata(
160 KindID: llvm::LLVMContext::MD_invariant_load,
161 Node: llvm::MDNode::get(Context&: getLLVMContext(), MDs: {}));
162 return Builder.CreateBitCast(V: Ptr, DestTy: ConvertType(T: E->getType()));
163 }
164
165 // Compute the type of the array we're initializing.
166 llvm::APInt APNumElements(Context.getTypeSize(T: Context.getSizeType()),
167 NumElements);
168 QualType ElementType = Context.getObjCIdType().withConst();
169 QualType ElementArrayType = Context.getConstantArrayType(
170 EltTy: ElementType, ArySize: APNumElements, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal,
171 /*IndexTypeQuals=*/0);
172
173 // Allocate the temporary array(s).
174 Address Objects = CreateMemTemp(T: ElementArrayType, Name: "objects");
175 Address Keys = Address::invalid();
176 if (DLE)
177 Keys = CreateMemTemp(T: ElementArrayType, Name: "keys");
178
179 // In ARC, we may need to do extra work to keep all the keys and
180 // values alive until after the call.
181 SmallVector<llvm::Value *, 16> NeededObjects;
182 bool TrackNeededObjects =
183 (getLangOpts().ObjCAutoRefCount &&
184 CGM.getCodeGenOpts().OptimizationLevel != 0);
185
186 // Perform the actual initialialization of the array(s).
187 for (uint64_t i = 0; i < NumElements; i++) {
188 if (ALE) {
189 // Emit the element and store it to the appropriate array slot.
190 const Expr *Rhs = ALE->getElement(Index: i);
191 LValue LV = MakeAddrLValue(Addr: Builder.CreateConstArrayGEP(Addr: Objects, Index: i),
192 T: ElementType, Source: AlignmentSource::Decl);
193
194 llvm::Value *value = EmitScalarExpr(E: Rhs);
195 EmitStoreThroughLValue(Src: RValue::get(V: value), Dst: LV, isInit: true);
196 if (TrackNeededObjects) {
197 NeededObjects.push_back(Elt: value);
198 }
199 } else {
200 // Emit the key and store it to the appropriate array slot.
201 const Expr *Key = DLE->getKeyValueElement(Index: i).Key;
202 LValue KeyLV = MakeAddrLValue(Addr: Builder.CreateConstArrayGEP(Addr: Keys, Index: i),
203 T: ElementType, Source: AlignmentSource::Decl);
204 llvm::Value *keyValue = EmitScalarExpr(E: Key);
205 EmitStoreThroughLValue(Src: RValue::get(V: keyValue), Dst: KeyLV, /*isInit=*/true);
206
207 // Emit the value and store it to the appropriate array slot.
208 const Expr *Value = DLE->getKeyValueElement(Index: i).Value;
209 LValue ValueLV = MakeAddrLValue(Addr: Builder.CreateConstArrayGEP(Addr: Objects, Index: i),
210 T: ElementType, Source: AlignmentSource::Decl);
211 llvm::Value *valueValue = EmitScalarExpr(E: Value);
212 EmitStoreThroughLValue(Src: RValue::get(V: valueValue), Dst: ValueLV, /*isInit=*/true);
213 if (TrackNeededObjects) {
214 NeededObjects.push_back(Elt: keyValue);
215 NeededObjects.push_back(Elt: valueValue);
216 }
217 }
218 }
219
220 // Generate the argument list.
221 CallArgList Args;
222 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
223 const ParmVarDecl *argDecl = *PI++;
224 QualType ArgQT = argDecl->getType().getUnqualifiedType();
225 Args.add(rvalue: RValue::get(Addr: Objects, CGF&: *this), type: ArgQT);
226 if (DLE) {
227 argDecl = *PI++;
228 ArgQT = argDecl->getType().getUnqualifiedType();
229 Args.add(rvalue: RValue::get(Addr: Keys, CGF&: *this), type: ArgQT);
230 }
231 argDecl = *PI;
232 ArgQT = argDecl->getType().getUnqualifiedType();
233 llvm::Value *Count =
234 llvm::ConstantInt::get(Ty: CGM.getTypes().ConvertType(T: ArgQT), V: NumElements);
235 Args.add(rvalue: RValue::get(V: Count), type: ArgQT);
236
237 // Generate a reference to the class pointer, which will be the receiver.
238 Selector Sel = MethodWithObjects->getSelector();
239 QualType ResultType = E->getType();
240 const ObjCObjectPointerType *InterfacePointerType
241 = ResultType->getAsObjCInterfacePointerType();
242 assert(InterfacePointerType && "Unexpected InterfacePointerType - null");
243 ObjCInterfaceDecl *Class
244 = InterfacePointerType->getObjectType()->getInterface();
245 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
246 llvm::Value *Receiver = Runtime.GetClass(CGF&: *this, OID: Class);
247
248 // Generate the message send.
249 RValue result = Runtime.GenerateMessageSend(
250 CGF&: *this, ReturnSlot: ReturnValueSlot(), ResultType: MethodWithObjects->getReturnType(), Sel,
251 Receiver, CallArgs: Args, Class, Method: MethodWithObjects);
252
253 // The above message send needs these objects, but in ARC they are
254 // passed in a buffer that is essentially __unsafe_unretained.
255 // Therefore we must prevent the optimizer from releasing them until
256 // after the call.
257 if (TrackNeededObjects) {
258 EmitARCIntrinsicUse(values: NeededObjects);
259 }
260
261 return Builder.CreateBitCast(V: result.getScalarVal(),
262 DestTy: ConvertType(T: E->getType()));
263}
264
265llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
266 return EmitObjCCollectionLiteral(E, MethodWithObjects: E->getArrayWithObjectsMethod());
267}
268
269llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
270 const ObjCDictionaryLiteral *E) {
271 return EmitObjCCollectionLiteral(E, MethodWithObjects: E->getDictWithObjectsMethod());
272}
273
274/// Emit a selector.
275llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
276 // Untyped selector.
277 // Note that this implementation allows for non-constant strings to be passed
278 // as arguments to @selector(). Currently, the only thing preventing this
279 // behaviour is the type checking in the front end.
280 return CGM.getObjCRuntime().GetSelector(CGF&: *this, Sel: E->getSelector());
281}
282
283llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
284 // FIXME: This should pass the Decl not the name.
285 return CGM.getObjCRuntime().GenerateProtocolRef(CGF&: *this, OPD: E->getProtocol());
286}
287
288/// Adjust the type of an Objective-C object that doesn't match up due
289/// to type erasure at various points, e.g., related result types or the use
290/// of parameterized classes.
291static RValue AdjustObjCObjectType(CodeGenFunction &CGF, QualType ExpT,
292 RValue Result) {
293 if (!ExpT->isObjCRetainableType())
294 return Result;
295
296 // If the converted types are the same, we're done.
297 llvm::Type *ExpLLVMTy = CGF.ConvertType(T: ExpT);
298 if (ExpLLVMTy == Result.getScalarVal()->getType())
299 return Result;
300
301 // We have applied a substitution. Cast the rvalue appropriately.
302 return RValue::get(V: CGF.Builder.CreateBitCast(V: Result.getScalarVal(),
303 DestTy: ExpLLVMTy));
304}
305
306/// Decide whether to extend the lifetime of the receiver of a
307/// returns-inner-pointer message.
308static bool
309shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
310 switch (message->getReceiverKind()) {
311
312 // For a normal instance message, we should extend unless the
313 // receiver is loaded from a variable with precise lifetime.
314 case ObjCMessageExpr::Instance: {
315 const Expr *receiver = message->getInstanceReceiver();
316
317 // Look through OVEs.
318 if (auto opaque = dyn_cast<OpaqueValueExpr>(Val: receiver)) {
319 if (opaque->getSourceExpr())
320 receiver = opaque->getSourceExpr()->IgnoreParens();
321 }
322
323 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(Val: receiver);
324 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
325 receiver = ice->getSubExpr()->IgnoreParens();
326
327 // Look through OVEs.
328 if (auto opaque = dyn_cast<OpaqueValueExpr>(Val: receiver)) {
329 if (opaque->getSourceExpr())
330 receiver = opaque->getSourceExpr()->IgnoreParens();
331 }
332
333 // Only __strong variables.
334 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
335 return true;
336
337 // All ivars and fields have precise lifetime.
338 if (isa<MemberExpr>(Val: receiver) || isa<ObjCIvarRefExpr>(Val: receiver))
339 return false;
340
341 // Otherwise, check for variables.
342 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(Val: ice->getSubExpr());
343 if (!declRef) return true;
344 const VarDecl *var = dyn_cast<VarDecl>(Val: declRef->getDecl());
345 if (!var) return true;
346
347 // All variables have precise lifetime except local variables with
348 // automatic storage duration that aren't specially marked.
349 return (var->hasLocalStorage() &&
350 !var->hasAttr<ObjCPreciseLifetimeAttr>());
351 }
352
353 case ObjCMessageExpr::Class:
354 case ObjCMessageExpr::SuperClass:
355 // It's never necessary for class objects.
356 return false;
357
358 case ObjCMessageExpr::SuperInstance:
359 // We generally assume that 'self' lives throughout a method call.
360 return false;
361 }
362
363 llvm_unreachable("invalid receiver kind");
364}
365
366/// Given an expression of ObjC pointer type, check whether it was
367/// immediately loaded from an ARC __weak l-value.
368static const Expr *findWeakLValue(const Expr *E) {
369 assert(E->getType()->isObjCRetainableType());
370 E = E->IgnoreParens();
371 if (auto CE = dyn_cast<CastExpr>(Val: E)) {
372 if (CE->getCastKind() == CK_LValueToRValue) {
373 if (CE->getSubExpr()->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
374 return CE->getSubExpr();
375 }
376 }
377
378 return nullptr;
379}
380
381/// The ObjC runtime may provide entrypoints that are likely to be faster
382/// than an ordinary message send of the appropriate selector.
383///
384/// The entrypoints are guaranteed to be equivalent to just sending the
385/// corresponding message. If the entrypoint is implemented naively as just a
386/// message send, using it is a trade-off: it sacrifices a few cycles of
387/// overhead to save a small amount of code. However, it's possible for
388/// runtimes to detect and special-case classes that use "standard"
389/// behavior; if that's dynamically a large proportion of all objects, using
390/// the entrypoint will also be faster than using a message send.
391///
392/// If the runtime does support a required entrypoint, then this method will
393/// generate a call and return the resulting value. Otherwise it will return
394/// std::nullopt and the caller can generate a msgSend instead.
395static std::optional<llvm::Value *> tryGenerateSpecializedMessageSend(
396 CodeGenFunction &CGF, QualType ResultType, llvm::Value *Receiver,
397 const CallArgList &Args, Selector Sel, const ObjCMethodDecl *method,
398 bool isClassMessage) {
399 auto &CGM = CGF.CGM;
400 if (!CGM.getCodeGenOpts().ObjCConvertMessagesToRuntimeCalls)
401 return std::nullopt;
402
403 auto &Runtime = CGM.getLangOpts().ObjCRuntime;
404 switch (Sel.getMethodFamily()) {
405 case OMF_alloc:
406 if (isClassMessage &&
407 Runtime.shouldUseRuntimeFunctionsForAlloc() &&
408 ResultType->isObjCObjectPointerType()) {
409 // [Foo alloc] -> objc_alloc(Foo) or
410 // [self alloc] -> objc_alloc(self)
411 if (Sel.isUnarySelector() && Sel.getNameForSlot(argIndex: 0) == "alloc")
412 return CGF.EmitObjCAlloc(value: Receiver, returnType: CGF.ConvertType(T: ResultType));
413 // [Foo allocWithZone:nil] -> objc_allocWithZone(Foo) or
414 // [self allocWithZone:nil] -> objc_allocWithZone(self)
415 if (Sel.isKeywordSelector() && Sel.getNumArgs() == 1 &&
416 Args.size() == 1 && Args.front().getType()->isPointerType() &&
417 Sel.getNameForSlot(argIndex: 0) == "allocWithZone") {
418 const llvm::Value* arg = Args.front().getKnownRValue().getScalarVal();
419 if (isa<llvm::ConstantPointerNull>(Val: arg))
420 return CGF.EmitObjCAllocWithZone(value: Receiver,
421 returnType: CGF.ConvertType(T: ResultType));
422 return std::nullopt;
423 }
424 }
425 break;
426
427 case OMF_autorelease:
428 if (ResultType->isObjCObjectPointerType() &&
429 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
430 Runtime.shouldUseARCFunctionsForRetainRelease())
431 return CGF.EmitObjCAutorelease(value: Receiver, returnType: CGF.ConvertType(T: ResultType));
432 break;
433
434 case OMF_retain:
435 if (ResultType->isObjCObjectPointerType() &&
436 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
437 Runtime.shouldUseARCFunctionsForRetainRelease())
438 return CGF.EmitObjCRetainNonBlock(value: Receiver, returnType: CGF.ConvertType(T: ResultType));
439 break;
440
441 case OMF_release:
442 if (ResultType->isVoidType() &&
443 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
444 Runtime.shouldUseARCFunctionsForRetainRelease()) {
445 CGF.EmitObjCRelease(value: Receiver, precise: ARCPreciseLifetime);
446 return nullptr;
447 }
448 break;
449
450 default:
451 break;
452 }
453 return std::nullopt;
454}
455
456CodeGen::RValue CGObjCRuntime::GeneratePossiblySpecializedMessageSend(
457 CodeGenFunction &CGF, ReturnValueSlot Return, QualType ResultType,
458 Selector Sel, llvm::Value *Receiver, const CallArgList &Args,
459 const ObjCInterfaceDecl *OID, const ObjCMethodDecl *Method,
460 bool isClassMessage) {
461 if (std::optional<llvm::Value *> SpecializedResult =
462 tryGenerateSpecializedMessageSend(CGF, ResultType, Receiver, Args,
463 Sel, method: Method, isClassMessage)) {
464 return RValue::get(V: *SpecializedResult);
465 }
466 return GenerateMessageSend(CGF, ReturnSlot: Return, ResultType, Sel, Receiver, CallArgs: Args, Class: OID,
467 Method);
468}
469
470static void AppendFirstImpliedRuntimeProtocols(
471 const ObjCProtocolDecl *PD,
472 llvm::UniqueVector<const ObjCProtocolDecl *> &PDs) {
473 if (!PD->isNonRuntimeProtocol()) {
474 const auto *Can = PD->getCanonicalDecl();
475 PDs.insert(Entry: Can);
476 return;
477 }
478
479 for (const auto *ParentPD : PD->protocols())
480 AppendFirstImpliedRuntimeProtocols(PD: ParentPD, PDs);
481}
482
483std::vector<const ObjCProtocolDecl *>
484CGObjCRuntime::GetRuntimeProtocolList(ObjCProtocolDecl::protocol_iterator begin,
485 ObjCProtocolDecl::protocol_iterator end) {
486 std::vector<const ObjCProtocolDecl *> RuntimePds;
487 llvm::DenseSet<const ObjCProtocolDecl *> NonRuntimePDs;
488
489 for (; begin != end; ++begin) {
490 const auto *It = *begin;
491 const auto *Can = It->getCanonicalDecl();
492 if (Can->isNonRuntimeProtocol())
493 NonRuntimePDs.insert(V: Can);
494 else
495 RuntimePds.push_back(x: Can);
496 }
497
498 // If there are no non-runtime protocols then we can just stop now.
499 if (NonRuntimePDs.empty())
500 return RuntimePds;
501
502 // Else we have to search through the non-runtime protocol's inheritancy
503 // hierarchy DAG stopping whenever a branch either finds a runtime protocol or
504 // a non-runtime protocol without any parents. These are the "first-implied"
505 // protocols from a non-runtime protocol.
506 llvm::UniqueVector<const ObjCProtocolDecl *> FirstImpliedProtos;
507 for (const auto *PD : NonRuntimePDs)
508 AppendFirstImpliedRuntimeProtocols(PD, PDs&: FirstImpliedProtos);
509
510 // Walk the Runtime list to get all protocols implied via the inclusion of
511 // this protocol, e.g. all protocols it inherits from including itself.
512 llvm::DenseSet<const ObjCProtocolDecl *> AllImpliedProtocols;
513 for (const auto *PD : RuntimePds) {
514 const auto *Can = PD->getCanonicalDecl();
515 AllImpliedProtocols.insert(V: Can);
516 Can->getImpliedProtocols(IPs&: AllImpliedProtocols);
517 }
518
519 // Similar to above, walk the list of first-implied protocols to find the set
520 // all the protocols implied excluding the listed protocols themselves since
521 // they are not yet a part of the `RuntimePds` list.
522 for (const auto *PD : FirstImpliedProtos) {
523 PD->getImpliedProtocols(IPs&: AllImpliedProtocols);
524 }
525
526 // From the first-implied list we have to finish building the final protocol
527 // list. If a protocol in the first-implied list was already implied via some
528 // inheritance path through some other protocols then it would be redundant to
529 // add it here and so we skip over it.
530 for (const auto *PD : FirstImpliedProtos) {
531 if (!AllImpliedProtocols.contains(V: PD)) {
532 RuntimePds.push_back(x: PD);
533 }
534 }
535
536 return RuntimePds;
537}
538
539/// Instead of '[[MyClass alloc] init]', try to generate
540/// 'objc_alloc_init(MyClass)'. This provides a code size improvement on the
541/// caller side, as well as the optimized objc_alloc.
542static std::optional<llvm::Value *>
543tryEmitSpecializedAllocInit(CodeGenFunction &CGF, const ObjCMessageExpr *OME) {
544 auto &Runtime = CGF.getLangOpts().ObjCRuntime;
545 if (!Runtime.shouldUseRuntimeFunctionForCombinedAllocInit())
546 return std::nullopt;
547
548 // Match the exact pattern '[[MyClass alloc] init]'.
549 Selector Sel = OME->getSelector();
550 if (OME->getReceiverKind() != ObjCMessageExpr::Instance ||
551 !OME->getType()->isObjCObjectPointerType() || !Sel.isUnarySelector() ||
552 Sel.getNameForSlot(argIndex: 0) != "init")
553 return std::nullopt;
554
555 // Okay, this is '[receiver init]', check if 'receiver' is '[cls alloc]'
556 // with 'cls' a Class.
557 auto *SubOME =
558 dyn_cast<ObjCMessageExpr>(Val: OME->getInstanceReceiver()->IgnoreParenCasts());
559 if (!SubOME)
560 return std::nullopt;
561 Selector SubSel = SubOME->getSelector();
562
563 if (!SubOME->getType()->isObjCObjectPointerType() ||
564 !SubSel.isUnarySelector() || SubSel.getNameForSlot(argIndex: 0) != "alloc")
565 return std::nullopt;
566
567 llvm::Value *Receiver = nullptr;
568 switch (SubOME->getReceiverKind()) {
569 case ObjCMessageExpr::Instance:
570 if (!SubOME->getInstanceReceiver()->getType()->isObjCClassType())
571 return std::nullopt;
572 Receiver = CGF.EmitScalarExpr(E: SubOME->getInstanceReceiver());
573 break;
574
575 case ObjCMessageExpr::Class: {
576 QualType ReceiverType = SubOME->getClassReceiver();
577 const ObjCObjectType *ObjTy = ReceiverType->castAs<ObjCObjectType>();
578 const ObjCInterfaceDecl *ID = ObjTy->getInterface();
579 assert(ID && "null interface should be impossible here");
580 Receiver = CGF.CGM.getObjCRuntime().GetClass(CGF, OID: ID);
581 break;
582 }
583 case ObjCMessageExpr::SuperInstance:
584 case ObjCMessageExpr::SuperClass:
585 return std::nullopt;
586 }
587
588 return CGF.EmitObjCAllocInit(value: Receiver, resultType: CGF.ConvertType(T: OME->getType()));
589}
590
591RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
592 ReturnValueSlot Return) {
593 // Only the lookup mechanism and first two arguments of the method
594 // implementation vary between runtimes. We can get the receiver and
595 // arguments in generic code.
596
597 bool isDelegateInit = E->isDelegateInitCall();
598
599 const ObjCMethodDecl *method = E->getMethodDecl();
600
601 // If the method is -retain, and the receiver's being loaded from
602 // a __weak variable, peephole the entire operation to objc_loadWeakRetained.
603 if (method && E->getReceiverKind() == ObjCMessageExpr::Instance &&
604 method->getMethodFamily() == OMF_retain) {
605 if (auto lvalueExpr = findWeakLValue(E: E->getInstanceReceiver())) {
606 LValue lvalue = EmitLValue(E: lvalueExpr);
607 llvm::Value *result = EmitARCLoadWeakRetained(addr: lvalue.getAddress());
608 return AdjustObjCObjectType(CGF&: *this, ExpT: E->getType(), Result: RValue::get(V: result));
609 }
610 }
611
612 if (std::optional<llvm::Value *> Val = tryEmitSpecializedAllocInit(CGF&: *this, OME: E))
613 return AdjustObjCObjectType(CGF&: *this, ExpT: E->getType(), Result: RValue::get(V: *Val));
614
615 // We don't retain the receiver in delegate init calls, and this is
616 // safe because the receiver value is always loaded from 'self',
617 // which we zero out. We don't want to Block_copy block receivers,
618 // though.
619 bool retainSelf =
620 (!isDelegateInit &&
621 CGM.getLangOpts().ObjCAutoRefCount &&
622 method &&
623 method->hasAttr<NSConsumesSelfAttr>());
624
625 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
626 bool isSuperMessage = false;
627 bool isClassMessage = false;
628 ObjCInterfaceDecl *OID = nullptr;
629 // Find the receiver
630 QualType ReceiverType;
631 llvm::Value *Receiver = nullptr;
632 switch (E->getReceiverKind()) {
633 case ObjCMessageExpr::Instance:
634 ReceiverType = E->getInstanceReceiver()->getType();
635 isClassMessage = ReceiverType->isObjCClassType();
636 if (retainSelf) {
637 TryEmitResult ter = tryEmitARCRetainScalarExpr(CGF&: *this,
638 e: E->getInstanceReceiver());
639 Receiver = ter.getPointer();
640 if (ter.getInt()) retainSelf = false;
641 } else
642 Receiver = EmitScalarExpr(E: E->getInstanceReceiver());
643 break;
644
645 case ObjCMessageExpr::Class: {
646 ReceiverType = E->getClassReceiver();
647 OID = ReceiverType->castAs<ObjCObjectType>()->getInterface();
648 assert(OID && "Invalid Objective-C class message send");
649 Receiver = Runtime.GetClass(CGF&: *this, OID);
650 isClassMessage = true;
651 break;
652 }
653
654 case ObjCMessageExpr::SuperInstance:
655 ReceiverType = E->getSuperType();
656 Receiver = LoadObjCSelf();
657 isSuperMessage = true;
658 break;
659
660 case ObjCMessageExpr::SuperClass:
661 ReceiverType = E->getSuperType();
662 Receiver = LoadObjCSelf();
663 isSuperMessage = true;
664 isClassMessage = true;
665 break;
666 }
667
668 if (retainSelf)
669 Receiver = EmitARCRetainNonBlock(value: Receiver);
670
671 // In ARC, we sometimes want to "extend the lifetime"
672 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
673 // messages.
674 if (getLangOpts().ObjCAutoRefCount && method &&
675 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
676 shouldExtendReceiverForInnerPointerMessage(message: E))
677 Receiver = EmitARCRetainAutorelease(type: ReceiverType, value: Receiver);
678
679 QualType ResultType = method ? method->getReturnType() : E->getType();
680
681 CallArgList Args;
682 EmitCallArgs(Args, Prototype: method, ArgRange: E->arguments(), /*AC*/AbstractCallee(method));
683
684 // For delegate init calls in ARC, do an unsafe store of null into
685 // self. This represents the call taking direct ownership of that
686 // value. We have to do this after emitting the other call
687 // arguments because they might also reference self, but we don't
688 // have to worry about any of them modifying self because that would
689 // be an undefined read and write of an object in unordered
690 // expressions.
691 if (isDelegateInit) {
692 assert(getLangOpts().ObjCAutoRefCount &&
693 "delegate init calls should only be marked in ARC");
694
695 // Do an unsafe store of null into self.
696 Address selfAddr =
697 GetAddrOfLocalVar(VD: cast<ObjCMethodDecl>(Val: CurCodeDecl)->getSelfDecl());
698 Builder.CreateStore(Val: getNullForVariable(addr: selfAddr), Addr: selfAddr);
699 }
700
701 RValue result;
702 if (isSuperMessage) {
703 // super is only valid in an Objective-C method
704 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(Val: CurFuncDecl);
705 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(Val: OMD->getDeclContext());
706 result = Runtime.GenerateMessageSendSuper(CGF&: *this, ReturnSlot: Return, ResultType,
707 Sel: E->getSelector(),
708 Class: OMD->getClassInterface(),
709 isCategoryImpl,
710 Self: Receiver,
711 IsClassMessage: isClassMessage,
712 CallArgs: Args,
713 Method: method);
714 } else {
715 // Call runtime methods directly if we can.
716 result = Runtime.GeneratePossiblySpecializedMessageSend(
717 CGF&: *this, Return, ResultType, Sel: E->getSelector(), Receiver, Args, OID,
718 Method: method, isClassMessage);
719 }
720
721 // For delegate init calls in ARC, implicitly store the result of
722 // the call back into self. This takes ownership of the value.
723 if (isDelegateInit) {
724 Address selfAddr =
725 GetAddrOfLocalVar(VD: cast<ObjCMethodDecl>(Val: CurCodeDecl)->getSelfDecl());
726 llvm::Value *newSelf = result.getScalarVal();
727
728 // The delegate return type isn't necessarily a matching type; in
729 // fact, it's quite likely to be 'id'.
730 llvm::Type *selfTy = selfAddr.getElementType();
731 newSelf = Builder.CreateBitCast(V: newSelf, DestTy: selfTy);
732
733 Builder.CreateStore(Val: newSelf, Addr: selfAddr);
734 }
735
736 return AdjustObjCObjectType(CGF&: *this, ExpT: E->getType(), Result: result);
737}
738
739namespace {
740struct FinishARCDealloc final : EHScopeStack::Cleanup {
741 void Emit(CodeGenFunction &CGF, Flags flags) override {
742 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(Val: CGF.CurCodeDecl);
743
744 const ObjCImplDecl *impl = cast<ObjCImplDecl>(Val: method->getDeclContext());
745 const ObjCInterfaceDecl *iface = impl->getClassInterface();
746 if (!iface->getSuperClass()) return;
747
748 bool isCategory = isa<ObjCCategoryImplDecl>(Val: impl);
749
750 // Call [super dealloc] if we have a superclass.
751 llvm::Value *self = CGF.LoadObjCSelf();
752
753 CallArgList args;
754 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnSlot: ReturnValueSlot(),
755 ResultType: CGF.getContext().VoidTy,
756 Sel: method->getSelector(),
757 Class: iface,
758 isCategoryImpl: isCategory,
759 Self: self,
760 /*is class msg*/ IsClassMessage: false,
761 CallArgs: args,
762 Method: method);
763 }
764};
765}
766
767/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
768/// the LLVM function and sets the other context used by
769/// CodeGenFunction.
770void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
771 const ObjCContainerDecl *CD) {
772 SourceLocation StartLoc = OMD->getBeginLoc();
773 FunctionArgList args;
774 // Check if we should generate debug info for this method.
775 if (OMD->hasAttr<NoDebugAttr>())
776 DebugInfo = nullptr; // disable debug info indefinitely for this function
777
778 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
779
780 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(MD: OMD);
781 if (OMD->isDirectMethod()) {
782 // Default hidden visibility
783 Fn->setVisibility(llvm::Function::HiddenVisibility);
784 if (CGM.isObjCDirectPreconditionThunkEnabled()) {
785 // However, if we expose the symbol, and the decl (property or method)
786 // have visibility attribute set ...
787 const NamedDecl *Decl = OMD;
788 if (const auto *PD = OMD->findPropertyDecl()) {
789 Decl = PD;
790 }
791 // ... then respect source level visibility setting
792 if (auto V = Decl->getExplicitVisibility(kind: NamedDecl::VisibilityForValue)) {
793 Fn->setVisibility(CGM.GetLLVMVisibility(V: *V));
794 }
795 }
796 CGM.SetLLVMFunctionAttributes(GD: OMD, Info: FI, F: Fn, /*IsThunk=*/false);
797 CGM.SetLLVMFunctionAttributesForDefinition(D: OMD, F: Fn);
798 } else {
799 CGM.SetInternalFunctionAttributes(GD: OMD, F: Fn, FI);
800 }
801
802 args.push_back(Elt: OMD->getSelfDecl());
803 if (!OMD->isDirectMethod())
804 args.push_back(Elt: OMD->getCmdDecl());
805
806 args.append(in_start: OMD->param_begin(), in_end: OMD->param_end());
807
808 CurGD = OMD;
809 CurEHLocation = OMD->getEndLoc();
810
811 StartFunction(GD: OMD, RetTy: OMD->getReturnType(), Fn, FnInfo: FI, Args: args,
812 Loc: OMD->getLocation(), StartLoc);
813
814 if (OMD->isDirectMethod()) {
815 CGM.getObjCRuntime().GenerateDirectMethodPrologue(CGF&: *this, Fn, OMD, CD);
816 }
817
818 // In ARC, certain methods get an extra cleanup.
819 if (CGM.getLangOpts().ObjCAutoRefCount &&
820 OMD->isInstanceMethod() &&
821 OMD->getSelector().isUnarySelector()) {
822 const IdentifierInfo *ident =
823 OMD->getSelector().getIdentifierInfoForSlot(argIndex: 0);
824 if (ident->isStr(Str: "dealloc"))
825 EHStack.pushCleanup<FinishARCDealloc>(Kind: getARCCleanupKind());
826 }
827}
828
829static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
830 LValue lvalue, QualType type);
831
832/// Generate an Objective-C method. An Objective-C method is a C function with
833/// its pointer, name, and types registered in the class structure.
834void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
835 StartObjCMethod(OMD, CD: OMD->getClassInterface());
836 PGO->assignRegionCounters(GD: GlobalDecl(OMD), Fn: CurFn);
837 assert(isa<CompoundStmt>(OMD->getBody()));
838 incrementProfileCounter(S: OMD->getBody());
839 EmitCompoundStmtWithoutScope(S: *cast<CompoundStmt>(Val: OMD->getBody()));
840 FinishFunction(EndLoc: OMD->getBodyRBrace());
841}
842
843/// emitStructGetterCall - Call the runtime function to load a property
844/// into the return value slot.
845static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
846 bool isAtomic, bool hasStrong) {
847 ASTContext &Context = CGF.getContext();
848
849 llvm::Value *src =
850 CGF.EmitLValueForIvar(ObjectTy: CGF.TypeOfSelfObject(), Base: CGF.LoadObjCSelf(), Ivar: ivar, CVRQualifiers: 0)
851 .getPointer(CGF);
852
853 // objc_copyStruct (ReturnValue, &structIvar,
854 // sizeof (Type of Ivar), isAtomic, false);
855 CallArgList args;
856
857 llvm::Value *dest = CGF.ReturnValue.emitRawPointer(CGF);
858 args.add(rvalue: RValue::get(V: dest), type: Context.VoidPtrTy);
859 args.add(rvalue: RValue::get(V: src), type: Context.VoidPtrTy);
860
861 CharUnits size = CGF.getContext().getTypeSizeInChars(T: ivar->getType());
862 args.add(rvalue: RValue::get(V: CGF.CGM.getSize(numChars: size)), type: Context.getSizeType());
863 args.add(rvalue: RValue::get(V: CGF.Builder.getInt1(V: isAtomic)), type: Context.BoolTy);
864 args.add(rvalue: RValue::get(V: CGF.Builder.getInt1(V: hasStrong)), type: Context.BoolTy);
865
866 llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
867 CGCallee callee = CGCallee::forDirect(functionPtr: fn);
868 CGF.EmitCall(CallInfo: CGF.getTypes().arrangeBuiltinFunctionCall(resultType: Context.VoidTy, args),
869 Callee: callee, ReturnValue: ReturnValueSlot(), Args: args);
870}
871
872/// Return the maximum size that permits atomic accesses for the given
873/// architecture.
874static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM) {
875 // ARM has 8-byte atomic accesses, but it's not clear whether we
876 // want to rely on them here.
877
878 // In the default case, just assume that any size up to a pointer is
879 // fine given adequate alignment.
880 return CharUnits::fromQuantity(Quantity: CGM.PointerSizeInBytes);
881}
882
883namespace {
884 class PropertyImplStrategy {
885 public:
886 enum StrategyKind {
887 /// The 'native' strategy is to use the architecture's provided
888 /// reads and writes.
889 Native,
890
891 /// Use objc_setProperty and objc_getProperty.
892 GetSetProperty,
893
894 /// Use objc_setProperty for the setter, but use expression
895 /// evaluation for the getter.
896 SetPropertyAndExpressionGet,
897
898 /// Use objc_copyStruct.
899 CopyStruct,
900
901 /// The 'expression' strategy is to emit normal assignment or
902 /// lvalue-to-rvalue expressions.
903 Expression
904 };
905
906 StrategyKind getKind() const { return StrategyKind(Kind); }
907
908 bool hasStrongMember() const { return HasStrong; }
909 bool isAtomic() const { return IsAtomic; }
910 bool isCopy() const { return IsCopy; }
911
912 CharUnits getIvarSize() const { return IvarSize; }
913 CharUnits getIvarAlignment() const { return IvarAlignment; }
914
915 PropertyImplStrategy(CodeGenModule &CGM,
916 const ObjCPropertyImplDecl *propImpl);
917
918 private:
919 LLVM_PREFERRED_TYPE(StrategyKind)
920 unsigned Kind : 8;
921 LLVM_PREFERRED_TYPE(bool)
922 unsigned IsAtomic : 1;
923 LLVM_PREFERRED_TYPE(bool)
924 unsigned IsCopy : 1;
925 LLVM_PREFERRED_TYPE(bool)
926 unsigned HasStrong : 1;
927
928 CharUnits IvarSize;
929 CharUnits IvarAlignment;
930 };
931}
932
933/// Pick an implementation strategy for the given property synthesis.
934PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
935 const ObjCPropertyImplDecl *propImpl) {
936 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
937 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
938
939 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
940 IsAtomic = prop->isAtomic();
941 HasStrong = false; // doesn't matter here.
942
943 // Evaluate the ivar's size and alignment.
944 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
945 QualType ivarType = ivar->getType();
946 auto TInfo = CGM.getContext().getTypeInfoInChars(T: ivarType);
947 IvarSize = TInfo.Width;
948 IvarAlignment = TInfo.Align;
949
950 // If we have a copy property, we always have to use setProperty.
951 // If the property is atomic we need to use getProperty, but in
952 // the nonatomic case we can just use expression.
953 if (IsCopy) {
954 Kind = IsAtomic ? GetSetProperty : SetPropertyAndExpressionGet;
955 return;
956 }
957
958 // Handle retain.
959 if (setterKind == ObjCPropertyDecl::Retain) {
960 // In GC-only, there's nothing special that needs to be done.
961 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
962 // fallthrough
963
964 // In ARC, if the property is non-atomic, use expression emission,
965 // which translates to objc_storeStrong. This isn't required, but
966 // it's slightly nicer.
967 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
968 // Using standard expression emission for the setter is only
969 // acceptable if the ivar is __strong, which won't be true if
970 // the property is annotated with __attribute__((NSObject)).
971 // TODO: falling all the way back to objc_setProperty here is
972 // just laziness, though; we could still use objc_storeStrong
973 // if we hacked it right.
974 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
975 Kind = Expression;
976 else
977 Kind = SetPropertyAndExpressionGet;
978 return;
979
980 // Otherwise, we need to at least use setProperty. However, if
981 // the property isn't atomic, we can use normal expression
982 // emission for the getter.
983 } else if (!IsAtomic) {
984 Kind = SetPropertyAndExpressionGet;
985 return;
986
987 // Otherwise, we have to use both setProperty and getProperty.
988 } else {
989 Kind = GetSetProperty;
990 return;
991 }
992 }
993
994 // If we're not atomic, just use expression accesses.
995 if (!IsAtomic) {
996 Kind = Expression;
997 return;
998 }
999
1000 // Properties on bitfield ivars need to be emitted using expression
1001 // accesses even if they're nominally atomic.
1002 if (ivar->isBitField()) {
1003 Kind = Expression;
1004 return;
1005 }
1006
1007 // GC-qualified or ARC-qualified ivars need to be emitted as
1008 // expressions. This actually works out to being atomic anyway,
1009 // except for ARC __strong, but that should trigger the above code.
1010 if (ivarType.hasNonTrivialObjCLifetime() ||
1011 (CGM.getLangOpts().getGC() &&
1012 CGM.getContext().getObjCGCAttrKind(Ty: ivarType))) {
1013 Kind = Expression;
1014 return;
1015 }
1016
1017 // Compute whether the ivar has strong members.
1018 if (CGM.getLangOpts().getGC())
1019 if (const auto *RD = ivarType->getAsRecordDecl())
1020 HasStrong = RD->hasObjectMember();
1021
1022 // We can never access structs with object members with a native
1023 // access, because we need to use write barriers. This is what
1024 // objc_copyStruct is for.
1025 if (HasStrong) {
1026 Kind = CopyStruct;
1027 return;
1028 }
1029
1030 // Otherwise, this is target-dependent and based on the size and
1031 // alignment of the ivar.
1032
1033 // If the size of the ivar is not a power of two, give up. We don't
1034 // want to get into the business of doing compare-and-swaps.
1035 if (!IvarSize.isPowerOfTwo()) {
1036 Kind = CopyStruct;
1037 return;
1038 }
1039
1040 // Most architectures require memory to fit within a single cache
1041 // line, so the alignment has to be at least the size of the access.
1042 // Otherwise we have to grab a lock.
1043 if (IvarAlignment < IvarSize) {
1044 Kind = CopyStruct;
1045 return;
1046 }
1047
1048 // If the ivar's size exceeds the architecture's maximum atomic
1049 // access size, we have to use CopyStruct.
1050 if (IvarSize > getMaxAtomicAccessSize(CGM)) {
1051 Kind = CopyStruct;
1052 return;
1053 }
1054
1055 // Otherwise, we can use native loads and stores.
1056 Kind = Native;
1057}
1058
1059/// Generate an Objective-C property getter function.
1060///
1061/// The given Decl must be an ObjCImplementationDecl. \@synthesize
1062/// is illegal within a category.
1063void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
1064 const ObjCPropertyImplDecl *PID) {
1065 llvm::Constant *AtomicHelperFn =
1066 CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
1067 ObjCMethodDecl *OMD = PID->getGetterMethodDecl();
1068 assert(OMD && "Invalid call to generate getter (empty method)");
1069 StartObjCMethod(OMD, CD: IMP->getClassInterface());
1070
1071 generateObjCGetterBody(classImpl: IMP, propImpl: PID, GetterMothodDecl: OMD, AtomicHelperFn);
1072
1073 FinishFunction(EndLoc: OMD->getEndLoc());
1074}
1075
1076static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
1077 const Expr *getter = propImpl->getGetterCXXConstructor();
1078 if (!getter) return true;
1079
1080 // Sema only makes only of these when the ivar has a C++ class type,
1081 // so the form is pretty constrained.
1082
1083 // If the property has a reference type, we might just be binding a
1084 // reference, in which case the result will be a gl-value. We should
1085 // treat this as a non-trivial operation.
1086 if (getter->isGLValue())
1087 return false;
1088
1089 // If we selected a trivial copy-constructor, we're okay.
1090 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(Val: getter))
1091 return (construct->getConstructor()->isTrivial());
1092
1093 // The constructor might require cleanups (in which case it's never
1094 // trivial).
1095 assert(isa<ExprWithCleanups>(getter));
1096 return false;
1097}
1098
1099/// emitCPPObjectAtomicGetterCall - Call the runtime function to
1100/// copy the ivar into the resturn slot.
1101static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
1102 llvm::Value *returnAddr,
1103 ObjCIvarDecl *ivar,
1104 llvm::Constant *AtomicHelperFn) {
1105 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
1106 // AtomicHelperFn);
1107 CallArgList args;
1108
1109 // The 1st argument is the return Slot.
1110 args.add(rvalue: RValue::get(V: returnAddr), type: CGF.getContext().VoidPtrTy);
1111
1112 // The 2nd argument is the address of the ivar.
1113 llvm::Value *ivarAddr =
1114 CGF.EmitLValueForIvar(ObjectTy: CGF.TypeOfSelfObject(), Base: CGF.LoadObjCSelf(), Ivar: ivar, CVRQualifiers: 0)
1115 .getPointer(CGF);
1116 args.add(rvalue: RValue::get(V: ivarAddr), type: CGF.getContext().VoidPtrTy);
1117
1118 // Third argument is the helper function.
1119 args.add(rvalue: RValue::get(V: AtomicHelperFn), type: CGF.getContext().VoidPtrTy);
1120
1121 llvm::FunctionCallee copyCppAtomicObjectFn =
1122 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
1123 CGCallee callee = CGCallee::forDirect(functionPtr: copyCppAtomicObjectFn);
1124 CGF.EmitCall(
1125 CallInfo: CGF.getTypes().arrangeBuiltinFunctionCall(resultType: CGF.getContext().VoidTy, args),
1126 Callee: callee, ReturnValue: ReturnValueSlot(), Args: args);
1127}
1128
1129// emitCmdValueForGetterSetterBody - Handle emitting the load necessary for
1130// the `_cmd` selector argument for getter/setter bodies. For direct methods,
1131// this returns an undefined/poison value; this matches behavior prior to `_cmd`
1132// being removed from the direct method ABI as the getter/setter caller would
1133// never load one. For non-direct methods, this emits a load of the implicit
1134// `_cmd` storage.
1135static llvm::Value *emitCmdValueForGetterSetterBody(CodeGenFunction &CGF,
1136 ObjCMethodDecl *MD) {
1137 if (MD->isDirectMethod()) {
1138 // Direct methods do not have a `_cmd` argument. Emit an undefined/poison
1139 // value. This will be passed to objc_getProperty/objc_setProperty, which
1140 // has not appeared bothered by the `_cmd` argument being undefined before.
1141 llvm::Type *selType = CGF.ConvertType(T: CGF.getContext().getObjCSelType());
1142 return llvm::PoisonValue::get(T: selType);
1143 }
1144
1145 return CGF.Builder.CreateLoad(Addr: CGF.GetAddrOfLocalVar(VD: MD->getCmdDecl()), Name: "cmd");
1146}
1147
1148void
1149CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
1150 const ObjCPropertyImplDecl *propImpl,
1151 const ObjCMethodDecl *GetterMethodDecl,
1152 llvm::Constant *AtomicHelperFn) {
1153
1154 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1155
1156 if (ivar->getType().isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct) {
1157 if (!AtomicHelperFn) {
1158 LValue Src =
1159 EmitLValueForIvar(ObjectTy: TypeOfSelfObject(), Base: LoadObjCSelf(), Ivar: ivar, CVRQualifiers: 0);
1160 LValue Dst = MakeAddrLValue(Addr: ReturnValue, T: ivar->getType());
1161 callCStructCopyConstructor(Dst, Src);
1162 } else {
1163 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1164 emitCPPObjectAtomicGetterCall(CGF&: *this, returnAddr: ReturnValue.emitRawPointer(CGF&: *this),
1165 ivar, AtomicHelperFn);
1166 }
1167 return;
1168 }
1169
1170 // If there's a non-trivial 'get' expression, we just have to emit that.
1171 if (!hasTrivialGetExpr(propImpl)) {
1172 if (!AtomicHelperFn) {
1173 auto *ret = ReturnStmt::Create(Ctx: getContext(), RL: SourceLocation(),
1174 E: propImpl->getGetterCXXConstructor(),
1175 /* NRVOCandidate=*/nullptr);
1176 EmitReturnStmt(S: *ret);
1177 }
1178 else {
1179 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1180 emitCPPObjectAtomicGetterCall(CGF&: *this, returnAddr: ReturnValue.emitRawPointer(CGF&: *this),
1181 ivar, AtomicHelperFn);
1182 }
1183 return;
1184 }
1185
1186 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
1187 QualType propType = prop->getType();
1188 ObjCMethodDecl *getterMethod = propImpl->getGetterMethodDecl();
1189
1190 // Pick an implementation strategy.
1191 PropertyImplStrategy strategy(CGM, propImpl);
1192 switch (strategy.getKind()) {
1193 case PropertyImplStrategy::Native: {
1194 // We don't need to do anything for a zero-size struct.
1195 if (strategy.getIvarSize().isZero())
1196 return;
1197
1198 LValue LV = EmitLValueForIvar(ObjectTy: TypeOfSelfObject(), Base: LoadObjCSelf(), Ivar: ivar, CVRQualifiers: 0);
1199
1200 // Currently, all atomic accesses have to be through integer
1201 // types, so there's no point in trying to pick a prettier type.
1202 uint64_t ivarSize = getContext().toBits(CharSize: strategy.getIvarSize());
1203 llvm::Type *bitcastType = llvm::Type::getIntNTy(C&: getLLVMContext(), N: ivarSize);
1204
1205 // Perform an atomic load. This does not impose ordering constraints.
1206 Address ivarAddr = LV.getAddress();
1207 ivarAddr = ivarAddr.withElementType(ElemTy: bitcastType);
1208 llvm::LoadInst *load = Builder.CreateLoad(Addr: ivarAddr, Name: "load");
1209 load->setAtomic(Ordering: llvm::AtomicOrdering::Unordered);
1210 llvm::Value *ivarVal = load;
1211 if (PointerAuthQualifier PAQ = ivar->getType().getPointerAuth()) {
1212 CGPointerAuthInfo SrcInfo = EmitPointerAuthInfo(Qualifier: PAQ, StorageAddress: ivarAddr);
1213 CGPointerAuthInfo TargetInfo =
1214 CGM.getPointerAuthInfoForType(type: getterMethod->getReturnType());
1215 ivarVal = emitPointerAuthResign(Pointer: ivarVal, PointerType: ivar->getType(), CurAuthInfo: SrcInfo,
1216 NewAuthInfo: TargetInfo, /*isKnownNonNull=*/IsKnownNonNull: false);
1217 }
1218
1219 // Store that value into the return address. Doing this with a
1220 // bitcast is likely to produce some pretty ugly IR, but it's not
1221 // the *most* terrible thing in the world.
1222 llvm::Type *retTy = ConvertType(T: getterMethod->getReturnType());
1223 uint64_t retTySize = CGM.getDataLayout().getTypeSizeInBits(Ty: retTy);
1224 if (ivarSize > retTySize) {
1225 bitcastType = llvm::Type::getIntNTy(C&: getLLVMContext(), N: retTySize);
1226 if (getterMethod->getReturnType()->hasBooleanRepresentation() &&
1227 CGM.getCodeGenOpts().isConvertingBoolWithCmp0())
1228 ivarVal = Builder.CreateICmpNE(
1229 LHS: ivarVal, RHS: llvm::Constant::getNullValue(Ty: ivarVal->getType()));
1230 else
1231 ivarVal = Builder.CreateTrunc(V: ivarVal, DestTy: bitcastType);
1232 }
1233 Builder.CreateStore(Val: ivarVal, Addr: ReturnValue.withElementType(ElemTy: bitcastType));
1234
1235 // Make sure we don't do an autorelease.
1236 AutoreleaseResult = false;
1237 return;
1238 }
1239
1240 case PropertyImplStrategy::GetSetProperty: {
1241 llvm::FunctionCallee getPropertyFn =
1242 CGM.getObjCRuntime().GetPropertyGetFunction();
1243
1244 if (ivar->getType().getPointerAuth()) {
1245 // This currently cannot be hit, but if we ever allow objc pointers
1246 // to be signed, this will become possible. Reaching here would require
1247 // a copy, weak, etc property backed by an authenticated pointer.
1248 CGM.ErrorUnsupported(D: propImpl,
1249 Type: "Obj-C getter requiring pointer authentication");
1250 return;
1251 }
1252
1253 if (!getPropertyFn) {
1254 CGM.ErrorUnsupported(D: propImpl, Type: "Obj-C getter requiring atomic copy");
1255 return;
1256 }
1257 CGCallee callee = CGCallee::forDirect(functionPtr: getPropertyFn);
1258
1259 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
1260 // FIXME: Can't this be simpler? This might even be worse than the
1261 // corresponding gcc code.
1262 llvm::Value *cmd = emitCmdValueForGetterSetterBody(CGF&: *this, MD: getterMethod);
1263 llvm::Value *self = Builder.CreateBitCast(V: LoadObjCSelf(), DestTy: VoidPtrTy);
1264 llvm::Value *ivarOffset =
1265 EmitIvarOffsetAsPointerDiff(Interface: classImpl->getClassInterface(), Ivar: ivar);
1266
1267 CallArgList args;
1268 args.add(rvalue: RValue::get(V: self), type: getContext().getObjCIdType());
1269 args.add(rvalue: RValue::get(V: cmd), type: getContext().getObjCSelType());
1270 args.add(rvalue: RValue::get(V: ivarOffset), type: getContext().getPointerDiffType());
1271 args.add(rvalue: RValue::get(V: Builder.getInt1(V: strategy.isAtomic())),
1272 type: getContext().BoolTy);
1273
1274 // FIXME: We shouldn't need to get the function info here, the
1275 // runtime already should have computed it to build the function.
1276 llvm::CallBase *CallInstruction;
1277 RValue RV = EmitCall(CallInfo: getTypes().arrangeBuiltinFunctionCall(
1278 resultType: getContext().getObjCIdType(), args),
1279 Callee: callee, ReturnValue: ReturnValueSlot(), Args: args, CallOrInvoke: &CallInstruction);
1280 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(Val: CallInstruction))
1281 call->setTailCall();
1282
1283 // We need to fix the type here. Ivars with copy & retain are
1284 // always objects so we don't need to worry about complex or
1285 // aggregates.
1286 RV = RValue::get(V: Builder.CreateBitCast(
1287 V: RV.getScalarVal(),
1288 DestTy: getTypes().ConvertType(T: getterMethod->getReturnType())));
1289
1290 EmitReturnOfRValue(RV, Ty: propType);
1291
1292 // objc_getProperty does an autorelease, so we should suppress ours.
1293 AutoreleaseResult = false;
1294
1295 return;
1296 }
1297
1298 case PropertyImplStrategy::CopyStruct:
1299 emitStructGetterCall(CGF&: *this, ivar, isAtomic: strategy.isAtomic(),
1300 hasStrong: strategy.hasStrongMember());
1301 return;
1302
1303 case PropertyImplStrategy::Expression:
1304 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1305 LValue LV = EmitLValueForIvar(ObjectTy: TypeOfSelfObject(), Base: LoadObjCSelf(), Ivar: ivar, CVRQualifiers: 0);
1306
1307 QualType ivarType = ivar->getType();
1308 auto EvaluationKind = getEvaluationKind(T: ivarType);
1309 assert(!ivarType.getPointerAuth() || EvaluationKind == TEK_Scalar);
1310 switch (EvaluationKind) {
1311 case TEK_Complex: {
1312 ComplexPairTy pair = EmitLoadOfComplex(src: LV, loc: SourceLocation());
1313 EmitStoreOfComplex(V: pair, dest: MakeAddrLValue(Addr: ReturnValue, T: ivarType),
1314 /*init*/ isInit: true);
1315 return;
1316 }
1317 case TEK_Aggregate: {
1318 // The return value slot is guaranteed to not be aliased, but
1319 // that's not necessarily the same as "on the stack", so
1320 // we still potentially need objc_memmove_collectable.
1321 EmitAggregateCopy(/* Dest= */ MakeAddrLValue(Addr: ReturnValue, T: ivarType),
1322 /* Src= */ LV, EltTy: ivarType, MayOverlap: getOverlapForReturnValue());
1323 return;
1324 }
1325 case TEK_Scalar: {
1326 llvm::Value *value;
1327 if (propType->isReferenceType()) {
1328 if (ivarType.getPointerAuth()) {
1329 CGM.ErrorUnsupported(D: propImpl,
1330 Type: "Obj-C getter for authenticated reference type");
1331 return;
1332 }
1333 value = LV.getAddress().emitRawPointer(CGF&: *this);
1334 } else {
1335 // We want to load and autoreleaseReturnValue ARC __weak ivars.
1336 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1337 if (getLangOpts().ObjCAutoRefCount) {
1338 value = emitARCRetainLoadOfScalar(CGF&: *this, lvalue: LV, type: ivarType);
1339 } else {
1340 value = EmitARCLoadWeak(addr: LV.getAddress());
1341 }
1342
1343 // Otherwise we want to do a simple load, suppressing the
1344 // final autorelease.
1345 } else {
1346 if (PointerAuthQualifier PAQ = ivar->getType().getPointerAuth()) {
1347 Address ivarAddr = LV.getAddress();
1348 llvm::LoadInst *LoadInst = Builder.CreateLoad(Addr: ivarAddr, Name: "load");
1349 llvm::Value *Load = LoadInst;
1350 auto SrcInfo = EmitPointerAuthInfo(Qualifier: PAQ, StorageAddress: ivarAddr);
1351 auto TargetInfo =
1352 CGM.getPointerAuthInfoForType(type: getterMethod->getReturnType());
1353 Load = emitPointerAuthResign(Pointer: Load, PointerType: ivarType, CurAuthInfo: SrcInfo, NewAuthInfo: TargetInfo,
1354 /*isKnownNonNull=*/IsKnownNonNull: false);
1355 value = Load;
1356 } else
1357 value = EmitLoadOfLValue(V: LV, Loc: SourceLocation()).getScalarVal();
1358
1359 AutoreleaseResult = false;
1360 }
1361
1362 value = Builder.CreateBitCast(
1363 V: value, DestTy: ConvertType(T: GetterMethodDecl->getReturnType()));
1364 }
1365
1366 EmitReturnOfRValue(RV: RValue::get(V: value), Ty: propType);
1367 return;
1368 }
1369 }
1370 llvm_unreachable("bad evaluation kind");
1371 }
1372
1373 }
1374 llvm_unreachable("bad @property implementation strategy!");
1375}
1376
1377/// emitStructSetterCall - Call the runtime function to store the value
1378/// from the first formal parameter into the given ivar.
1379static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
1380 ObjCIvarDecl *ivar) {
1381 // objc_copyStruct (&structIvar, &Arg,
1382 // sizeof (struct something), true, false);
1383 CallArgList args;
1384
1385 // The first argument is the address of the ivar.
1386 llvm::Value *ivarAddr =
1387 CGF.EmitLValueForIvar(ObjectTy: CGF.TypeOfSelfObject(), Base: CGF.LoadObjCSelf(), Ivar: ivar, CVRQualifiers: 0)
1388 .getPointer(CGF);
1389 ivarAddr = CGF.Builder.CreateBitCast(V: ivarAddr, DestTy: CGF.Int8PtrTy);
1390 args.add(rvalue: RValue::get(V: ivarAddr), type: CGF.getContext().VoidPtrTy);
1391
1392 // The second argument is the address of the parameter variable.
1393 ParmVarDecl *argVar = *OMD->param_begin();
1394 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1395 argVar->getType().getNonReferenceType(), VK_LValue,
1396 SourceLocation());
1397 llvm::Value *argAddr = CGF.EmitLValue(E: &argRef).getPointer(CGF);
1398 args.add(rvalue: RValue::get(V: argAddr), type: CGF.getContext().VoidPtrTy);
1399
1400 // The third argument is the sizeof the type.
1401 llvm::Value *size =
1402 CGF.CGM.getSize(numChars: CGF.getContext().getTypeSizeInChars(T: ivar->getType()));
1403 args.add(rvalue: RValue::get(V: size), type: CGF.getContext().getSizeType());
1404
1405 // The fourth argument is the 'isAtomic' flag.
1406 args.add(rvalue: RValue::get(V: CGF.Builder.getTrue()), type: CGF.getContext().BoolTy);
1407
1408 // The fifth argument is the 'hasStrong' flag.
1409 // FIXME: should this really always be false?
1410 args.add(rvalue: RValue::get(V: CGF.Builder.getFalse()), type: CGF.getContext().BoolTy);
1411
1412 llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
1413 CGCallee callee = CGCallee::forDirect(functionPtr: fn);
1414 CGF.EmitCall(
1415 CallInfo: CGF.getTypes().arrangeBuiltinFunctionCall(resultType: CGF.getContext().VoidTy, args),
1416 Callee: callee, ReturnValue: ReturnValueSlot(), Args: args);
1417}
1418
1419/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1420/// the value from the first formal parameter into the given ivar, using
1421/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
1422static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
1423 ObjCMethodDecl *OMD,
1424 ObjCIvarDecl *ivar,
1425 llvm::Constant *AtomicHelperFn) {
1426 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
1427 // AtomicHelperFn);
1428 CallArgList args;
1429
1430 // The first argument is the address of the ivar.
1431 llvm::Value *ivarAddr =
1432 CGF.EmitLValueForIvar(ObjectTy: CGF.TypeOfSelfObject(), Base: CGF.LoadObjCSelf(), Ivar: ivar, CVRQualifiers: 0)
1433 .getPointer(CGF);
1434 args.add(rvalue: RValue::get(V: ivarAddr), type: CGF.getContext().VoidPtrTy);
1435
1436 // The second argument is the address of the parameter variable.
1437 ParmVarDecl *argVar = *OMD->param_begin();
1438 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1439 argVar->getType().getNonReferenceType(), VK_LValue,
1440 SourceLocation());
1441 llvm::Value *argAddr = CGF.EmitLValue(E: &argRef).getPointer(CGF);
1442 args.add(rvalue: RValue::get(V: argAddr), type: CGF.getContext().VoidPtrTy);
1443
1444 // Third argument is the helper function.
1445 args.add(rvalue: RValue::get(V: AtomicHelperFn), type: CGF.getContext().VoidPtrTy);
1446
1447 llvm::FunctionCallee fn =
1448 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
1449 CGCallee callee = CGCallee::forDirect(functionPtr: fn);
1450 CGF.EmitCall(
1451 CallInfo: CGF.getTypes().arrangeBuiltinFunctionCall(resultType: CGF.getContext().VoidTy, args),
1452 Callee: callee, ReturnValue: ReturnValueSlot(), Args: args);
1453}
1454
1455
1456static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1457 Expr *setter = PID->getSetterCXXAssignment();
1458 if (!setter) return true;
1459
1460 // Sema only makes only of these when the ivar has a C++ class type,
1461 // so the form is pretty constrained.
1462
1463 // An operator call is trivial if the function it calls is trivial.
1464 // This also implies that there's nothing non-trivial going on with
1465 // the arguments, because operator= can only be trivial if it's a
1466 // synthesized assignment operator and therefore both parameters are
1467 // references.
1468 if (CallExpr *call = dyn_cast<CallExpr>(Val: setter)) {
1469 if (const FunctionDecl *callee
1470 = dyn_cast_or_null<FunctionDecl>(Val: call->getCalleeDecl()))
1471 if (callee->isTrivial())
1472 return true;
1473 return false;
1474 }
1475
1476 assert(isa<ExprWithCleanups>(setter));
1477 return false;
1478}
1479
1480static bool UseOptimizedSetter(CodeGenModule &CGM) {
1481 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
1482 return false;
1483 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
1484}
1485
1486void
1487CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
1488 const ObjCPropertyImplDecl *propImpl,
1489 llvm::Constant *AtomicHelperFn) {
1490 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1491 ObjCMethodDecl *setterMethod = propImpl->getSetterMethodDecl();
1492
1493 if (ivar->getType().isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct) {
1494 ParmVarDecl *PVD = *setterMethod->param_begin();
1495 if (!AtomicHelperFn) {
1496 // Call the move assignment operator instead of calling the copy
1497 // assignment operator and destructor.
1498 LValue Dst = EmitLValueForIvar(ObjectTy: TypeOfSelfObject(), Base: LoadObjCSelf(), Ivar: ivar,
1499 /*quals*/ CVRQualifiers: 0);
1500 LValue Src = MakeAddrLValue(Addr: GetAddrOfLocalVar(VD: PVD), T: ivar->getType());
1501 callCStructMoveAssignmentOperator(Dst, Src);
1502 } else {
1503 // If atomic, assignment is called via a locking api.
1504 emitCPPObjectAtomicSetterCall(CGF&: *this, OMD: setterMethod, ivar, AtomicHelperFn);
1505 }
1506 // Decativate the destructor for the setter parameter.
1507 DeactivateCleanupBlock(Cleanup: CalleeDestructedParamCleanups[PVD], DominatingIP: AllocaInsertPt);
1508 return;
1509 }
1510
1511 // Just use the setter expression if Sema gave us one and it's
1512 // non-trivial.
1513 if (!hasTrivialSetExpr(PID: propImpl)) {
1514 if (!AtomicHelperFn)
1515 // If non-atomic, assignment is called directly.
1516 EmitStmt(S: propImpl->getSetterCXXAssignment());
1517 else
1518 // If atomic, assignment is called via a locking api.
1519 emitCPPObjectAtomicSetterCall(CGF&: *this, OMD: setterMethod, ivar,
1520 AtomicHelperFn);
1521 return;
1522 }
1523
1524 PropertyImplStrategy strategy(CGM, propImpl);
1525 switch (strategy.getKind()) {
1526 case PropertyImplStrategy::Native: {
1527 // We don't need to do anything for a zero-size struct.
1528 if (strategy.getIvarSize().isZero())
1529 return;
1530
1531 Address argAddr = GetAddrOfLocalVar(VD: *setterMethod->param_begin());
1532
1533 LValue ivarLValue =
1534 EmitLValueForIvar(ObjectTy: TypeOfSelfObject(), Base: LoadObjCSelf(), Ivar: ivar, /*quals*/ CVRQualifiers: 0);
1535 Address ivarAddr = ivarLValue.getAddress();
1536
1537 // Currently, all atomic accesses have to be through integer
1538 // types, so there's no point in trying to pick a prettier type.
1539 llvm::Type *castType = llvm::Type::getIntNTy(
1540 C&: getLLVMContext(), N: getContext().toBits(CharSize: strategy.getIvarSize()));
1541
1542 // Cast both arguments to the chosen operation type.
1543 argAddr = argAddr.withElementType(ElemTy: castType);
1544 ivarAddr = ivarAddr.withElementType(ElemTy: castType);
1545
1546 llvm::Value *load = Builder.CreateLoad(Addr: argAddr);
1547
1548 if (PointerAuthQualifier PAQ = ivar->getType().getPointerAuth()) {
1549 QualType PropertyType = propImpl->getPropertyDecl()->getType();
1550 CGPointerAuthInfo SrcInfo = CGM.getPointerAuthInfoForType(type: PropertyType);
1551 CGPointerAuthInfo TargetInfo = EmitPointerAuthInfo(Qualifier: PAQ, StorageAddress: ivarAddr);
1552 load = emitPointerAuthResign(Pointer: load, PointerType: ivar->getType(), CurAuthInfo: SrcInfo, NewAuthInfo: TargetInfo,
1553 /*isKnownNonNull=*/IsKnownNonNull: false);
1554 }
1555
1556 // Perform an atomic store. There are no memory ordering requirements.
1557 llvm::StoreInst *store = Builder.CreateStore(Val: load, Addr: ivarAddr);
1558 store->setAtomic(Ordering: llvm::AtomicOrdering::Unordered);
1559 return;
1560 }
1561
1562 case PropertyImplStrategy::GetSetProperty:
1563 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1564
1565 llvm::FunctionCallee setOptimizedPropertyFn = nullptr;
1566 llvm::FunctionCallee setPropertyFn = nullptr;
1567 if (UseOptimizedSetter(CGM)) {
1568 // 10.8 and iOS 6.0 code and GC is off
1569 setOptimizedPropertyFn =
1570 CGM.getObjCRuntime().GetOptimizedPropertySetFunction(
1571 atomic: strategy.isAtomic(), copy: strategy.isCopy());
1572 if (!setOptimizedPropertyFn) {
1573 CGM.ErrorUnsupported(D: propImpl, Type: "Obj-C optimized setter - NYI");
1574 return;
1575 }
1576 }
1577 else {
1578 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1579 if (!setPropertyFn) {
1580 CGM.ErrorUnsupported(D: propImpl, Type: "Obj-C setter requiring atomic copy");
1581 return;
1582 }
1583 }
1584
1585 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1586 // <is-atomic>, <is-copy>).
1587 llvm::Value *cmd = emitCmdValueForGetterSetterBody(CGF&: *this, MD: setterMethod);
1588 llvm::Value *self =
1589 Builder.CreateBitCast(V: LoadObjCSelf(), DestTy: VoidPtrTy);
1590 llvm::Value *ivarOffset =
1591 EmitIvarOffsetAsPointerDiff(Interface: classImpl->getClassInterface(), Ivar: ivar);
1592 Address argAddr = GetAddrOfLocalVar(VD: *setterMethod->param_begin());
1593 llvm::Value *arg = Builder.CreateLoad(Addr: argAddr, Name: "arg");
1594 arg = Builder.CreateBitCast(V: arg, DestTy: VoidPtrTy);
1595
1596 CallArgList args;
1597 args.add(rvalue: RValue::get(V: self), type: getContext().getObjCIdType());
1598 args.add(rvalue: RValue::get(V: cmd), type: getContext().getObjCSelType());
1599 if (setOptimizedPropertyFn) {
1600 args.add(rvalue: RValue::get(V: arg), type: getContext().getObjCIdType());
1601 args.add(rvalue: RValue::get(V: ivarOffset), type: getContext().getPointerDiffType());
1602 CGCallee callee = CGCallee::forDirect(functionPtr: setOptimizedPropertyFn);
1603 EmitCall(CallInfo: getTypes().arrangeBuiltinFunctionCall(resultType: getContext().VoidTy, args),
1604 Callee: callee, ReturnValue: ReturnValueSlot(), Args: args);
1605 } else {
1606 args.add(rvalue: RValue::get(V: ivarOffset), type: getContext().getPointerDiffType());
1607 args.add(rvalue: RValue::get(V: arg), type: getContext().getObjCIdType());
1608 args.add(rvalue: RValue::get(V: Builder.getInt1(V: strategy.isAtomic())),
1609 type: getContext().BoolTy);
1610 args.add(rvalue: RValue::get(V: Builder.getInt1(V: strategy.isCopy())),
1611 type: getContext().BoolTy);
1612 // FIXME: We shouldn't need to get the function info here, the runtime
1613 // already should have computed it to build the function.
1614 CGCallee callee = CGCallee::forDirect(functionPtr: setPropertyFn);
1615 EmitCall(CallInfo: getTypes().arrangeBuiltinFunctionCall(resultType: getContext().VoidTy, args),
1616 Callee: callee, ReturnValue: ReturnValueSlot(), Args: args);
1617 }
1618
1619 return;
1620 }
1621
1622 case PropertyImplStrategy::CopyStruct:
1623 emitStructSetterCall(CGF&: *this, OMD: setterMethod, ivar);
1624 return;
1625
1626 case PropertyImplStrategy::Expression:
1627 break;
1628 }
1629
1630 // Otherwise, fake up some ASTs and emit a normal assignment.
1631 ValueDecl *selfDecl = setterMethod->getSelfDecl();
1632 DeclRefExpr self(getContext(), selfDecl, false, selfDecl->getType(),
1633 VK_LValue, SourceLocation());
1634 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack, selfDecl->getType(),
1635 CK_LValueToRValue, &self, VK_PRValue,
1636 FPOptionsOverride());
1637 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
1638 SourceLocation(), SourceLocation(),
1639 &selfLoad, true, true);
1640
1641 ParmVarDecl *argDecl = *setterMethod->param_begin();
1642 QualType argType = argDecl->getType().getNonReferenceType();
1643 DeclRefExpr arg(getContext(), argDecl, false, argType, VK_LValue,
1644 SourceLocation());
1645 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1646 argType.getUnqualifiedType(), CK_LValueToRValue,
1647 &arg, VK_PRValue, FPOptionsOverride());
1648
1649 // The property type can differ from the ivar type in some situations with
1650 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1651 // The following absurdity is just to ensure well-formed IR.
1652 CastKind argCK = CK_NoOp;
1653 if (ivarRef.getType()->isObjCObjectPointerType()) {
1654 if (argLoad.getType()->isObjCObjectPointerType())
1655 argCK = CK_BitCast;
1656 else if (argLoad.getType()->isBlockPointerType())
1657 argCK = CK_BlockPointerToObjCPointerCast;
1658 else
1659 argCK = CK_CPointerToObjCPointerCast;
1660 } else if (ivarRef.getType()->isBlockPointerType()) {
1661 if (argLoad.getType()->isBlockPointerType())
1662 argCK = CK_BitCast;
1663 else
1664 argCK = CK_AnyPointerToBlockPointerCast;
1665 } else if (ivarRef.getType()->isPointerType()) {
1666 argCK = CK_BitCast;
1667 } else if (argLoad.getType()->isAtomicType() &&
1668 !ivarRef.getType()->isAtomicType()) {
1669 argCK = CK_AtomicToNonAtomic;
1670 } else if (!argLoad.getType()->isAtomicType() &&
1671 ivarRef.getType()->isAtomicType()) {
1672 argCK = CK_NonAtomicToAtomic;
1673 }
1674 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack, ivarRef.getType(), argCK,
1675 &argLoad, VK_PRValue, FPOptionsOverride());
1676 Expr *finalArg = &argLoad;
1677 if (!getContext().hasSameUnqualifiedType(T1: ivarRef.getType(),
1678 T2: argLoad.getType()))
1679 finalArg = &argCast;
1680
1681 BinaryOperator *assign = BinaryOperator::Create(
1682 C: getContext(), lhs: &ivarRef, rhs: finalArg, opc: BO_Assign, ResTy: ivarRef.getType(),
1683 VK: VK_PRValue, OK: OK_Ordinary, opLoc: SourceLocation(), FPFeatures: FPOptionsOverride());
1684 EmitStmt(S: assign);
1685}
1686
1687/// Generate an Objective-C property setter function.
1688///
1689/// The given Decl must be an ObjCImplementationDecl. \@synthesize
1690/// is illegal within a category.
1691void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1692 const ObjCPropertyImplDecl *PID) {
1693 llvm::Constant *AtomicHelperFn =
1694 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
1695 ObjCMethodDecl *OMD = PID->getSetterMethodDecl();
1696 assert(OMD && "Invalid call to generate setter (empty method)");
1697 StartObjCMethod(OMD, CD: IMP->getClassInterface());
1698
1699 generateObjCSetterBody(classImpl: IMP, propImpl: PID, AtomicHelperFn);
1700
1701 FinishFunction(EndLoc: OMD->getEndLoc());
1702}
1703
1704namespace {
1705 struct DestroyIvar final : EHScopeStack::Cleanup {
1706 private:
1707 llvm::Value *addr;
1708 const ObjCIvarDecl *ivar;
1709 CodeGenFunction::Destroyer *destroyer;
1710 bool useEHCleanupForArray;
1711 public:
1712 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1713 CodeGenFunction::Destroyer *destroyer,
1714 bool useEHCleanupForArray)
1715 : addr(addr), ivar(ivar), destroyer(destroyer),
1716 useEHCleanupForArray(useEHCleanupForArray) {}
1717
1718 void Emit(CodeGenFunction &CGF, Flags flags) override {
1719 LValue lvalue
1720 = CGF.EmitLValueForIvar(ObjectTy: CGF.TypeOfSelfObject(), Base: addr, Ivar: ivar, /*CVR*/ CVRQualifiers: 0);
1721 CGF.emitDestroy(addr: lvalue.getAddress(), type: ivar->getType(), destroyer,
1722 useEHCleanupForArray: flags.isForNormalCleanup() && useEHCleanupForArray);
1723 }
1724 };
1725}
1726
1727/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1728static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1729 Address addr,
1730 QualType type) {
1731 llvm::Value *null = getNullForVariable(addr);
1732 CGF.EmitARCStoreStrongCall(addr, value: null, /*ignored*/ resultIgnored: true);
1733}
1734
1735static void emitCXXDestructMethod(CodeGenFunction &CGF,
1736 ObjCImplementationDecl *impl) {
1737 CodeGenFunction::RunCleanupsScope scope(CGF);
1738
1739 llvm::Value *self = CGF.LoadObjCSelf();
1740
1741 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1742 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
1743 ivar; ivar = ivar->getNextIvar()) {
1744 QualType type = ivar->getType();
1745
1746 // Check whether the ivar is a destructible type.
1747 QualType::DestructionKind dtorKind = type.isDestructedType();
1748 if (!dtorKind) continue;
1749
1750 CodeGenFunction::Destroyer *destroyer = nullptr;
1751
1752 // Use a call to objc_storeStrong to destroy strong ivars, for the
1753 // general benefit of the tools.
1754 if (dtorKind == QualType::DK_objc_strong_lifetime) {
1755 destroyer = destroyARCStrongWithStore;
1756
1757 // Otherwise use the default for the destruction kind.
1758 } else {
1759 destroyer = CGF.getDestroyer(destructionKind: dtorKind);
1760 }
1761
1762 CleanupKind cleanupKind = CGF.getCleanupKind(kind: dtorKind);
1763
1764 CGF.EHStack.pushCleanup<DestroyIvar>(Kind: cleanupKind, A: self, A: ivar, A: destroyer,
1765 A: cleanupKind & EHCleanup);
1766 }
1767
1768 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1769}
1770
1771void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1772 ObjCMethodDecl *MD,
1773 bool ctor) {
1774 MD->createImplicitParams(Context&: CGM.getContext(), ID: IMP->getClassInterface());
1775 StartObjCMethod(OMD: MD, CD: IMP->getClassInterface());
1776
1777 // Emit .cxx_construct.
1778 if (ctor) {
1779 // Suppress the final autorelease in ARC.
1780 AutoreleaseResult = false;
1781
1782 for (const auto *IvarInit : IMP->inits()) {
1783 FieldDecl *Field = IvarInit->getAnyMember();
1784 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Val: Field);
1785 LValue LV = EmitLValueForIvar(ObjectTy: TypeOfSelfObject(),
1786 Base: LoadObjCSelf(), Ivar, CVRQualifiers: 0);
1787 EmitAggExpr(E: IvarInit->getInit(),
1788 AS: AggValueSlot::forLValue(LV, isDestructed: AggValueSlot::IsDestructed,
1789 needsGC: AggValueSlot::DoesNotNeedGCBarriers,
1790 isAliased: AggValueSlot::IsNotAliased,
1791 mayOverlap: AggValueSlot::DoesNotOverlap));
1792 }
1793 // constructor returns 'self'.
1794 CodeGenTypes &Types = CGM.getTypes();
1795 QualType IdTy(CGM.getContext().getObjCIdType());
1796 llvm::Value *SelfAsId =
1797 Builder.CreateBitCast(V: LoadObjCSelf(), DestTy: Types.ConvertType(T: IdTy));
1798 EmitReturnOfRValue(RV: RValue::get(V: SelfAsId), Ty: IdTy);
1799
1800 // Emit .cxx_destruct.
1801 } else {
1802 emitCXXDestructMethod(CGF&: *this, impl: IMP);
1803 }
1804 FinishFunction();
1805}
1806
1807llvm::Value *CodeGenFunction::LoadObjCSelf() {
1808 VarDecl *Self = cast<ObjCMethodDecl>(Val: CurFuncDecl)->getSelfDecl();
1809 DeclRefExpr DRE(getContext(), Self,
1810 /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
1811 Self->getType(), VK_LValue, SourceLocation());
1812 return EmitLoadOfScalar(lvalue: EmitDeclRefLValue(E: &DRE), Loc: SourceLocation());
1813}
1814
1815QualType CodeGenFunction::TypeOfSelfObject() {
1816 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(Val: CurFuncDecl);
1817 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
1818 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1819 Val: getContext().getCanonicalType(T: selfDecl->getType()));
1820 return PTy->getPointeeType();
1821}
1822
1823void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
1824 llvm::FunctionCallee EnumerationMutationFnPtr =
1825 CGM.getObjCRuntime().EnumerationMutationFunction();
1826 if (!EnumerationMutationFnPtr) {
1827 CGM.ErrorUnsupported(S: &S, Type: "Obj-C fast enumeration for this runtime");
1828 return;
1829 }
1830 CGCallee EnumerationMutationFn =
1831 CGCallee::forDirect(functionPtr: EnumerationMutationFnPtr);
1832
1833 CGDebugInfo *DI = getDebugInfo();
1834 if (DI)
1835 DI->EmitLexicalBlockStart(Builder, Loc: S.getSourceRange().getBegin());
1836
1837 RunCleanupsScope ForScope(*this);
1838
1839 // The local variable comes into scope immediately.
1840 AutoVarEmission variable = AutoVarEmission::invalid();
1841 if (const DeclStmt *SD = dyn_cast<DeclStmt>(Val: S.getElement()))
1842 variable = EmitAutoVarAlloca(var: *cast<VarDecl>(Val: SD->getSingleDecl()));
1843
1844 JumpDest LoopEnd = getJumpDestInCurrentScope(Name: "forcoll.end");
1845
1846 // Fast enumeration state.
1847 QualType StateTy = CGM.getObjCFastEnumerationStateType();
1848 Address StatePtr = CreateMemTemp(T: StateTy, Name: "state.ptr");
1849 EmitNullInitialization(DestPtr: StatePtr, Ty: StateTy);
1850
1851 // Number of elements in the items array.
1852 static const unsigned NumItems = 16;
1853
1854 // Fetch the countByEnumeratingWithState:objects:count: selector.
1855 const IdentifierInfo *II[] = {
1856 &CGM.getContext().Idents.get(Name: "countByEnumeratingWithState"),
1857 &CGM.getContext().Idents.get(Name: "objects"),
1858 &CGM.getContext().Idents.get(Name: "count")};
1859 Selector FastEnumSel =
1860 CGM.getContext().Selectors.getSelector(NumArgs: std::size(II), IIV: &II[0]);
1861
1862 QualType ItemsTy = getContext().getConstantArrayType(
1863 EltTy: getContext().getObjCIdType(), ArySize: llvm::APInt(32, NumItems), SizeExpr: nullptr,
1864 ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
1865 Address ItemsPtr = CreateMemTemp(T: ItemsTy, Name: "items.ptr");
1866
1867 // Emit the collection pointer. In ARC, we do a retain.
1868 llvm::Value *Collection;
1869 if (getLangOpts().ObjCAutoRefCount) {
1870 Collection = EmitARCRetainScalarExpr(expr: S.getCollection());
1871
1872 // Enter a cleanup to do the release.
1873 EmitObjCConsumeObject(T: S.getCollection()->getType(), Ptr: Collection);
1874 } else {
1875 Collection = EmitScalarExpr(E: S.getCollection());
1876 }
1877
1878 // The 'continue' label needs to appear within the cleanup for the
1879 // collection object.
1880 JumpDest AfterBody = getJumpDestInCurrentScope(Name: "forcoll.next");
1881
1882 // Send it our message:
1883 CallArgList Args;
1884
1885 // The first argument is a temporary of the enumeration-state type.
1886 Args.add(rvalue: RValue::get(Addr: StatePtr, CGF&: *this), type: getContext().getPointerType(T: StateTy));
1887
1888 // The second argument is a temporary array with space for NumItems
1889 // pointers. We'll actually be loading elements from the array
1890 // pointer written into the control state; this buffer is so that
1891 // collections that *aren't* backed by arrays can still queue up
1892 // batches of elements.
1893 Args.add(rvalue: RValue::get(Addr: ItemsPtr, CGF&: *this), type: getContext().getPointerType(T: ItemsTy));
1894
1895 // The third argument is the capacity of that temporary array.
1896 llvm::Type *NSUIntegerTy = ConvertType(T: getContext().getNSUIntegerType());
1897 llvm::Constant *Count = llvm::ConstantInt::get(Ty: NSUIntegerTy, V: NumItems);
1898 Args.add(rvalue: RValue::get(V: Count), type: getContext().getNSUIntegerType());
1899
1900 // Start the enumeration.
1901 RValue CountRV =
1902 CGM.getObjCRuntime().GenerateMessageSend(CGF&: *this, ReturnSlot: ReturnValueSlot(),
1903 ResultType: getContext().getNSUIntegerType(),
1904 Sel: FastEnumSel, Receiver: Collection, CallArgs: Args);
1905
1906 // The initial number of objects that were returned in the buffer.
1907 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
1908
1909 llvm::BasicBlock *EmptyBB = createBasicBlock(name: "forcoll.empty");
1910 llvm::BasicBlock *LoopInitBB = createBasicBlock(name: "forcoll.loopinit");
1911
1912 llvm::Value *zero = llvm::Constant::getNullValue(Ty: NSUIntegerTy);
1913
1914 // If the limit pointer was zero to begin with, the collection is
1915 // empty; skip all this. Set the branch weight assuming this has the same
1916 // probability of exiting the loop as any other loop exit.
1917 uint64_t EntryCount = getCurrentProfileCount();
1918 Builder.CreateCondBr(
1919 Cond: Builder.CreateICmpEQ(LHS: initialBufferLimit, RHS: zero, Name: "iszero"), True: EmptyBB,
1920 False: LoopInitBB,
1921 BranchWeights: createProfileWeights(TrueCount: EntryCount, FalseCount: getProfileCount(S: S.getBody())));
1922
1923 // Otherwise, initialize the loop.
1924 EmitBlock(BB: LoopInitBB);
1925
1926 // Save the initial mutations value. This is the value at an
1927 // address that was written into the state object by
1928 // countByEnumeratingWithState:objects:count:.
1929 Address StateMutationsPtrPtr =
1930 Builder.CreateStructGEP(Addr: StatePtr, Index: 2, Name: "mutationsptr.ptr");
1931 llvm::Value *StateMutationsPtr
1932 = Builder.CreateLoad(Addr: StateMutationsPtrPtr, Name: "mutationsptr");
1933
1934 llvm::Type *UnsignedLongTy = ConvertType(T: getContext().UnsignedLongTy);
1935 llvm::Value *initialMutations =
1936 Builder.CreateAlignedLoad(Ty: UnsignedLongTy, Addr: StateMutationsPtr,
1937 Align: getPointerAlign(), Name: "forcoll.initial-mutations");
1938
1939 // Start looping. This is the point we return to whenever we have a
1940 // fresh, non-empty batch of objects.
1941 llvm::BasicBlock *LoopBodyBB = createBasicBlock(name: "forcoll.loopbody");
1942 EmitBlock(BB: LoopBodyBB);
1943
1944 // The current index into the buffer.
1945 llvm::PHINode *index = Builder.CreatePHI(Ty: NSUIntegerTy, NumReservedValues: 3, Name: "forcoll.index");
1946 index->addIncoming(V: zero, BB: LoopInitBB);
1947
1948 // The current buffer size.
1949 llvm::PHINode *count = Builder.CreatePHI(Ty: NSUIntegerTy, NumReservedValues: 3, Name: "forcoll.count");
1950 count->addIncoming(V: initialBufferLimit, BB: LoopInitBB);
1951
1952 incrementProfileCounter(S: &S);
1953
1954 // Check whether the mutations value has changed from where it was
1955 // at start. StateMutationsPtr should actually be invariant between
1956 // refreshes.
1957 StateMutationsPtr = Builder.CreateLoad(Addr: StateMutationsPtrPtr, Name: "mutationsptr");
1958 llvm::Value *currentMutations
1959 = Builder.CreateAlignedLoad(Ty: UnsignedLongTy, Addr: StateMutationsPtr,
1960 Align: getPointerAlign(), Name: "statemutations");
1961
1962 llvm::BasicBlock *WasMutatedBB = createBasicBlock(name: "forcoll.mutated");
1963 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock(name: "forcoll.notmutated");
1964
1965 Builder.CreateCondBr(Cond: Builder.CreateICmpEQ(LHS: currentMutations, RHS: initialMutations),
1966 True: WasNotMutatedBB, False: WasMutatedBB);
1967
1968 // If so, call the enumeration-mutation function.
1969 EmitBlock(BB: WasMutatedBB);
1970 llvm::Type *ObjCIdType = ConvertType(T: getContext().getObjCIdType());
1971 llvm::Value *V =
1972 Builder.CreateBitCast(V: Collection, DestTy: ObjCIdType);
1973 CallArgList Args2;
1974 Args2.add(rvalue: RValue::get(V), type: getContext().getObjCIdType());
1975 // FIXME: We shouldn't need to get the function info here, the runtime already
1976 // should have computed it to build the function.
1977 EmitCall(
1978 CallInfo: CGM.getTypes().arrangeBuiltinFunctionCall(resultType: getContext().VoidTy, args: Args2),
1979 Callee: EnumerationMutationFn, ReturnValue: ReturnValueSlot(), Args: Args2);
1980
1981 // Otherwise, or if the mutation function returns, just continue.
1982 EmitBlock(BB: WasNotMutatedBB);
1983
1984 // Initialize the element variable.
1985 RunCleanupsScope elementVariableScope(*this);
1986 bool elementIsVariable;
1987 LValue elementLValue;
1988 QualType elementType;
1989 if (const DeclStmt *SD = dyn_cast<DeclStmt>(Val: S.getElement())) {
1990 // Initialize the variable, in case it's a __block variable or something.
1991 EmitAutoVarInit(emission: variable);
1992
1993 const VarDecl *D = cast<VarDecl>(Val: SD->getSingleDecl());
1994 DeclRefExpr tempDRE(getContext(), const_cast<VarDecl *>(D), false,
1995 D->getType(), VK_LValue, SourceLocation());
1996 elementLValue = EmitLValue(E: &tempDRE);
1997 elementType = D->getType();
1998 elementIsVariable = true;
1999
2000 if (D->isARCPseudoStrong())
2001 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
2002 } else {
2003 elementLValue = LValue(); // suppress warning
2004 elementType = cast<Expr>(Val: S.getElement())->getType();
2005 elementIsVariable = false;
2006 }
2007 llvm::Type *convertedElementType = ConvertType(T: elementType);
2008
2009 // Fetch the buffer out of the enumeration state.
2010 // TODO: this pointer should actually be invariant between
2011 // refreshes, which would help us do certain loop optimizations.
2012 Address StateItemsPtr =
2013 Builder.CreateStructGEP(Addr: StatePtr, Index: 1, Name: "stateitems.ptr");
2014 llvm::Value *EnumStateItems =
2015 Builder.CreateLoad(Addr: StateItemsPtr, Name: "stateitems");
2016
2017 // Fetch the value at the current index from the buffer.
2018 llvm::Value *CurrentItemPtr = Builder.CreateInBoundsGEP(
2019 Ty: ObjCIdType, Ptr: EnumStateItems, IdxList: index, Name: "currentitem.ptr");
2020 llvm::Value *CurrentItem =
2021 Builder.CreateAlignedLoad(Ty: ObjCIdType, Addr: CurrentItemPtr, Align: getPointerAlign());
2022
2023 if (SanOpts.has(K: SanitizerKind::ObjCCast)) {
2024 // Before using an item from the collection, check that the implicit cast
2025 // from id to the element type is valid. This is done with instrumentation
2026 // roughly corresponding to:
2027 //
2028 // if (![item isKindOfClass:expectedCls]) { /* emit diagnostic */ }
2029 const ObjCObjectPointerType *ObjPtrTy =
2030 elementType->getAsObjCInterfacePointerType();
2031 const ObjCInterfaceType *InterfaceTy =
2032 ObjPtrTy ? ObjPtrTy->getInterfaceType() : nullptr;
2033 if (InterfaceTy) {
2034 auto CheckOrdinal = SanitizerKind::SO_ObjCCast;
2035 auto CheckHandler = SanitizerHandler::InvalidObjCCast;
2036 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
2037 auto &C = CGM.getContext();
2038 assert(InterfaceTy->getDecl() && "No decl for ObjC interface type");
2039 Selector IsKindOfClassSel = GetUnarySelector(name: "isKindOfClass", Ctx&: C);
2040 CallArgList IsKindOfClassArgs;
2041 llvm::Value *Cls =
2042 CGM.getObjCRuntime().GetClass(CGF&: *this, OID: InterfaceTy->getDecl());
2043 IsKindOfClassArgs.add(rvalue: RValue::get(V: Cls), type: C.getObjCClassType());
2044 llvm::Value *IsClass =
2045 CGM.getObjCRuntime()
2046 .GenerateMessageSend(CGF&: *this, ReturnSlot: ReturnValueSlot(), ResultType: C.BoolTy,
2047 Sel: IsKindOfClassSel, Receiver: CurrentItem,
2048 CallArgs: IsKindOfClassArgs)
2049 .getScalarVal();
2050 llvm::Constant *StaticData[] = {
2051 EmitCheckSourceLocation(Loc: S.getBeginLoc()),
2052 EmitCheckTypeDescriptor(T: QualType(InterfaceTy, 0))};
2053 EmitCheck(Checked: {{IsClass, CheckOrdinal}}, Check: CheckHandler,
2054 StaticArgs: ArrayRef<llvm::Constant *>(StaticData), DynamicArgs: CurrentItem);
2055 }
2056 }
2057
2058 // Cast that value to the right type.
2059 CurrentItem = Builder.CreateBitCast(V: CurrentItem, DestTy: convertedElementType,
2060 Name: "currentitem");
2061
2062 // Make sure we have an l-value. Yes, this gets evaluated every
2063 // time through the loop.
2064 if (!elementIsVariable) {
2065 elementLValue = EmitLValue(E: cast<Expr>(Val: S.getElement()));
2066 EmitStoreThroughLValue(Src: RValue::get(V: CurrentItem), Dst: elementLValue);
2067 } else {
2068 EmitStoreThroughLValue(Src: RValue::get(V: CurrentItem), Dst: elementLValue,
2069 /*isInit*/ true);
2070 }
2071
2072 // If we do have an element variable, this assignment is the end of
2073 // its initialization.
2074 if (elementIsVariable)
2075 EmitAutoVarCleanups(emission: variable);
2076
2077 // Perform the loop body, setting up break and continue labels.
2078 BreakContinueStack.push_back(Elt: BreakContinue(S, LoopEnd, AfterBody));
2079 {
2080 RunCleanupsScope Scope(*this);
2081 EmitStmt(S: S.getBody());
2082 }
2083 BreakContinueStack.pop_back();
2084
2085 // Destroy the element variable now.
2086 elementVariableScope.ForceCleanup();
2087
2088 // Check whether there are more elements.
2089 EmitBlock(BB: AfterBody.getBlock());
2090
2091 llvm::BasicBlock *FetchMoreBB = createBasicBlock(name: "forcoll.refetch");
2092
2093 // First we check in the local buffer.
2094 llvm::Value *indexPlusOne =
2095 Builder.CreateNUWAdd(LHS: index, RHS: llvm::ConstantInt::get(Ty: NSUIntegerTy, V: 1));
2096
2097 // If we haven't overrun the buffer yet, we can continue.
2098 // Set the branch weights based on the simplifying assumption that this is
2099 // like a while-loop, i.e., ignoring that the false branch fetches more
2100 // elements and then returns to the loop.
2101 Builder.CreateCondBr(
2102 Cond: Builder.CreateICmpULT(LHS: indexPlusOne, RHS: count), True: LoopBodyBB, False: FetchMoreBB,
2103 BranchWeights: createProfileWeights(TrueCount: getProfileCount(S: S.getBody()), FalseCount: EntryCount));
2104
2105 index->addIncoming(V: indexPlusOne, BB: AfterBody.getBlock());
2106 count->addIncoming(V: count, BB: AfterBody.getBlock());
2107
2108 // Otherwise, we have to fetch more elements.
2109 EmitBlock(BB: FetchMoreBB);
2110
2111 CountRV =
2112 CGM.getObjCRuntime().GenerateMessageSend(CGF&: *this, ReturnSlot: ReturnValueSlot(),
2113 ResultType: getContext().getNSUIntegerType(),
2114 Sel: FastEnumSel, Receiver: Collection, CallArgs: Args);
2115
2116 // If we got a zero count, we're done.
2117 llvm::Value *refetchCount = CountRV.getScalarVal();
2118
2119 // (note that the message send might split FetchMoreBB)
2120 index->addIncoming(V: zero, BB: Builder.GetInsertBlock());
2121 count->addIncoming(V: refetchCount, BB: Builder.GetInsertBlock());
2122
2123 Builder.CreateCondBr(Cond: Builder.CreateICmpEQ(LHS: refetchCount, RHS: zero),
2124 True: EmptyBB, False: LoopBodyBB);
2125
2126 // No more elements.
2127 EmitBlock(BB: EmptyBB);
2128
2129 if (!elementIsVariable) {
2130 // If the element was not a declaration, set it to be null.
2131
2132 llvm::Value *null = llvm::Constant::getNullValue(Ty: convertedElementType);
2133 elementLValue = EmitLValue(E: cast<Expr>(Val: S.getElement()));
2134 EmitStoreThroughLValue(Src: RValue::get(V: null), Dst: elementLValue);
2135 }
2136
2137 if (DI)
2138 DI->EmitLexicalBlockEnd(Builder, Loc: S.getSourceRange().getEnd());
2139
2140 ForScope.ForceCleanup();
2141 EmitBlock(BB: LoopEnd.getBlock());
2142}
2143
2144void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
2145 CGM.getObjCRuntime().EmitTryStmt(CGF&: *this, S);
2146}
2147
2148void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
2149 CGM.getObjCRuntime().EmitThrowStmt(CGF&: *this, S);
2150}
2151
2152void CodeGenFunction::EmitObjCAtSynchronizedStmt(
2153 const ObjCAtSynchronizedStmt &S) {
2154 CGM.getObjCRuntime().EmitSynchronizedStmt(CGF&: *this, S);
2155}
2156
2157namespace {
2158 struct CallObjCRelease final : EHScopeStack::Cleanup {
2159 CallObjCRelease(llvm::Value *object) : object(object) {}
2160 llvm::Value *object;
2161
2162 void Emit(CodeGenFunction &CGF, Flags flags) override {
2163 // Releases at the end of the full-expression are imprecise.
2164 CGF.EmitARCRelease(value: object, precise: ARCImpreciseLifetime);
2165 }
2166 };
2167}
2168
2169/// Produce the code for a CK_ARCConsumeObject. Does a primitive
2170/// release at the end of the full-expression.
2171llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
2172 llvm::Value *object) {
2173 // If we're in a conditional branch, we need to make the cleanup
2174 // conditional.
2175 pushFullExprCleanup<CallObjCRelease>(kind: getARCCleanupKind(), A: object);
2176 return object;
2177}
2178
2179llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
2180 llvm::Value *value) {
2181 return EmitARCRetainAutorelease(type, value);
2182}
2183
2184/// Given a number of pointers, inform the optimizer that they're
2185/// being intrinsically used up until this point in the program.
2186void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
2187 llvm::Function *&fn = CGM.getObjCEntrypoints().clang_arc_use;
2188 if (!fn)
2189 fn = CGM.getIntrinsic(IID: llvm::Intrinsic::objc_clang_arc_use);
2190
2191 // This isn't really a "runtime" function, but as an intrinsic it
2192 // doesn't really matter as long as we align things up.
2193 EmitNounwindRuntimeCall(callee: fn, args: values);
2194}
2195
2196/// Emit a call to "clang.arc.noop.use", which consumes the result of a call
2197/// that has operand bundle "clang.arc.attachedcall".
2198void CodeGenFunction::EmitARCNoopIntrinsicUse(ArrayRef<llvm::Value *> values) {
2199 llvm::Function *&fn = CGM.getObjCEntrypoints().clang_arc_noop_use;
2200 if (!fn)
2201 fn = CGM.getIntrinsic(IID: llvm::Intrinsic::objc_clang_arc_noop_use);
2202 EmitNounwindRuntimeCall(callee: fn, args: values);
2203}
2204
2205static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM, llvm::Value *RTF) {
2206 if (auto *F = dyn_cast<llvm::Function>(Val: RTF)) {
2207 // If the target runtime doesn't naturally support ARC, emit weak
2208 // references to the runtime support library. We don't really
2209 // permit this to fail, but we need a particular relocation style.
2210 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC() &&
2211 !CGM.getTriple().isOSBinFormatCOFF()) {
2212 F->setLinkage(llvm::Function::ExternalWeakLinkage);
2213 }
2214 }
2215}
2216
2217static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM,
2218 llvm::FunctionCallee RTF) {
2219 setARCRuntimeFunctionLinkage(CGM, RTF: RTF.getCallee());
2220}
2221
2222static llvm::Function *getARCIntrinsic(llvm::Intrinsic::ID IntID,
2223 CodeGenModule &CGM) {
2224 llvm::Function *fn = CGM.getIntrinsic(IID: IntID);
2225 setARCRuntimeFunctionLinkage(CGM, RTF: fn);
2226 return fn;
2227}
2228
2229/// Perform an operation having the signature
2230/// i8* (i8*)
2231/// where a null input causes a no-op and returns null.
2232static llvm::Value *emitARCValueOperation(
2233 CodeGenFunction &CGF, llvm::Value *value, llvm::Type *returnType,
2234 llvm::Function *&fn, llvm::Intrinsic::ID IntID,
2235 llvm::CallInst::TailCallKind tailKind = llvm::CallInst::TCK_None) {
2236 if (isa<llvm::ConstantPointerNull>(Val: value))
2237 return value;
2238
2239 if (!fn)
2240 fn = getARCIntrinsic(IntID, CGM&: CGF.CGM);
2241
2242 // Cast the argument to 'id'.
2243 llvm::Type *origType = returnType ? returnType : value->getType();
2244 value = CGF.Builder.CreateBitCast(V: value, DestTy: CGF.Int8PtrTy);
2245
2246 // Call the function.
2247 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(callee: fn, args: value);
2248 call->setTailCallKind(tailKind);
2249
2250 // Cast the result back to the original type.
2251 return CGF.Builder.CreateBitCast(V: call, DestTy: origType);
2252}
2253
2254/// Perform an operation having the following signature:
2255/// i8* (i8**)
2256static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF, Address addr,
2257 llvm::Function *&fn,
2258 llvm::Intrinsic::ID IntID) {
2259 if (!fn)
2260 fn = getARCIntrinsic(IntID, CGM&: CGF.CGM);
2261
2262 return CGF.EmitNounwindRuntimeCall(callee: fn, args: addr.emitRawPointer(CGF));
2263}
2264
2265/// Perform an operation having the following signature:
2266/// i8* (i8**, i8*)
2267static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF, Address addr,
2268 llvm::Value *value,
2269 llvm::Function *&fn,
2270 llvm::Intrinsic::ID IntID,
2271 bool ignored) {
2272 assert(addr.getElementType() == value->getType());
2273
2274 if (!fn)
2275 fn = getARCIntrinsic(IntID, CGM&: CGF.CGM);
2276
2277 llvm::Type *origType = value->getType();
2278
2279 llvm::Value *args[] = {
2280 CGF.Builder.CreateBitCast(V: addr.emitRawPointer(CGF), DestTy: CGF.Int8PtrPtrTy),
2281 CGF.Builder.CreateBitCast(V: value, DestTy: CGF.Int8PtrTy)};
2282 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(callee: fn, args);
2283
2284 if (ignored) return nullptr;
2285
2286 return CGF.Builder.CreateBitCast(V: result, DestTy: origType);
2287}
2288
2289/// Perform an operation having the following signature:
2290/// void (i8**, i8**)
2291static void emitARCCopyOperation(CodeGenFunction &CGF, Address dst, Address src,
2292 llvm::Function *&fn,
2293 llvm::Intrinsic::ID IntID) {
2294 assert(dst.getType() == src.getType());
2295
2296 if (!fn)
2297 fn = getARCIntrinsic(IntID, CGM&: CGF.CGM);
2298
2299 llvm::Value *args[] = {
2300 CGF.Builder.CreateBitCast(V: dst.emitRawPointer(CGF), DestTy: CGF.Int8PtrPtrTy),
2301 CGF.Builder.CreateBitCast(V: src.emitRawPointer(CGF), DestTy: CGF.Int8PtrPtrTy)};
2302 CGF.EmitNounwindRuntimeCall(callee: fn, args);
2303}
2304
2305/// Perform an operation having the signature
2306/// i8* (i8*)
2307/// where a null input causes a no-op and returns null.
2308static llvm::Value *emitObjCValueOperation(CodeGenFunction &CGF,
2309 llvm::Value *value,
2310 llvm::Type *returnType,
2311 llvm::FunctionCallee &fn,
2312 StringRef fnName) {
2313 if (isa<llvm::ConstantPointerNull>(Val: value))
2314 return value;
2315
2316 if (!fn) {
2317 llvm::FunctionType *fnType =
2318 llvm::FunctionType::get(Result: CGF.Int8PtrTy, Params: CGF.Int8PtrTy, isVarArg: false);
2319 fn = CGF.CGM.CreateRuntimeFunction(Ty: fnType, Name: fnName);
2320
2321 // We have Native ARC, so set nonlazybind attribute for performance
2322 if (llvm::Function *f = dyn_cast<llvm::Function>(Val: fn.getCallee()))
2323 if (fnName == "objc_retain")
2324 f->addFnAttr(Kind: llvm::Attribute::NonLazyBind);
2325 }
2326
2327 // Cast the argument to 'id'.
2328 llvm::Type *origType = returnType ? returnType : value->getType();
2329 value = CGF.Builder.CreateBitCast(V: value, DestTy: CGF.Int8PtrTy);
2330
2331 // Call the function.
2332 llvm::CallBase *Inst = CGF.EmitCallOrInvoke(Callee: fn, Args: value);
2333
2334 // Mark calls to objc_autorelease as tail on the assumption that methods
2335 // overriding autorelease do not touch anything on the stack.
2336 if (fnName == "objc_autorelease")
2337 if (auto *Call = dyn_cast<llvm::CallInst>(Val: Inst))
2338 Call->setTailCall();
2339
2340 // Cast the result back to the original type.
2341 return CGF.Builder.CreateBitCast(V: Inst, DestTy: origType);
2342}
2343
2344/// Produce the code to do a retain. Based on the type, calls one of:
2345/// call i8* \@objc_retain(i8* %value)
2346/// call i8* \@objc_retainBlock(i8* %value)
2347llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
2348 if (type->isBlockPointerType())
2349 return EmitARCRetainBlock(value, /*mandatory*/ false);
2350 else
2351 return EmitARCRetainNonBlock(value);
2352}
2353
2354/// Retain the given object, with normal retain semantics.
2355/// call i8* \@objc_retain(i8* %value)
2356llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
2357 return emitARCValueOperation(CGF&: *this, value, returnType: nullptr,
2358 fn&: CGM.getObjCEntrypoints().objc_retain,
2359 IntID: llvm::Intrinsic::objc_retain);
2360}
2361
2362/// Retain the given block, with _Block_copy semantics.
2363/// call i8* \@objc_retainBlock(i8* %value)
2364///
2365/// \param mandatory - If false, emit the call with metadata
2366/// indicating that it's okay for the optimizer to eliminate this call
2367/// if it can prove that the block never escapes except down the stack.
2368llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
2369 bool mandatory) {
2370 llvm::Value *result
2371 = emitARCValueOperation(CGF&: *this, value, returnType: nullptr,
2372 fn&: CGM.getObjCEntrypoints().objc_retainBlock,
2373 IntID: llvm::Intrinsic::objc_retainBlock);
2374
2375 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
2376 // tell the optimizer that it doesn't need to do this copy if the
2377 // block doesn't escape, where being passed as an argument doesn't
2378 // count as escaping.
2379 if (!mandatory && isa<llvm::Instruction>(Val: result)) {
2380 llvm::CallInst *call
2381 = cast<llvm::CallInst>(Val: result->stripPointerCasts());
2382 assert(call->getCalledOperand() ==
2383 CGM.getObjCEntrypoints().objc_retainBlock);
2384
2385 call->setMetadata(Kind: "clang.arc.copy_on_escape",
2386 Node: llvm::MDNode::get(Context&: Builder.getContext(), MDs: {}));
2387 }
2388
2389 return result;
2390}
2391
2392static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF) {
2393 // Fetch the void(void) inline asm which marks that we're going to
2394 // do something with the autoreleased return value.
2395 llvm::InlineAsm *&marker
2396 = CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker;
2397 if (!marker) {
2398 StringRef assembly
2399 = CGF.CGM.getTargetCodeGenInfo()
2400 .getARCRetainAutoreleasedReturnValueMarker();
2401
2402 // If we have an empty assembly string, there's nothing to do.
2403 if (assembly.empty()) {
2404
2405 // Otherwise, at -O0, build an inline asm that we're going to call
2406 // in a moment.
2407 } else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
2408 llvm::FunctionType *type =
2409 llvm::FunctionType::get(Result: CGF.VoidTy, /*variadic*/isVarArg: false);
2410
2411 marker = llvm::InlineAsm::get(Ty: type, AsmString: assembly, Constraints: "", /*sideeffects*/ hasSideEffects: true);
2412
2413 // If we're at -O1 and above, we don't want to litter the code
2414 // with this marker yet, so leave a breadcrumb for the ARC
2415 // optimizer to pick up.
2416 } else {
2417 const char *retainRVMarkerKey = llvm::objcarc::getRVMarkerModuleFlagStr();
2418 if (!CGF.CGM.getModule().getModuleFlag(Key: retainRVMarkerKey)) {
2419 auto *str = llvm::MDString::get(Context&: CGF.getLLVMContext(), Str: assembly);
2420 CGF.CGM.getModule().addModuleFlag(Behavior: llvm::Module::Error,
2421 Key: retainRVMarkerKey, Val: str);
2422 }
2423 }
2424 }
2425
2426 // Call the marker asm if we made one, which we do only at -O0.
2427 if (marker)
2428 CGF.Builder.CreateCall(Callee: marker, Args: {}, OpBundles: CGF.getBundlesForFunclet(Callee: marker));
2429}
2430
2431static llvm::Value *emitOptimizedARCReturnCall(llvm::Value *value,
2432 bool IsRetainRV,
2433 CodeGenFunction &CGF) {
2434 emitAutoreleasedReturnValueMarker(CGF);
2435
2436 // Add operand bundle "clang.arc.attachedcall" to the call instead of emitting
2437 // retainRV or claimRV calls in the IR. We currently do this only when the
2438 // optimization level isn't -O0 since global-isel, which is currently run at
2439 // -O0, doesn't know about the operand bundle.
2440 ObjCEntrypoints &EPs = CGF.CGM.getObjCEntrypoints();
2441 llvm::Function *&EP = IsRetainRV
2442 ? EPs.objc_retainAutoreleasedReturnValue
2443 : EPs.objc_unsafeClaimAutoreleasedReturnValue;
2444 llvm::Intrinsic::ID IID =
2445 IsRetainRV ? llvm::Intrinsic::objc_retainAutoreleasedReturnValue
2446 : llvm::Intrinsic::objc_unsafeClaimAutoreleasedReturnValue;
2447 EP = getARCIntrinsic(IntID: IID, CGM&: CGF.CGM);
2448
2449 llvm::Triple::ArchType Arch = CGF.CGM.getTriple().getArch();
2450
2451 // FIXME: Do this on all targets and at -O0 too. This can be enabled only if
2452 // the target backend knows how to handle the operand bundle.
2453 if (CGF.CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2454 (Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_32 ||
2455 Arch == llvm::Triple::x86_64)) {
2456 llvm::Value *bundleArgs[] = {EP};
2457 llvm::OperandBundleDef OB("clang.arc.attachedcall", bundleArgs);
2458 auto *oldCall = cast<llvm::CallBase>(Val: value);
2459 llvm::CallBase *newCall = llvm::CallBase::addOperandBundle(
2460 CB: oldCall, ID: llvm::LLVMContext::OB_clang_arc_attachedcall, OB,
2461 InsertPt: oldCall->getIterator());
2462 newCall->copyMetadata(SrcInst: *oldCall);
2463 oldCall->replaceAllUsesWith(V: newCall);
2464 oldCall->eraseFromParent();
2465 CGF.EmitARCNoopIntrinsicUse(values: newCall);
2466 return newCall;
2467 }
2468
2469 bool isNoTail =
2470 CGF.CGM.getTargetCodeGenInfo().markARCOptimizedReturnCallsAsNoTail();
2471 llvm::CallInst::TailCallKind tailKind =
2472 isNoTail ? llvm::CallInst::TCK_NoTail : llvm::CallInst::TCK_None;
2473 return emitARCValueOperation(CGF, value, returnType: nullptr, fn&: EP, IntID: IID, tailKind);
2474}
2475
2476/// Retain the given object which is the result of a function call.
2477/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
2478///
2479/// Yes, this function name is one character away from a different
2480/// call with completely different semantics.
2481llvm::Value *
2482CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
2483 return emitOptimizedARCReturnCall(value, IsRetainRV: true, CGF&: *this);
2484}
2485
2486/// Claim a possibly-autoreleased return value at +0. This is only
2487/// valid to do in contexts which do not rely on the retain to keep
2488/// the object valid for all of its uses; for example, when
2489/// the value is ignored, or when it is being assigned to an
2490/// __unsafe_unretained variable.
2491///
2492/// call i8* \@objc_unsafeClaimAutoreleasedReturnValue(i8* %value)
2493llvm::Value *
2494CodeGenFunction::EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value) {
2495 return emitOptimizedARCReturnCall(value, IsRetainRV: false, CGF&: *this);
2496}
2497
2498/// Release the given object.
2499/// call void \@objc_release(i8* %value)
2500void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2501 ARCPreciseLifetime_t precise) {
2502 if (isa<llvm::ConstantPointerNull>(Val: value)) return;
2503
2504 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_release;
2505 if (!fn)
2506 fn = getARCIntrinsic(IntID: llvm::Intrinsic::objc_release, CGM);
2507
2508 // Cast the argument to 'id'.
2509 value = Builder.CreateBitCast(V: value, DestTy: Int8PtrTy);
2510
2511 // Call objc_release.
2512 llvm::CallInst *call = EmitNounwindRuntimeCall(callee: fn, args: value);
2513
2514 if (precise == ARCImpreciseLifetime) {
2515 call->setMetadata(Kind: "clang.imprecise_release",
2516 Node: llvm::MDNode::get(Context&: Builder.getContext(), MDs: {}));
2517 }
2518}
2519
2520/// Destroy a __strong variable.
2521///
2522/// At -O0, emit a call to store 'null' into the address;
2523/// instrumenting tools prefer this because the address is exposed,
2524/// but it's relatively cumbersome to optimize.
2525///
2526/// At -O1 and above, just load and call objc_release.
2527///
2528/// call void \@objc_storeStrong(i8** %addr, i8* null)
2529void CodeGenFunction::EmitARCDestroyStrong(Address addr,
2530 ARCPreciseLifetime_t precise) {
2531 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2532 llvm::Value *null = getNullForVariable(addr);
2533 EmitARCStoreStrongCall(addr, value: null, /*ignored*/ resultIgnored: true);
2534 return;
2535 }
2536
2537 llvm::Value *value = Builder.CreateLoad(Addr: addr);
2538 EmitARCRelease(value, precise);
2539}
2540
2541/// Store into a strong object. Always calls this:
2542/// call void \@objc_storeStrong(i8** %addr, i8* %value)
2543llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(Address addr,
2544 llvm::Value *value,
2545 bool ignored) {
2546 assert(addr.getElementType() == value->getType());
2547
2548 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_storeStrong;
2549 if (!fn)
2550 fn = getARCIntrinsic(IntID: llvm::Intrinsic::objc_storeStrong, CGM);
2551
2552 llvm::Value *args[] = {
2553 Builder.CreateBitCast(V: addr.emitRawPointer(CGF&: *this), DestTy: Int8PtrPtrTy),
2554 Builder.CreateBitCast(V: value, DestTy: Int8PtrTy)};
2555 EmitNounwindRuntimeCall(callee: fn, args);
2556
2557 if (ignored) return nullptr;
2558 return value;
2559}
2560
2561/// Store into a strong object. Sometimes calls this:
2562/// call void \@objc_storeStrong(i8** %addr, i8* %value)
2563/// Other times, breaks it down into components.
2564llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
2565 llvm::Value *newValue,
2566 bool ignored) {
2567 QualType type = dst.getType();
2568 bool isBlock = type->isBlockPointerType();
2569
2570 // Use a store barrier at -O0 unless this is a block type or the
2571 // lvalue is inadequately aligned.
2572 if (shouldUseFusedARCCalls() &&
2573 !isBlock &&
2574 (dst.getAlignment().isZero() ||
2575 dst.getAlignment() >= CharUnits::fromQuantity(Quantity: PointerAlignInBytes))) {
2576 return EmitARCStoreStrongCall(addr: dst.getAddress(), value: newValue, ignored);
2577 }
2578
2579 // Otherwise, split it out.
2580
2581 // Retain the new value.
2582 newValue = EmitARCRetain(type, value: newValue);
2583
2584 // Read the old value.
2585 llvm::Value *oldValue = EmitLoadOfScalar(lvalue: dst, Loc: SourceLocation());
2586
2587 // Store. We do this before the release so that any deallocs won't
2588 // see the old value.
2589 EmitStoreOfScalar(value: newValue, lvalue: dst);
2590
2591 // Finally, release the old value.
2592 EmitARCRelease(value: oldValue, precise: dst.isARCPreciseLifetime());
2593
2594 return newValue;
2595}
2596
2597/// Autorelease the given object.
2598/// call i8* \@objc_autorelease(i8* %value)
2599llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2600 return emitARCValueOperation(CGF&: *this, value, returnType: nullptr,
2601 fn&: CGM.getObjCEntrypoints().objc_autorelease,
2602 IntID: llvm::Intrinsic::objc_autorelease);
2603}
2604
2605/// Autorelease the given object.
2606/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
2607llvm::Value *
2608CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2609 return emitARCValueOperation(CGF&: *this, value, returnType: nullptr,
2610 fn&: CGM.getObjCEntrypoints().objc_autoreleaseReturnValue,
2611 IntID: llvm::Intrinsic::objc_autoreleaseReturnValue,
2612 tailKind: llvm::CallInst::TCK_Tail);
2613}
2614
2615/// Do a fused retain/autorelease of the given object.
2616/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
2617llvm::Value *
2618CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2619 return emitARCValueOperation(CGF&: *this, value, returnType: nullptr,
2620 fn&: CGM.getObjCEntrypoints().objc_retainAutoreleaseReturnValue,
2621 IntID: llvm::Intrinsic::objc_retainAutoreleaseReturnValue,
2622 tailKind: llvm::CallInst::TCK_Tail);
2623}
2624
2625/// Do a fused retain/autorelease of the given object.
2626/// call i8* \@objc_retainAutorelease(i8* %value)
2627/// or
2628/// %retain = call i8* \@objc_retainBlock(i8* %value)
2629/// call i8* \@objc_autorelease(i8* %retain)
2630llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2631 llvm::Value *value) {
2632 if (!type->isBlockPointerType())
2633 return EmitARCRetainAutoreleaseNonBlock(value);
2634
2635 if (isa<llvm::ConstantPointerNull>(Val: value)) return value;
2636
2637 llvm::Type *origType = value->getType();
2638 value = Builder.CreateBitCast(V: value, DestTy: Int8PtrTy);
2639 value = EmitARCRetainBlock(value, /*mandatory*/ true);
2640 value = EmitARCAutorelease(value);
2641 return Builder.CreateBitCast(V: value, DestTy: origType);
2642}
2643
2644/// Do a fused retain/autorelease of the given object.
2645/// call i8* \@objc_retainAutorelease(i8* %value)
2646llvm::Value *
2647CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2648 return emitARCValueOperation(CGF&: *this, value, returnType: nullptr,
2649 fn&: CGM.getObjCEntrypoints().objc_retainAutorelease,
2650 IntID: llvm::Intrinsic::objc_retainAutorelease);
2651}
2652
2653/// i8* \@objc_loadWeak(i8** %addr)
2654/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2655llvm::Value *CodeGenFunction::EmitARCLoadWeak(Address addr) {
2656 return emitARCLoadOperation(CGF&: *this, addr,
2657 fn&: CGM.getObjCEntrypoints().objc_loadWeak,
2658 IntID: llvm::Intrinsic::objc_loadWeak);
2659}
2660
2661/// i8* \@objc_loadWeakRetained(i8** %addr)
2662llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(Address addr) {
2663 return emitARCLoadOperation(CGF&: *this, addr,
2664 fn&: CGM.getObjCEntrypoints().objc_loadWeakRetained,
2665 IntID: llvm::Intrinsic::objc_loadWeakRetained);
2666}
2667
2668/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
2669/// Returns %value.
2670llvm::Value *CodeGenFunction::EmitARCStoreWeak(Address addr,
2671 llvm::Value *value,
2672 bool ignored) {
2673 return emitARCStoreOperation(CGF&: *this, addr, value,
2674 fn&: CGM.getObjCEntrypoints().objc_storeWeak,
2675 IntID: llvm::Intrinsic::objc_storeWeak, ignored);
2676}
2677
2678/// i8* \@objc_initWeak(i8** %addr, i8* %value)
2679/// Returns %value. %addr is known to not have a current weak entry.
2680/// Essentially equivalent to:
2681/// *addr = nil; objc_storeWeak(addr, value);
2682void CodeGenFunction::EmitARCInitWeak(Address addr, llvm::Value *value) {
2683 // If we're initializing to null, just write null to memory; no need
2684 // to get the runtime involved. But don't do this if optimization
2685 // is enabled, because accounting for this would make the optimizer
2686 // much more complicated.
2687 if (isa<llvm::ConstantPointerNull>(Val: value) &&
2688 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2689 Builder.CreateStore(Val: value, Addr: addr);
2690 return;
2691 }
2692
2693 emitARCStoreOperation(CGF&: *this, addr, value,
2694 fn&: CGM.getObjCEntrypoints().objc_initWeak,
2695 IntID: llvm::Intrinsic::objc_initWeak, /*ignored*/ true);
2696}
2697
2698/// void \@objc_destroyWeak(i8** %addr)
2699/// Essentially objc_storeWeak(addr, nil).
2700void CodeGenFunction::EmitARCDestroyWeak(Address addr) {
2701 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_destroyWeak;
2702 if (!fn)
2703 fn = getARCIntrinsic(IntID: llvm::Intrinsic::objc_destroyWeak, CGM);
2704
2705 EmitNounwindRuntimeCall(callee: fn, args: addr.emitRawPointer(CGF&: *this));
2706}
2707
2708/// void \@objc_moveWeak(i8** %dest, i8** %src)
2709/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2710/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2711void CodeGenFunction::EmitARCMoveWeak(Address dst, Address src) {
2712 emitARCCopyOperation(CGF&: *this, dst, src,
2713 fn&: CGM.getObjCEntrypoints().objc_moveWeak,
2714 IntID: llvm::Intrinsic::objc_moveWeak);
2715}
2716
2717/// void \@objc_copyWeak(i8** %dest, i8** %src)
2718/// Disregards the current value in %dest. Essentially
2719/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2720void CodeGenFunction::EmitARCCopyWeak(Address dst, Address src) {
2721 emitARCCopyOperation(CGF&: *this, dst, src,
2722 fn&: CGM.getObjCEntrypoints().objc_copyWeak,
2723 IntID: llvm::Intrinsic::objc_copyWeak);
2724}
2725
2726void CodeGenFunction::emitARCCopyAssignWeak(QualType Ty, Address DstAddr,
2727 Address SrcAddr) {
2728 llvm::Value *Object = EmitARCLoadWeakRetained(addr: SrcAddr);
2729 Object = EmitObjCConsumeObject(type: Ty, object: Object);
2730 EmitARCStoreWeak(addr: DstAddr, value: Object, ignored: false);
2731}
2732
2733void CodeGenFunction::emitARCMoveAssignWeak(QualType Ty, Address DstAddr,
2734 Address SrcAddr) {
2735 llvm::Value *Object = EmitARCLoadWeakRetained(addr: SrcAddr);
2736 Object = EmitObjCConsumeObject(type: Ty, object: Object);
2737 EmitARCStoreWeak(addr: DstAddr, value: Object, ignored: false);
2738 EmitARCDestroyWeak(addr: SrcAddr);
2739}
2740
2741/// Produce the code to do a objc_autoreleasepool_push.
2742/// call i8* \@objc_autoreleasePoolPush(void)
2743llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2744 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPush;
2745 if (!fn)
2746 fn = getARCIntrinsic(IntID: llvm::Intrinsic::objc_autoreleasePoolPush, CGM);
2747
2748 return EmitNounwindRuntimeCall(callee: fn);
2749}
2750
2751/// Produce the code to do a primitive release.
2752/// call void \@objc_autoreleasePoolPop(i8* %ptr)
2753void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2754 assert(value->getType() == Int8PtrTy);
2755
2756 if (getInvokeDest()) {
2757 // Call the runtime method not the intrinsic if we are handling exceptions
2758 llvm::FunctionCallee &fn =
2759 CGM.getObjCEntrypoints().objc_autoreleasePoolPopInvoke;
2760 if (!fn) {
2761 llvm::FunctionType *fnType =
2762 llvm::FunctionType::get(Result: Builder.getVoidTy(), Params: Int8PtrTy, isVarArg: false);
2763 fn = CGM.CreateRuntimeFunction(Ty: fnType, Name: "objc_autoreleasePoolPop");
2764 setARCRuntimeFunctionLinkage(CGM, RTF: fn);
2765 }
2766
2767 // objc_autoreleasePoolPop can throw.
2768 EmitRuntimeCallOrInvoke(callee: fn, args: value);
2769 } else {
2770 llvm::FunctionCallee &fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPop;
2771 if (!fn)
2772 fn = getARCIntrinsic(IntID: llvm::Intrinsic::objc_autoreleasePoolPop, CGM);
2773
2774 EmitRuntimeCall(callee: fn, args: value);
2775 }
2776}
2777
2778/// Produce the code to do an MRR version objc_autoreleasepool_push.
2779/// Which is: [[NSAutoreleasePool alloc] init];
2780/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2781/// init is declared as: - (id) init; in its NSObject super class.
2782///
2783llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2784 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2785 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(CGF&: *this);
2786 // [NSAutoreleasePool alloc]
2787 const IdentifierInfo *II = &CGM.getContext().Idents.get(Name: "alloc");
2788 Selector AllocSel = getContext().Selectors.getSelector(NumArgs: 0, IIV: &II);
2789 CallArgList Args;
2790 RValue AllocRV =
2791 Runtime.GenerateMessageSend(CGF&: *this, ReturnSlot: ReturnValueSlot(),
2792 ResultType: getContext().getObjCIdType(),
2793 Sel: AllocSel, Receiver, CallArgs: Args);
2794
2795 // [Receiver init]
2796 Receiver = AllocRV.getScalarVal();
2797 II = &CGM.getContext().Idents.get(Name: "init");
2798 Selector InitSel = getContext().Selectors.getSelector(NumArgs: 0, IIV: &II);
2799 RValue InitRV =
2800 Runtime.GenerateMessageSend(CGF&: *this, ReturnSlot: ReturnValueSlot(),
2801 ResultType: getContext().getObjCIdType(),
2802 Sel: InitSel, Receiver, CallArgs: Args);
2803 return InitRV.getScalarVal();
2804}
2805
2806/// Allocate the given objc object.
2807/// call i8* \@objc_alloc(i8* %value)
2808llvm::Value *CodeGenFunction::EmitObjCAlloc(llvm::Value *value,
2809 llvm::Type *resultType) {
2810 return emitObjCValueOperation(CGF&: *this, value, returnType: resultType,
2811 fn&: CGM.getObjCEntrypoints().objc_alloc,
2812 fnName: "objc_alloc");
2813}
2814
2815/// Allocate the given objc object.
2816/// call i8* \@objc_allocWithZone(i8* %value)
2817llvm::Value *CodeGenFunction::EmitObjCAllocWithZone(llvm::Value *value,
2818 llvm::Type *resultType) {
2819 return emitObjCValueOperation(CGF&: *this, value, returnType: resultType,
2820 fn&: CGM.getObjCEntrypoints().objc_allocWithZone,
2821 fnName: "objc_allocWithZone");
2822}
2823
2824llvm::Value *CodeGenFunction::EmitObjCAllocInit(llvm::Value *value,
2825 llvm::Type *resultType) {
2826 return emitObjCValueOperation(CGF&: *this, value, returnType: resultType,
2827 fn&: CGM.getObjCEntrypoints().objc_alloc_init,
2828 fnName: "objc_alloc_init");
2829}
2830
2831/// Produce the code to do a primitive release.
2832/// [tmp drain];
2833void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2834 const IdentifierInfo *II = &CGM.getContext().Idents.get(Name: "drain");
2835 Selector DrainSel = getContext().Selectors.getSelector(NumArgs: 0, IIV: &II);
2836 CallArgList Args;
2837 CGM.getObjCRuntime().GenerateMessageSend(CGF&: *this, ReturnSlot: ReturnValueSlot(),
2838 ResultType: getContext().VoidTy, Sel: DrainSel, Receiver: Arg, CallArgs: Args);
2839}
2840
2841void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2842 Address addr,
2843 QualType type) {
2844 CGF.EmitARCDestroyStrong(addr, precise: ARCPreciseLifetime);
2845}
2846
2847void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2848 Address addr,
2849 QualType type) {
2850 CGF.EmitARCDestroyStrong(addr, precise: ARCImpreciseLifetime);
2851}
2852
2853void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2854 Address addr,
2855 QualType type) {
2856 CGF.EmitARCDestroyWeak(addr);
2857}
2858
2859void CodeGenFunction::emitARCIntrinsicUse(CodeGenFunction &CGF, Address addr,
2860 QualType type) {
2861 llvm::Value *value = CGF.Builder.CreateLoad(Addr: addr);
2862 CGF.EmitARCIntrinsicUse(values: value);
2863}
2864
2865/// Autorelease the given object.
2866/// call i8* \@objc_autorelease(i8* %value)
2867llvm::Value *CodeGenFunction::EmitObjCAutorelease(llvm::Value *value,
2868 llvm::Type *returnType) {
2869 return emitObjCValueOperation(
2870 CGF&: *this, value, returnType,
2871 fn&: CGM.getObjCEntrypoints().objc_autoreleaseRuntimeFunction,
2872 fnName: "objc_autorelease");
2873}
2874
2875/// Retain the given object, with normal retain semantics.
2876/// call i8* \@objc_retain(i8* %value)
2877llvm::Value *CodeGenFunction::EmitObjCRetainNonBlock(llvm::Value *value,
2878 llvm::Type *returnType) {
2879 return emitObjCValueOperation(
2880 CGF&: *this, value, returnType,
2881 fn&: CGM.getObjCEntrypoints().objc_retainRuntimeFunction, fnName: "objc_retain");
2882}
2883
2884/// Release the given object.
2885/// call void \@objc_release(i8* %value)
2886void CodeGenFunction::EmitObjCRelease(llvm::Value *value,
2887 ARCPreciseLifetime_t precise) {
2888 if (isa<llvm::ConstantPointerNull>(Val: value)) return;
2889
2890 llvm::FunctionCallee &fn =
2891 CGM.getObjCEntrypoints().objc_releaseRuntimeFunction;
2892 if (!fn) {
2893 llvm::FunctionType *fnType =
2894 llvm::FunctionType::get(Result: Builder.getVoidTy(), Params: Int8PtrTy, isVarArg: false);
2895 fn = CGM.CreateRuntimeFunction(Ty: fnType, Name: "objc_release");
2896 setARCRuntimeFunctionLinkage(CGM, RTF: fn);
2897 // We have Native ARC, so set nonlazybind attribute for performance
2898 if (llvm::Function *f = dyn_cast<llvm::Function>(Val: fn.getCallee()))
2899 f->addFnAttr(Kind: llvm::Attribute::NonLazyBind);
2900 }
2901
2902 // Cast the argument to 'id'.
2903 value = Builder.CreateBitCast(V: value, DestTy: Int8PtrTy);
2904
2905 // Call objc_release.
2906 llvm::CallBase *call = EmitCallOrInvoke(Callee: fn, Args: value);
2907
2908 if (precise == ARCImpreciseLifetime) {
2909 call->setMetadata(Kind: "clang.imprecise_release",
2910 Node: llvm::MDNode::get(Context&: Builder.getContext(), MDs: {}));
2911 }
2912}
2913
2914namespace {
2915 struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
2916 llvm::Value *Token;
2917
2918 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2919
2920 void Emit(CodeGenFunction &CGF, Flags flags) override {
2921 CGF.EmitObjCAutoreleasePoolPop(value: Token);
2922 }
2923 };
2924 struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
2925 llvm::Value *Token;
2926
2927 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2928
2929 void Emit(CodeGenFunction &CGF, Flags flags) override {
2930 CGF.EmitObjCMRRAutoreleasePoolPop(Arg: Token);
2931 }
2932 };
2933}
2934
2935void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
2936 if (CGM.getLangOpts().ObjCAutoRefCount)
2937 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(Kind: NormalCleanup, A: Ptr);
2938 else
2939 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(Kind: NormalCleanup, A: Ptr);
2940}
2941
2942static bool shouldRetainObjCLifetime(Qualifiers::ObjCLifetime lifetime) {
2943 switch (lifetime) {
2944 case Qualifiers::OCL_None:
2945 case Qualifiers::OCL_ExplicitNone:
2946 case Qualifiers::OCL_Strong:
2947 case Qualifiers::OCL_Autoreleasing:
2948 return true;
2949
2950 case Qualifiers::OCL_Weak:
2951 return false;
2952 }
2953
2954 llvm_unreachable("impossible lifetime!");
2955}
2956
2957static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2958 LValue lvalue,
2959 QualType type) {
2960 llvm::Value *result;
2961 bool shouldRetain = shouldRetainObjCLifetime(lifetime: type.getObjCLifetime());
2962 if (shouldRetain) {
2963 result = CGF.EmitLoadOfLValue(V: lvalue, Loc: SourceLocation()).getScalarVal();
2964 } else {
2965 assert(type.getObjCLifetime() == Qualifiers::OCL_Weak);
2966 result = CGF.EmitARCLoadWeakRetained(addr: lvalue.getAddress());
2967 }
2968 return TryEmitResult(result, !shouldRetain);
2969}
2970
2971static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2972 const Expr *e) {
2973 e = e->IgnoreParens();
2974 QualType type = e->getType();
2975
2976 // If we're loading retained from a __strong xvalue, we can avoid
2977 // an extra retain/release pair by zeroing out the source of this
2978 // "move" operation.
2979 if (e->isXValue() &&
2980 !type.isConstQualified() &&
2981 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2982 // Emit the lvalue.
2983 LValue lv = CGF.EmitLValue(E: e);
2984
2985 // Load the object pointer.
2986 llvm::Value *result = CGF.EmitLoadOfLValue(V: lv,
2987 Loc: SourceLocation()).getScalarVal();
2988
2989 // Set the source pointer to NULL.
2990 CGF.EmitStoreOfScalar(value: getNullForVariable(addr: lv.getAddress()), lvalue: lv);
2991
2992 return TryEmitResult(result, true);
2993 }
2994
2995 // As a very special optimization, in ARC++, if the l-value is the
2996 // result of a non-volatile assignment, do a simple retain of the
2997 // result of the call to objc_storeWeak instead of reloading.
2998 if (CGF.getLangOpts().CPlusPlus &&
2999 !type.isVolatileQualified() &&
3000 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
3001 isa<BinaryOperator>(Val: e) &&
3002 cast<BinaryOperator>(Val: e)->getOpcode() == BO_Assign)
3003 return TryEmitResult(CGF.EmitScalarExpr(E: e), false);
3004
3005 // Try to emit code for scalar constant instead of emitting LValue and
3006 // loading it because we are not guaranteed to have an l-value. One of such
3007 // cases is DeclRefExpr referencing non-odr-used constant-evaluated variable.
3008 if (const auto *decl_expr = dyn_cast<DeclRefExpr>(Val: e)) {
3009 auto *DRE = const_cast<DeclRefExpr *>(decl_expr);
3010 if (CodeGenFunction::ConstantEmission constant = CGF.tryEmitAsConstant(RefExpr: DRE))
3011 return TryEmitResult(CGF.emitScalarConstant(Constant: constant, E: DRE),
3012 !shouldRetainObjCLifetime(lifetime: type.getObjCLifetime()));
3013 }
3014
3015 return tryEmitARCRetainLoadOfScalar(CGF, lvalue: CGF.EmitLValue(E: e), type);
3016}
3017
3018typedef llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
3019 llvm::Value *value)>
3020 ValueTransform;
3021
3022/// Insert code immediately after a call.
3023
3024// FIXME: We should find a way to emit the runtime call immediately
3025// after the call is emitted to eliminate the need for this function.
3026static llvm::Value *emitARCOperationAfterCall(CodeGenFunction &CGF,
3027 llvm::Value *value,
3028 ValueTransform doAfterCall,
3029 ValueTransform doFallback) {
3030 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
3031 auto *callBase = dyn_cast<llvm::CallBase>(Val: value);
3032
3033 if (callBase && llvm::objcarc::hasAttachedCallOpBundle(CB: callBase)) {
3034 // Fall back if the call base has operand bundle "clang.arc.attachedcall".
3035 value = doFallback(CGF, value);
3036 } else if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(Val: value)) {
3037 // Place the retain immediately following the call.
3038 CGF.Builder.SetInsertPoint(TheBB: call->getParent(),
3039 IP: ++llvm::BasicBlock::iterator(call));
3040 value = doAfterCall(CGF, value);
3041 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(Val: value)) {
3042 // Place the retain at the beginning of the normal destination block.
3043 llvm::BasicBlock *BB = invoke->getNormalDest();
3044 CGF.Builder.SetInsertPoint(TheBB: BB, IP: BB->begin());
3045 value = doAfterCall(CGF, value);
3046
3047 // Bitcasts can arise because of related-result returns. Rewrite
3048 // the operand.
3049 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(Val: value)) {
3050 // Change the insert point to avoid emitting the fall-back call after the
3051 // bitcast.
3052 CGF.Builder.SetInsertPoint(TheBB: bitcast->getParent(), IP: bitcast->getIterator());
3053 llvm::Value *operand = bitcast->getOperand(i_nocapture: 0);
3054 operand = emitARCOperationAfterCall(CGF, value: operand, doAfterCall, doFallback);
3055 bitcast->setOperand(i_nocapture: 0, Val_nocapture: operand);
3056 value = bitcast;
3057 } else {
3058 auto *phi = dyn_cast<llvm::PHINode>(Val: value);
3059 if (phi && phi->getNumIncomingValues() == 2 &&
3060 isa<llvm::ConstantPointerNull>(Val: phi->getIncomingValue(i: 1)) &&
3061 isa<llvm::CallBase>(Val: phi->getIncomingValue(i: 0))) {
3062 // Handle phi instructions that are generated when it's necessary to check
3063 // whether the receiver of a message is null.
3064 llvm::Value *inVal = phi->getIncomingValue(i: 0);
3065 inVal = emitARCOperationAfterCall(CGF, value: inVal, doAfterCall, doFallback);
3066 phi->setIncomingValue(i: 0, V: inVal);
3067 value = phi;
3068 } else {
3069 // Generic fall-back case.
3070 // Retain using the non-block variant: we never need to do a copy
3071 // of a block that's been returned to us.
3072 value = doFallback(CGF, value);
3073 }
3074 }
3075
3076 CGF.Builder.restoreIP(IP: ip);
3077 return value;
3078}
3079
3080/// Given that the given expression is some sort of call (which does
3081/// not return retained), emit a retain following it.
3082static llvm::Value *emitARCRetainCallResult(CodeGenFunction &CGF,
3083 const Expr *e) {
3084 llvm::Value *value = CGF.EmitScalarExpr(E: e);
3085 return emitARCOperationAfterCall(CGF, value,
3086 doAfterCall: [](CodeGenFunction &CGF, llvm::Value *value) {
3087 return CGF.EmitARCRetainAutoreleasedReturnValue(value);
3088 },
3089 doFallback: [](CodeGenFunction &CGF, llvm::Value *value) {
3090 return CGF.EmitARCRetainNonBlock(value);
3091 });
3092}
3093
3094/// Given that the given expression is some sort of call (which does
3095/// not return retained), perform an unsafeClaim following it.
3096static llvm::Value *emitARCUnsafeClaimCallResult(CodeGenFunction &CGF,
3097 const Expr *e) {
3098 llvm::Value *value = CGF.EmitScalarExpr(E: e);
3099 return emitARCOperationAfterCall(CGF, value,
3100 doAfterCall: [](CodeGenFunction &CGF, llvm::Value *value) {
3101 return CGF.EmitARCUnsafeClaimAutoreleasedReturnValue(value);
3102 },
3103 doFallback: [](CodeGenFunction &CGF, llvm::Value *value) {
3104 return value;
3105 });
3106}
3107
3108llvm::Value *CodeGenFunction::EmitARCReclaimReturnedObject(const Expr *E,
3109 bool allowUnsafeClaim) {
3110 if (allowUnsafeClaim &&
3111 CGM.getLangOpts().ObjCRuntime.hasARCUnsafeClaimAutoreleasedReturnValue()) {
3112 return emitARCUnsafeClaimCallResult(CGF&: *this, e: E);
3113 } else {
3114 llvm::Value *value = emitARCRetainCallResult(CGF&: *this, e: E);
3115 return EmitObjCConsumeObject(type: E->getType(), object: value);
3116 }
3117}
3118
3119/// Determine whether it might be important to emit a separate
3120/// objc_retain_block on the result of the given expression, or
3121/// whether it's okay to just emit it in a +1 context.
3122static bool shouldEmitSeparateBlockRetain(const Expr *e) {
3123 assert(e->getType()->isBlockPointerType());
3124 e = e->IgnoreParens();
3125
3126 // For future goodness, emit block expressions directly in +1
3127 // contexts if we can.
3128 if (isa<BlockExpr>(Val: e))
3129 return false;
3130
3131 if (const CastExpr *cast = dyn_cast<CastExpr>(Val: e)) {
3132 switch (cast->getCastKind()) {
3133 // Emitting these operations in +1 contexts is goodness.
3134 case CK_LValueToRValue:
3135 case CK_ARCReclaimReturnedObject:
3136 case CK_ARCConsumeObject:
3137 case CK_ARCProduceObject:
3138 return false;
3139
3140 // These operations preserve a block type.
3141 case CK_NoOp:
3142 case CK_BitCast:
3143 return shouldEmitSeparateBlockRetain(e: cast->getSubExpr());
3144
3145 // These operations are known to be bad (or haven't been considered).
3146 case CK_AnyPointerToBlockPointerCast:
3147 default:
3148 return true;
3149 }
3150 }
3151
3152 return true;
3153}
3154
3155namespace {
3156/// A CRTP base class for emitting expressions of retainable object
3157/// pointer type in ARC.
3158template <typename Impl, typename Result> class ARCExprEmitter {
3159protected:
3160 CodeGenFunction &CGF;
3161 Impl &asImpl() { return *static_cast<Impl*>(this); }
3162
3163 ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
3164
3165public:
3166 Result visit(const Expr *e);
3167 Result visitCastExpr(const CastExpr *e);
3168 Result visitPseudoObjectExpr(const PseudoObjectExpr *e);
3169 Result visitBlockExpr(const BlockExpr *e);
3170 Result visitBinaryOperator(const BinaryOperator *e);
3171 Result visitBinAssign(const BinaryOperator *e);
3172 Result visitBinAssignUnsafeUnretained(const BinaryOperator *e);
3173 Result visitBinAssignAutoreleasing(const BinaryOperator *e);
3174 Result visitBinAssignWeak(const BinaryOperator *e);
3175 Result visitBinAssignStrong(const BinaryOperator *e);
3176
3177 // Minimal implementation:
3178 // Result visitLValueToRValue(const Expr *e)
3179 // Result visitConsumeObject(const Expr *e)
3180 // Result visitExtendBlockObject(const Expr *e)
3181 // Result visitReclaimReturnedObject(const Expr *e)
3182 // Result visitCall(const Expr *e)
3183 // Result visitExpr(const Expr *e)
3184 //
3185 // Result emitBitCast(Result result, llvm::Type *resultType)
3186 // llvm::Value *getValueOfResult(Result result)
3187};
3188}
3189
3190/// Try to emit a PseudoObjectExpr under special ARC rules.
3191///
3192/// This massively duplicates emitPseudoObjectRValue.
3193template <typename Impl, typename Result>
3194Result
3195ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {
3196 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
3197
3198 // Find the result expression.
3199 const Expr *resultExpr = E->getResultExpr();
3200 assert(resultExpr);
3201 Result result;
3202
3203 for (PseudoObjectExpr::const_semantics_iterator
3204 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
3205 const Expr *semantic = *i;
3206
3207 // If this semantic expression is an opaque value, bind it
3208 // to the result of its source expression.
3209 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(Val: semantic)) {
3210 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
3211 OVMA opaqueData;
3212
3213 // If this semantic is the result of the pseudo-object
3214 // expression, try to evaluate the source as +1.
3215 if (ov == resultExpr) {
3216 assert(!OVMA::shouldBindAsLValue(ov));
3217 result = asImpl().visit(ov->getSourceExpr());
3218 opaqueData = OVMA::bind(CGF, ov,
3219 RValue::get(asImpl().getValueOfResult(result)));
3220
3221 // Otherwise, just bind it.
3222 } else {
3223 opaqueData = OVMA::bind(CGF, ov, e: ov->getSourceExpr());
3224 }
3225 opaques.push_back(Elt: opaqueData);
3226
3227 // Otherwise, if the expression is the result, evaluate it
3228 // and remember the result.
3229 } else if (semantic == resultExpr) {
3230 result = asImpl().visit(semantic);
3231
3232 // Otherwise, evaluate the expression in an ignored context.
3233 } else {
3234 CGF.EmitIgnoredExpr(E: semantic);
3235 }
3236 }
3237
3238 // Unbind all the opaques now.
3239 for (CodeGenFunction::OpaqueValueMappingData &opaque : opaques)
3240 opaque.unbind(CGF);
3241
3242 return result;
3243}
3244
3245template <typename Impl, typename Result>
3246Result ARCExprEmitter<Impl, Result>::visitBlockExpr(const BlockExpr *e) {
3247 // The default implementation just forwards the expression to visitExpr.
3248 return asImpl().visitExpr(e);
3249}
3250
3251template <typename Impl, typename Result>
3252Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
3253 switch (e->getCastKind()) {
3254
3255 // No-op casts don't change the type, so we just ignore them.
3256 case CK_NoOp:
3257 return asImpl().visit(e->getSubExpr());
3258
3259 // These casts can change the type.
3260 case CK_CPointerToObjCPointerCast:
3261 case CK_BlockPointerToObjCPointerCast:
3262 case CK_AnyPointerToBlockPointerCast:
3263 case CK_BitCast: {
3264 llvm::Type *resultType = CGF.ConvertType(T: e->getType());
3265 assert(e->getSubExpr()->getType()->hasPointerRepresentation());
3266 Result result = asImpl().visit(e->getSubExpr());
3267 return asImpl().emitBitCast(result, resultType);
3268 }
3269
3270 // Handle some casts specially.
3271 case CK_LValueToRValue:
3272 return asImpl().visitLValueToRValue(e->getSubExpr());
3273 case CK_ARCConsumeObject:
3274 return asImpl().visitConsumeObject(e->getSubExpr());
3275 case CK_ARCExtendBlockObject:
3276 return asImpl().visitExtendBlockObject(e->getSubExpr());
3277 case CK_ARCReclaimReturnedObject:
3278 return asImpl().visitReclaimReturnedObject(e->getSubExpr());
3279
3280 // Otherwise, use the default logic.
3281 default:
3282 return asImpl().visitExpr(e);
3283 }
3284}
3285
3286template <typename Impl, typename Result>
3287Result
3288ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
3289 switch (e->getOpcode()) {
3290 case BO_Comma:
3291 CGF.EmitIgnoredExpr(E: e->getLHS());
3292 CGF.EnsureInsertPoint();
3293 return asImpl().visit(e->getRHS());
3294
3295 case BO_Assign:
3296 return asImpl().visitBinAssign(e);
3297
3298 default:
3299 return asImpl().visitExpr(e);
3300 }
3301}
3302
3303template <typename Impl, typename Result>
3304Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
3305 switch (e->getLHS()->getType().getObjCLifetime()) {
3306 case Qualifiers::OCL_ExplicitNone:
3307 return asImpl().visitBinAssignUnsafeUnretained(e);
3308
3309 case Qualifiers::OCL_Weak:
3310 return asImpl().visitBinAssignWeak(e);
3311
3312 case Qualifiers::OCL_Autoreleasing:
3313 return asImpl().visitBinAssignAutoreleasing(e);
3314
3315 case Qualifiers::OCL_Strong:
3316 return asImpl().visitBinAssignStrong(e);
3317
3318 case Qualifiers::OCL_None:
3319 return asImpl().visitExpr(e);
3320 }
3321 llvm_unreachable("bad ObjC ownership qualifier");
3322}
3323
3324/// The default rule for __unsafe_unretained emits the RHS recursively,
3325/// stores into the unsafe variable, and propagates the result outward.
3326template <typename Impl, typename Result>
3327Result ARCExprEmitter<Impl,Result>::
3328 visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
3329 // Recursively emit the RHS.
3330 // For __block safety, do this before emitting the LHS.
3331 Result result = asImpl().visit(e->getRHS());
3332
3333 // Perform the store.
3334 LValue lvalue =
3335 CGF.EmitCheckedLValue(E: e->getLHS(), TCK: CodeGenFunction::TCK_Store);
3336 CGF.EmitStoreThroughLValue(Src: RValue::get(asImpl().getValueOfResult(result)),
3337 Dst: lvalue);
3338
3339 return result;
3340}
3341
3342template <typename Impl, typename Result>
3343Result
3344ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {
3345 return asImpl().visitExpr(e);
3346}
3347
3348template <typename Impl, typename Result>
3349Result
3350ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {
3351 return asImpl().visitExpr(e);
3352}
3353
3354template <typename Impl, typename Result>
3355Result
3356ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
3357 return asImpl().visitExpr(e);
3358}
3359
3360/// The general expression-emission logic.
3361template <typename Impl, typename Result>
3362Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
3363 // We should *never* see a nested full-expression here, because if
3364 // we fail to emit at +1, our caller must not retain after we close
3365 // out the full-expression. This isn't as important in the unsafe
3366 // emitter.
3367 assert(!isa<ExprWithCleanups>(e));
3368
3369 // Look through parens, __extension__, generic selection, etc.
3370 e = e->IgnoreParens();
3371
3372 // Handle certain kinds of casts.
3373 if (const CastExpr *ce = dyn_cast<CastExpr>(Val: e)) {
3374 return asImpl().visitCastExpr(ce);
3375
3376 // Handle the comma operator.
3377 } else if (auto op = dyn_cast<BinaryOperator>(Val: e)) {
3378 return asImpl().visitBinaryOperator(op);
3379
3380 // TODO: handle conditional operators here
3381
3382 // For calls and message sends, use the retained-call logic.
3383 // Delegate inits are a special case in that they're the only
3384 // returns-retained expression that *isn't* surrounded by
3385 // a consume.
3386 } else if (isa<CallExpr>(Val: e) ||
3387 (isa<ObjCMessageExpr>(Val: e) &&
3388 !cast<ObjCMessageExpr>(Val: e)->isDelegateInitCall())) {
3389 return asImpl().visitCall(e);
3390
3391 // Look through pseudo-object expressions.
3392 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(Val: e)) {
3393 return asImpl().visitPseudoObjectExpr(pseudo);
3394 } else if (auto *be = dyn_cast<BlockExpr>(Val: e))
3395 return asImpl().visitBlockExpr(be);
3396
3397 return asImpl().visitExpr(e);
3398}
3399
3400namespace {
3401
3402/// An emitter for +1 results.
3403struct ARCRetainExprEmitter :
3404 public ARCExprEmitter<ARCRetainExprEmitter, TryEmitResult> {
3405
3406 ARCRetainExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3407
3408 llvm::Value *getValueOfResult(TryEmitResult result) {
3409 return result.getPointer();
3410 }
3411
3412 TryEmitResult emitBitCast(TryEmitResult result, llvm::Type *resultType) {
3413 llvm::Value *value = result.getPointer();
3414 value = CGF.Builder.CreateBitCast(V: value, DestTy: resultType);
3415 result.setPointer(value);
3416 return result;
3417 }
3418
3419 TryEmitResult visitLValueToRValue(const Expr *e) {
3420 return tryEmitARCRetainLoadOfScalar(CGF, e);
3421 }
3422
3423 /// For consumptions, just emit the subexpression and thus elide
3424 /// the retain/release pair.
3425 TryEmitResult visitConsumeObject(const Expr *e) {
3426 llvm::Value *result = CGF.EmitScalarExpr(E: e);
3427 return TryEmitResult(result, true);
3428 }
3429
3430 TryEmitResult visitBlockExpr(const BlockExpr *e) {
3431 TryEmitResult result = visitExpr(e);
3432 // Avoid the block-retain if this is a block literal that doesn't need to be
3433 // copied to the heap.
3434 if (CGF.CGM.getCodeGenOpts().ObjCAvoidHeapifyLocalBlocks &&
3435 e->getBlockDecl()->canAvoidCopyToHeap())
3436 result.setInt(true);
3437 return result;
3438 }
3439
3440 /// Block extends are net +0. Naively, we could just recurse on
3441 /// the subexpression, but actually we need to ensure that the
3442 /// value is copied as a block, so there's a little filter here.
3443 TryEmitResult visitExtendBlockObject(const Expr *e) {
3444 llvm::Value *result; // will be a +0 value
3445
3446 // If we can't safely assume the sub-expression will produce a
3447 // block-copied value, emit the sub-expression at +0.
3448 if (shouldEmitSeparateBlockRetain(e)) {
3449 result = CGF.EmitScalarExpr(E: e);
3450
3451 // Otherwise, try to emit the sub-expression at +1 recursively.
3452 } else {
3453 TryEmitResult subresult = asImpl().visit(e);
3454
3455 // If that produced a retained value, just use that.
3456 if (subresult.getInt()) {
3457 return subresult;
3458 }
3459
3460 // Otherwise it's +0.
3461 result = subresult.getPointer();
3462 }
3463
3464 // Retain the object as a block.
3465 result = CGF.EmitARCRetainBlock(value: result, /*mandatory*/ true);
3466 return TryEmitResult(result, true);
3467 }
3468
3469 /// For reclaims, emit the subexpression as a retained call and
3470 /// skip the consumption.
3471 TryEmitResult visitReclaimReturnedObject(const Expr *e) {
3472 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3473 return TryEmitResult(result, true);
3474 }
3475
3476 /// When we have an undecorated call, retroactively do a claim.
3477 TryEmitResult visitCall(const Expr *e) {
3478 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3479 return TryEmitResult(result, true);
3480 }
3481
3482 // TODO: maybe special-case visitBinAssignWeak?
3483
3484 TryEmitResult visitExpr(const Expr *e) {
3485 // We didn't find an obvious production, so emit what we've got and
3486 // tell the caller that we didn't manage to retain.
3487 llvm::Value *result = CGF.EmitScalarExpr(E: e);
3488 return TryEmitResult(result, false);
3489 }
3490};
3491}
3492
3493static TryEmitResult
3494tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
3495 return ARCRetainExprEmitter(CGF).visit(e);
3496}
3497
3498static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
3499 LValue lvalue,
3500 QualType type) {
3501 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
3502 llvm::Value *value = result.getPointer();
3503 if (!result.getInt())
3504 value = CGF.EmitARCRetain(type, value);
3505 return value;
3506}
3507
3508/// EmitARCRetainScalarExpr - Semantically equivalent to
3509/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
3510/// best-effort attempt to peephole expressions that naturally produce
3511/// retained objects.
3512llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
3513 // The retain needs to happen within the full-expression.
3514 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Val: e)) {
3515 RunCleanupsScope scope(*this);
3516 return EmitARCRetainScalarExpr(e: cleanups->getSubExpr());
3517 }
3518
3519 TryEmitResult result = tryEmitARCRetainScalarExpr(CGF&: *this, e);
3520 llvm::Value *value = result.getPointer();
3521 if (!result.getInt())
3522 value = EmitARCRetain(type: e->getType(), value);
3523 return value;
3524}
3525
3526llvm::Value *
3527CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
3528 // The retain needs to happen within the full-expression.
3529 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Val: e)) {
3530 RunCleanupsScope scope(*this);
3531 return EmitARCRetainAutoreleaseScalarExpr(e: cleanups->getSubExpr());
3532 }
3533
3534 TryEmitResult result = tryEmitARCRetainScalarExpr(CGF&: *this, e);
3535 llvm::Value *value = result.getPointer();
3536 if (result.getInt())
3537 value = EmitARCAutorelease(value);
3538 else
3539 value = EmitARCRetainAutorelease(type: e->getType(), value);
3540 return value;
3541}
3542
3543llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
3544 llvm::Value *result;
3545 bool doRetain;
3546
3547 if (shouldEmitSeparateBlockRetain(e)) {
3548 result = EmitScalarExpr(E: e);
3549 doRetain = true;
3550 } else {
3551 TryEmitResult subresult = tryEmitARCRetainScalarExpr(CGF&: *this, e);
3552 result = subresult.getPointer();
3553 doRetain = !subresult.getInt();
3554 }
3555
3556 if (doRetain)
3557 result = EmitARCRetainBlock(value: result, /*mandatory*/ true);
3558 return EmitObjCConsumeObject(type: e->getType(), object: result);
3559}
3560
3561llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
3562 // In ARC, retain and autorelease the expression.
3563 if (getLangOpts().ObjCAutoRefCount) {
3564 // Do so before running any cleanups for the full-expression.
3565 // EmitARCRetainAutoreleaseScalarExpr does this for us.
3566 return EmitARCRetainAutoreleaseScalarExpr(e: expr);
3567 }
3568
3569 // Otherwise, use the normal scalar-expression emission. The
3570 // exception machinery doesn't do anything special with the
3571 // exception like retaining it, so there's no safety associated with
3572 // only running cleanups after the throw has started, and when it
3573 // matters it tends to be substantially inferior code.
3574 return EmitScalarExpr(E: expr);
3575}
3576
3577namespace {
3578
3579/// An emitter for assigning into an __unsafe_unretained context.
3580struct ARCUnsafeUnretainedExprEmitter :
3581 public ARCExprEmitter<ARCUnsafeUnretainedExprEmitter, llvm::Value*> {
3582
3583 ARCUnsafeUnretainedExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3584
3585 llvm::Value *getValueOfResult(llvm::Value *value) {
3586 return value;
3587 }
3588
3589 llvm::Value *emitBitCast(llvm::Value *value, llvm::Type *resultType) {
3590 return CGF.Builder.CreateBitCast(V: value, DestTy: resultType);
3591 }
3592
3593 llvm::Value *visitLValueToRValue(const Expr *e) {
3594 return CGF.EmitScalarExpr(E: e);
3595 }
3596
3597 /// For consumptions, just emit the subexpression and perform the
3598 /// consumption like normal.
3599 llvm::Value *visitConsumeObject(const Expr *e) {
3600 llvm::Value *value = CGF.EmitScalarExpr(E: e);
3601 return CGF.EmitObjCConsumeObject(type: e->getType(), object: value);
3602 }
3603
3604 /// No special logic for block extensions. (This probably can't
3605 /// actually happen in this emitter, though.)
3606 llvm::Value *visitExtendBlockObject(const Expr *e) {
3607 return CGF.EmitARCExtendBlockObject(e);
3608 }
3609
3610 /// For reclaims, perform an unsafeClaim if that's enabled.
3611 llvm::Value *visitReclaimReturnedObject(const Expr *e) {
3612 return CGF.EmitARCReclaimReturnedObject(E: e, /*unsafe*/ allowUnsafeClaim: true);
3613 }
3614
3615 /// When we have an undecorated call, just emit it without adding
3616 /// the unsafeClaim.
3617 llvm::Value *visitCall(const Expr *e) {
3618 return CGF.EmitScalarExpr(E: e);
3619 }
3620
3621 /// Just do normal scalar emission in the default case.
3622 llvm::Value *visitExpr(const Expr *e) {
3623 return CGF.EmitScalarExpr(E: e);
3624 }
3625};
3626}
3627
3628static llvm::Value *emitARCUnsafeUnretainedScalarExpr(CodeGenFunction &CGF,
3629 const Expr *e) {
3630 return ARCUnsafeUnretainedExprEmitter(CGF).visit(e);
3631}
3632
3633/// EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to
3634/// immediately releasing the resut of EmitARCRetainScalarExpr, but
3635/// avoiding any spurious retains, including by performing reclaims
3636/// with objc_unsafeClaimAutoreleasedReturnValue.
3637llvm::Value *CodeGenFunction::EmitARCUnsafeUnretainedScalarExpr(const Expr *e) {
3638 // Look through full-expressions.
3639 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Val: e)) {
3640 RunCleanupsScope scope(*this);
3641 return emitARCUnsafeUnretainedScalarExpr(CGF&: *this, e: cleanups->getSubExpr());
3642 }
3643
3644 return emitARCUnsafeUnretainedScalarExpr(CGF&: *this, e);
3645}
3646
3647std::pair<LValue,llvm::Value*>
3648CodeGenFunction::EmitARCStoreUnsafeUnretained(const BinaryOperator *e,
3649 bool ignored) {
3650 // Evaluate the RHS first. If we're ignoring the result, assume
3651 // that we can emit at an unsafe +0.
3652 llvm::Value *value;
3653 if (ignored) {
3654 value = EmitARCUnsafeUnretainedScalarExpr(e: e->getRHS());
3655 } else {
3656 value = EmitScalarExpr(E: e->getRHS());
3657 }
3658
3659 // Emit the LHS and perform the store.
3660 LValue lvalue = EmitLValue(E: e->getLHS());
3661 EmitStoreOfScalar(value, lvalue);
3662
3663 return std::pair<LValue,llvm::Value*>(std::move(lvalue), value);
3664}
3665
3666std::pair<LValue,llvm::Value*>
3667CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
3668 bool ignored) {
3669 // Evaluate the RHS first.
3670 TryEmitResult result = tryEmitARCRetainScalarExpr(CGF&: *this, e: e->getRHS());
3671 llvm::Value *value = result.getPointer();
3672
3673 bool hasImmediateRetain = result.getInt();
3674
3675 // If we didn't emit a retained object, and the l-value is of block
3676 // type, then we need to emit the block-retain immediately in case
3677 // it invalidates the l-value.
3678 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
3679 value = EmitARCRetainBlock(value, /*mandatory*/ false);
3680 hasImmediateRetain = true;
3681 }
3682
3683 LValue lvalue = EmitLValue(E: e->getLHS());
3684
3685 // If the RHS was emitted retained, expand this.
3686 if (hasImmediateRetain) {
3687 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, Loc: SourceLocation());
3688 EmitStoreOfScalar(value, lvalue);
3689 EmitARCRelease(value: oldValue, precise: lvalue.isARCPreciseLifetime());
3690 } else {
3691 value = EmitARCStoreStrong(dst: lvalue, newValue: value, ignored);
3692 }
3693
3694 return std::pair<LValue,llvm::Value*>(lvalue, value);
3695}
3696
3697std::pair<LValue,llvm::Value*>
3698CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
3699 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e: e->getRHS());
3700 LValue lvalue = EmitLValue(E: e->getLHS());
3701
3702 EmitStoreOfScalar(value, lvalue);
3703
3704 return std::pair<LValue,llvm::Value*>(lvalue, value);
3705}
3706
3707void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
3708 const ObjCAutoreleasePoolStmt &ARPS) {
3709 const Stmt *subStmt = ARPS.getSubStmt();
3710 const CompoundStmt &S = cast<CompoundStmt>(Val: *subStmt);
3711
3712 CGDebugInfo *DI = getDebugInfo();
3713 if (DI)
3714 DI->EmitLexicalBlockStart(Builder, Loc: S.getLBracLoc());
3715
3716 // Keep track of the current cleanup stack depth.
3717 RunCleanupsScope Scope(*this);
3718 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
3719 llvm::Value *token = EmitObjCAutoreleasePoolPush();
3720 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(Kind: NormalCleanup, A: token);
3721 } else {
3722 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
3723 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(Kind: NormalCleanup, A: token);
3724 }
3725
3726 for (const auto *I : S.body())
3727 EmitStmt(S: I);
3728
3729 if (DI)
3730 DI->EmitLexicalBlockEnd(Builder, Loc: S.getRBracLoc());
3731}
3732
3733/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3734/// make sure it survives garbage collection until this point.
3735void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
3736 // We just use an inline assembly.
3737 llvm::FunctionType *extenderType
3738 = llvm::FunctionType::get(Result: VoidTy, Params: VoidPtrTy, isVarArg: RequiredArgs::All);
3739 llvm::InlineAsm *extender = llvm::InlineAsm::get(Ty: extenderType,
3740 /* assembly */ AsmString: "",
3741 /* constraints */ Constraints: "r",
3742 /* side effects */ hasSideEffects: true);
3743
3744 EmitNounwindRuntimeCall(callee: extender, args: object);
3745}
3746
3747/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
3748/// non-trivial copy assignment function, produce following helper function.
3749/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
3750///
3751llvm::Constant *
3752CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
3753 const ObjCPropertyImplDecl *PID) {
3754 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3755 if ((!(PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_atomic)))
3756 return nullptr;
3757
3758 QualType Ty = PID->getPropertyIvarDecl()->getType();
3759 ASTContext &C = getContext();
3760
3761 if (Ty.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct) {
3762 // Call the move assignment operator instead of calling the copy assignment
3763 // operator and destructor.
3764 CharUnits Alignment = C.getTypeAlignInChars(T: Ty);
3765 llvm::Constant *Fn = getNonTrivialCStructMoveAssignmentOperator(
3766 CGM, DstAlignment: Alignment, SrcAlignment: Alignment, IsVolatile: Ty.isVolatileQualified(), QT: Ty);
3767 return Fn;
3768 }
3769
3770 if (!getLangOpts().CPlusPlus ||
3771 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
3772 return nullptr;
3773 if (!Ty->isRecordType())
3774 return nullptr;
3775 llvm::Constant *HelperFn = nullptr;
3776 if (hasTrivialSetExpr(PID))
3777 return nullptr;
3778 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
3779 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
3780 return HelperFn;
3781
3782 const IdentifierInfo *II =
3783 &CGM.getContext().Idents.get(Name: "__assign_helper_atomic_property_");
3784
3785 QualType ReturnTy = C.VoidTy;
3786 QualType DestTy = C.getPointerType(T: Ty);
3787 QualType SrcTy = Ty;
3788 SrcTy.addConst();
3789 SrcTy = C.getPointerType(T: SrcTy);
3790
3791 SmallVector<QualType, 2> ArgTys;
3792 ArgTys.push_back(Elt: DestTy);
3793 ArgTys.push_back(Elt: SrcTy);
3794 QualType FunctionTy = C.getFunctionType(ResultTy: ReturnTy, Args: ArgTys, EPI: {});
3795
3796 FunctionDecl *FD = FunctionDecl::Create(
3797 C, DC: C.getTranslationUnitDecl(), StartLoc: SourceLocation(), NLoc: SourceLocation(), N: II,
3798 T: FunctionTy, TInfo: nullptr, SC: SC_Static, UsesFPIntrin: false, isInlineSpecified: false, hasWrittenPrototype: false);
3799
3800 FunctionArgList args;
3801 ParmVarDecl *Params[2];
3802 ParmVarDecl *DstDecl = ParmVarDecl::Create(
3803 C, DC: FD, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr, T: DestTy,
3804 TInfo: C.getTrivialTypeSourceInfo(T: DestTy, Loc: SourceLocation()), S: SC_None,
3805 /*DefArg=*/nullptr);
3806 args.push_back(Elt: Params[0] = DstDecl);
3807 ParmVarDecl *SrcDecl = ParmVarDecl::Create(
3808 C, DC: FD, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr, T: SrcTy,
3809 TInfo: C.getTrivialTypeSourceInfo(T: SrcTy, Loc: SourceLocation()), S: SC_None,
3810 /*DefArg=*/nullptr);
3811 args.push_back(Elt: Params[1] = SrcDecl);
3812 FD->setParams(Params);
3813
3814 const CGFunctionInfo &FI =
3815 CGM.getTypes().arrangeBuiltinFunctionDeclaration(resultType: ReturnTy, args);
3816
3817 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(Info: FI);
3818
3819 llvm::Function *Fn =
3820 llvm::Function::Create(Ty: LTy, Linkage: llvm::GlobalValue::InternalLinkage,
3821 N: "__assign_helper_atomic_property_",
3822 M: &CGM.getModule());
3823
3824 CGM.SetInternalFunctionAttributes(GD: GlobalDecl(), F: Fn, FI);
3825
3826 StartFunction(GD: FD, RetTy: ReturnTy, Fn, FnInfo: FI, Args: args);
3827
3828 DeclRefExpr DstExpr(C, DstDecl, false, DestTy, VK_PRValue, SourceLocation());
3829 UnaryOperator *DST = UnaryOperator::Create(
3830 C, input: &DstExpr, opc: UO_Deref, type: DestTy->getPointeeType(), VK: VK_LValue, OK: OK_Ordinary,
3831 l: SourceLocation(), CanOverflow: false, FPFeatures: FPOptionsOverride());
3832
3833 DeclRefExpr SrcExpr(C, SrcDecl, false, SrcTy, VK_PRValue, SourceLocation());
3834 UnaryOperator *SRC = UnaryOperator::Create(
3835 C, input: &SrcExpr, opc: UO_Deref, type: SrcTy->getPointeeType(), VK: VK_LValue, OK: OK_Ordinary,
3836 l: SourceLocation(), CanOverflow: false, FPFeatures: FPOptionsOverride());
3837
3838 Expr *Args[2] = {DST, SRC};
3839 CallExpr *CalleeExp = cast<CallExpr>(Val: PID->getSetterCXXAssignment());
3840 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
3841 Ctx: C, OpKind: OO_Equal, Fn: CalleeExp->getCallee(), Args, Ty: DestTy->getPointeeType(),
3842 VK: VK_LValue, OperatorLoc: SourceLocation(), FPFeatures: FPOptionsOverride());
3843
3844 EmitStmt(S: TheCall);
3845
3846 FinishFunction();
3847 HelperFn = Fn;
3848 CGM.setAtomicSetterHelperFnMap(Ty, Fn: HelperFn);
3849 return HelperFn;
3850}
3851
3852llvm::Constant *CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
3853 const ObjCPropertyImplDecl *PID) {
3854 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3855 if ((!(PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_atomic)))
3856 return nullptr;
3857
3858 QualType Ty = PD->getType();
3859 ASTContext &C = getContext();
3860
3861 if (Ty.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct) {
3862 CharUnits Alignment = C.getTypeAlignInChars(T: Ty);
3863 llvm::Constant *Fn = getNonTrivialCStructCopyConstructor(
3864 CGM, DstAlignment: Alignment, SrcAlignment: Alignment, IsVolatile: Ty.isVolatileQualified(), QT: Ty);
3865 return Fn;
3866 }
3867
3868 if (!getLangOpts().CPlusPlus ||
3869 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
3870 return nullptr;
3871 if (!Ty->isRecordType())
3872 return nullptr;
3873 llvm::Constant *HelperFn = nullptr;
3874 if (hasTrivialGetExpr(propImpl: PID))
3875 return nullptr;
3876 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
3877 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
3878 return HelperFn;
3879
3880 const IdentifierInfo *II =
3881 &CGM.getContext().Idents.get(Name: "__copy_helper_atomic_property_");
3882
3883 QualType ReturnTy = C.VoidTy;
3884 QualType DestTy = C.getPointerType(T: Ty);
3885 QualType SrcTy = Ty;
3886 SrcTy.addConst();
3887 SrcTy = C.getPointerType(T: SrcTy);
3888
3889 SmallVector<QualType, 2> ArgTys;
3890 ArgTys.push_back(Elt: DestTy);
3891 ArgTys.push_back(Elt: SrcTy);
3892 QualType FunctionTy = C.getFunctionType(ResultTy: ReturnTy, Args: ArgTys, EPI: {});
3893
3894 FunctionDecl *FD = FunctionDecl::Create(
3895 C, DC: C.getTranslationUnitDecl(), StartLoc: SourceLocation(), NLoc: SourceLocation(), N: II,
3896 T: FunctionTy, TInfo: nullptr, SC: SC_Static, UsesFPIntrin: false, isInlineSpecified: false, hasWrittenPrototype: false);
3897
3898 FunctionArgList args;
3899 ParmVarDecl *Params[2];
3900 ParmVarDecl *DstDecl = ParmVarDecl::Create(
3901 C, DC: FD, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr, T: DestTy,
3902 TInfo: C.getTrivialTypeSourceInfo(T: DestTy, Loc: SourceLocation()), S: SC_None,
3903 /*DefArg=*/nullptr);
3904 args.push_back(Elt: Params[0] = DstDecl);
3905 ParmVarDecl *SrcDecl = ParmVarDecl::Create(
3906 C, DC: FD, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr, T: SrcTy,
3907 TInfo: C.getTrivialTypeSourceInfo(T: SrcTy, Loc: SourceLocation()), S: SC_None,
3908 /*DefArg=*/nullptr);
3909 args.push_back(Elt: Params[1] = SrcDecl);
3910 FD->setParams(Params);
3911
3912 const CGFunctionInfo &FI =
3913 CGM.getTypes().arrangeBuiltinFunctionDeclaration(resultType: ReturnTy, args);
3914
3915 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(Info: FI);
3916
3917 llvm::Function *Fn = llvm::Function::Create(
3918 Ty: LTy, Linkage: llvm::GlobalValue::InternalLinkage, N: "__copy_helper_atomic_property_",
3919 M: &CGM.getModule());
3920
3921 CGM.SetInternalFunctionAttributes(GD: GlobalDecl(), F: Fn, FI);
3922
3923 StartFunction(GD: FD, RetTy: ReturnTy, Fn, FnInfo: FI, Args: args);
3924
3925 DeclRefExpr SrcExpr(getContext(), SrcDecl, false, SrcTy, VK_PRValue,
3926 SourceLocation());
3927
3928 UnaryOperator *SRC = UnaryOperator::Create(
3929 C, input: &SrcExpr, opc: UO_Deref, type: SrcTy->getPointeeType(), VK: VK_LValue, OK: OK_Ordinary,
3930 l: SourceLocation(), CanOverflow: false, FPFeatures: FPOptionsOverride());
3931
3932 CXXConstructExpr *CXXConstExpr =
3933 cast<CXXConstructExpr>(Val: PID->getGetterCXXConstructor());
3934
3935 SmallVector<Expr*, 4> ConstructorArgs;
3936 ConstructorArgs.push_back(Elt: SRC);
3937 ConstructorArgs.append(in_start: std::next(x: CXXConstExpr->arg_begin()),
3938 in_end: CXXConstExpr->arg_end());
3939
3940 CXXConstructExpr *TheCXXConstructExpr =
3941 CXXConstructExpr::Create(Ctx: C, Ty, Loc: SourceLocation(),
3942 Ctor: CXXConstExpr->getConstructor(),
3943 Elidable: CXXConstExpr->isElidable(),
3944 Args: ConstructorArgs,
3945 HadMultipleCandidates: CXXConstExpr->hadMultipleCandidates(),
3946 ListInitialization: CXXConstExpr->isListInitialization(),
3947 StdInitListInitialization: CXXConstExpr->isStdInitListInitialization(),
3948 ZeroInitialization: CXXConstExpr->requiresZeroInitialization(),
3949 ConstructKind: CXXConstExpr->getConstructionKind(),
3950 ParenOrBraceRange: SourceRange());
3951
3952 DeclRefExpr DstExpr(getContext(), DstDecl, false, DestTy, VK_PRValue,
3953 SourceLocation());
3954
3955 RValue DV = EmitAnyExpr(E: &DstExpr);
3956 CharUnits Alignment =
3957 getContext().getTypeAlignInChars(T: TheCXXConstructExpr->getType());
3958 EmitAggExpr(E: TheCXXConstructExpr,
3959 AS: AggValueSlot::forAddr(
3960 addr: Address(DV.getScalarVal(), ConvertTypeForMem(T: Ty), Alignment),
3961 quals: Qualifiers(), isDestructed: AggValueSlot::IsDestructed,
3962 needsGC: AggValueSlot::DoesNotNeedGCBarriers,
3963 isAliased: AggValueSlot::IsNotAliased, mayOverlap: AggValueSlot::DoesNotOverlap));
3964
3965 FinishFunction();
3966 HelperFn = Fn;
3967 CGM.setAtomicGetterHelperFnMap(Ty, Fn: HelperFn);
3968 return HelperFn;
3969}
3970
3971llvm::Value *
3972CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3973 // Get selectors for retain/autorelease.
3974 const IdentifierInfo *CopyID = &getContext().Idents.get(Name: "copy");
3975 Selector CopySelector =
3976 getContext().Selectors.getNullarySelector(ID: CopyID);
3977 const IdentifierInfo *AutoreleaseID = &getContext().Idents.get(Name: "autorelease");
3978 Selector AutoreleaseSelector =
3979 getContext().Selectors.getNullarySelector(ID: AutoreleaseID);
3980
3981 // Emit calls to retain/autorelease.
3982 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3983 llvm::Value *Val = Block;
3984 RValue Result;
3985 Result = Runtime.GenerateMessageSend(CGF&: *this, ReturnSlot: ReturnValueSlot(),
3986 ResultType: Ty, Sel: CopySelector,
3987 Receiver: Val, CallArgs: CallArgList(), Class: nullptr, Method: nullptr);
3988 Val = Result.getScalarVal();
3989 Result = Runtime.GenerateMessageSend(CGF&: *this, ReturnSlot: ReturnValueSlot(),
3990 ResultType: Ty, Sel: AutoreleaseSelector,
3991 Receiver: Val, CallArgs: CallArgList(), Class: nullptr, Method: nullptr);
3992 Val = Result.getScalarVal();
3993 return Val;
3994}
3995
3996static unsigned getBaseMachOPlatformID(const llvm::Triple &TT) {
3997 switch (TT.getOS()) {
3998 case llvm::Triple::Darwin:
3999 case llvm::Triple::MacOSX:
4000 return llvm::MachO::PLATFORM_MACOS;
4001 case llvm::Triple::IOS:
4002 return llvm::MachO::PLATFORM_IOS;
4003 case llvm::Triple::TvOS:
4004 return llvm::MachO::PLATFORM_TVOS;
4005 case llvm::Triple::WatchOS:
4006 return llvm::MachO::PLATFORM_WATCHOS;
4007 case llvm::Triple::XROS:
4008 return llvm::MachO::PLATFORM_XROS;
4009 case llvm::Triple::DriverKit:
4010 return llvm::MachO::PLATFORM_DRIVERKIT;
4011 default:
4012 return llvm::MachO::PLATFORM_UNKNOWN;
4013 }
4014}
4015
4016static llvm::Value *emitIsPlatformVersionAtLeast(CodeGenFunction &CGF,
4017 const VersionTuple &Version) {
4018 CodeGenModule &CGM = CGF.CGM;
4019 // Note: we intend to support multi-platform version checks, so reserve
4020 // the room for a dual platform checking invocation that will be
4021 // implemented in the future.
4022 llvm::SmallVector<llvm::Value *, 8> Args;
4023
4024 auto EmitArgs = [&](const VersionTuple &Version, const llvm::Triple &TT) {
4025 std::optional<unsigned> Min = Version.getMinor(),
4026 SMin = Version.getSubminor();
4027 Args.push_back(
4028 Elt: llvm::ConstantInt::get(Ty: CGM.Int32Ty, V: getBaseMachOPlatformID(TT)));
4029 Args.push_back(Elt: llvm::ConstantInt::get(Ty: CGM.Int32Ty, V: Version.getMajor()));
4030 Args.push_back(Elt: llvm::ConstantInt::get(Ty: CGM.Int32Ty, V: Min.value_or(u: 0)));
4031 Args.push_back(Elt: llvm::ConstantInt::get(Ty: CGM.Int32Ty, V: SMin.value_or(u: 0)));
4032 };
4033
4034 assert(!Version.empty() && "unexpected empty version");
4035 EmitArgs(Version, CGM.getTarget().getTriple());
4036
4037 if (!CGM.IsPlatformVersionAtLeastFn) {
4038 llvm::FunctionType *FTy = llvm::FunctionType::get(
4039 Result: CGM.Int32Ty, Params: {CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty},
4040 isVarArg: false);
4041 CGM.IsPlatformVersionAtLeastFn =
4042 CGM.CreateRuntimeFunction(Ty: FTy, Name: "__isPlatformVersionAtLeast");
4043 }
4044
4045 llvm::Value *Check =
4046 CGF.EmitNounwindRuntimeCall(callee: CGM.IsPlatformVersionAtLeastFn, args: Args);
4047 return CGF.Builder.CreateICmpNE(LHS: Check,
4048 RHS: llvm::Constant::getNullValue(Ty: CGM.Int32Ty));
4049}
4050
4051llvm::Value *
4052CodeGenFunction::EmitBuiltinAvailable(const VersionTuple &Version) {
4053 // Darwin uses the new __isPlatformVersionAtLeast family of routines.
4054 if (CGM.getTarget().getTriple().isOSDarwin())
4055 return emitIsPlatformVersionAtLeast(CGF&: *this, Version);
4056
4057 if (!CGM.IsOSVersionAtLeastFn) {
4058 llvm::FunctionType *FTy =
4059 llvm::FunctionType::get(Result: Int32Ty, Params: {Int32Ty, Int32Ty, Int32Ty}, isVarArg: false);
4060 CGM.IsOSVersionAtLeastFn =
4061 CGM.CreateRuntimeFunction(Ty: FTy, Name: "__isOSVersionAtLeast");
4062 }
4063
4064 std::optional<unsigned> Min = Version.getMinor(),
4065 SMin = Version.getSubminor();
4066 llvm::Value *Args[] = {
4067 llvm::ConstantInt::get(Ty: CGM.Int32Ty, V: Version.getMajor()),
4068 llvm::ConstantInt::get(Ty: CGM.Int32Ty, V: Min.value_or(u: 0)),
4069 llvm::ConstantInt::get(Ty: CGM.Int32Ty, V: SMin.value_or(u: 0))};
4070
4071 llvm::Value *CallRes =
4072 EmitNounwindRuntimeCall(callee: CGM.IsOSVersionAtLeastFn, args: Args);
4073
4074 return Builder.CreateICmpNE(LHS: CallRes, RHS: llvm::Constant::getNullValue(Ty: Int32Ty));
4075}
4076
4077static bool isFoundationNeededForDarwinAvailabilityCheck(
4078 const llvm::Triple &TT, const VersionTuple &TargetVersion) {
4079 VersionTuple FoundationDroppedInVersion;
4080 switch (TT.getOS()) {
4081 case llvm::Triple::IOS:
4082 case llvm::Triple::TvOS:
4083 FoundationDroppedInVersion = VersionTuple(/*Major=*/13);
4084 break;
4085 case llvm::Triple::WatchOS:
4086 FoundationDroppedInVersion = VersionTuple(/*Major=*/6);
4087 break;
4088 case llvm::Triple::Darwin:
4089 case llvm::Triple::MacOSX:
4090 FoundationDroppedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/15);
4091 break;
4092 case llvm::Triple::XROS:
4093 // XROS doesn't need Foundation.
4094 return false;
4095 case llvm::Triple::DriverKit:
4096 // DriverKit doesn't need Foundation.
4097 return false;
4098 default:
4099 llvm_unreachable("Unexpected OS");
4100 }
4101 return TargetVersion < FoundationDroppedInVersion;
4102}
4103
4104void CodeGenModule::emitAtAvailableLinkGuard() {
4105 if (!IsPlatformVersionAtLeastFn)
4106 return;
4107 // @available requires CoreFoundation only on Darwin.
4108 if (!Target.getTriple().isOSDarwin())
4109 return;
4110 // @available doesn't need Foundation on macOS 10.15+, iOS/tvOS 13+, or
4111 // watchOS 6+.
4112 if (!isFoundationNeededForDarwinAvailabilityCheck(
4113 TT: Target.getTriple(), TargetVersion: Target.getPlatformMinVersion()))
4114 return;
4115 // Add -framework CoreFoundation to the linker commands. We still want to
4116 // emit the core foundation reference down below because otherwise if
4117 // CoreFoundation is not used in the code, the linker won't link the
4118 // framework.
4119 auto &Context = getLLVMContext();
4120 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, Str: "-framework"),
4121 llvm::MDString::get(Context, Str: "CoreFoundation")};
4122 LinkerOptionsMetadata.push_back(Elt: llvm::MDNode::get(Context, MDs: Args));
4123 // Emit a reference to a symbol from CoreFoundation to ensure that
4124 // CoreFoundation is linked into the final binary.
4125 llvm::FunctionType *FTy =
4126 llvm::FunctionType::get(Result: Int32Ty, Params: {VoidPtrTy}, isVarArg: false);
4127 llvm::FunctionCallee CFFunc =
4128 CreateRuntimeFunction(Ty: FTy, Name: "CFBundleGetVersionNumber");
4129
4130 llvm::FunctionType *CheckFTy = llvm::FunctionType::get(Result: VoidTy, Params: {}, isVarArg: false);
4131 llvm::FunctionCallee CFLinkCheckFuncRef = CreateRuntimeFunction(
4132 Ty: CheckFTy, Name: "__clang_at_available_requires_core_foundation_framework",
4133 ExtraAttrs: llvm::AttributeList(), /*Local=*/true);
4134 llvm::Function *CFLinkCheckFunc =
4135 cast<llvm::Function>(Val: CFLinkCheckFuncRef.getCallee()->stripPointerCasts());
4136 if (CFLinkCheckFunc->empty()) {
4137 CFLinkCheckFunc->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
4138 CFLinkCheckFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);
4139 CodeGenFunction CGF(*this);
4140 CGF.Builder.SetInsertPoint(CGF.createBasicBlock(name: "", parent: CFLinkCheckFunc));
4141 CGF.EmitNounwindRuntimeCall(callee: CFFunc,
4142 args: llvm::Constant::getNullValue(Ty: VoidPtrTy));
4143 CGF.Builder.CreateUnreachable();
4144 addCompilerUsedGlobal(GV: CFLinkCheckFunc);
4145 }
4146}
4147
4148CGObjCRuntime::~CGObjCRuntime() {}
4149