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