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