1 //===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit Objective-C code as LLVM code.
12 //===----------------------------------------------------------------------===//
14 #include "CGDebugInfo.h"
15 #include "CGObjCRuntime.h"
16 #include "CodeGenFunction.h"
17 #include "CodeGenModule.h"
18 #include "TargetInfo.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/StmtObjC.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "clang/CodeGen/CGFunctionInfo.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/IR/CallSite.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/InlineAsm.h"
28 using namespace clang;
29 using namespace CodeGen;
31 typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
33 tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
34 static RValue AdjustObjCObjectType(CodeGenFunction &CGF,
38 /// Given the address of a variable of pointer type, find the correct
39 /// null to store into it.
40 static llvm::Constant *getNullForVariable(llvm::Value *addr) {
42 cast<llvm::PointerType>(addr->getType())->getElementType();
43 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
46 /// Emits an instance of NSConstantString representing the object.
47 llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
50 CGM.getObjCRuntime().GenerateConstantString(E->getString());
51 // FIXME: This bitcast should just be made an invariant on the Runtime.
52 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
55 /// EmitObjCBoxedExpr - This routine generates code to call
56 /// the appropriate expression boxing method. This will either be
57 /// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:],
58 /// or [NSValue valueWithBytes:objCType:].
61 CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
62 // Generate the correct selector for this literal's concrete type.
64 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
65 const Expr *SubExpr = E->getSubExpr();
66 assert(BoxingMethod && "BoxingMethod is null");
67 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
68 Selector Sel = BoxingMethod->getSelector();
70 // Generate a reference to the class pointer, which will be the receiver.
71 // Assumes that the method was introduced in the class that should be
72 // messaged (avoids pulling it out of the result type).
73 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
74 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
75 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
78 const ParmVarDecl *ArgDecl = *BoxingMethod->param_begin();
79 QualType ArgQT = ArgDecl->getType().getUnqualifiedType();
81 // ObjCBoxedExpr supports boxing of structs and unions
82 // via [NSValue valueWithBytes:objCType:]
83 const QualType ValueType(SubExpr->getType().getCanonicalType());
84 if (ValueType->isObjCBoxableRecordType()) {
85 // Emit CodeGen for first parameter
86 // and cast value to correct type
87 llvm::Value *Temporary = CreateMemTemp(SubExpr->getType());
88 EmitAnyExprToMem(SubExpr, Temporary, Qualifiers(), /*isInit*/ true);
89 llvm::Value *BitCast = Builder.CreateBitCast(Temporary,
91 Args.add(RValue::get(BitCast), ArgQT);
93 // Create char array to store type encoding
95 getContext().getObjCEncodingForType(ValueType, Str);
96 llvm::GlobalVariable *GV = CGM.GetAddrOfConstantCString(Str);
98 // Cast type encoding to correct type
99 const ParmVarDecl *EncodingDecl = BoxingMethod->parameters()[1];
100 QualType EncodingQT = EncodingDecl->getType().getUnqualifiedType();
101 llvm::Value *Cast = Builder.CreateBitCast(GV, ConvertType(EncodingQT));
103 Args.add(RValue::get(Cast), EncodingQT);
105 Args.add(EmitAnyExpr(SubExpr), ArgQT);
108 RValue result = Runtime.GenerateMessageSend(
109 *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
110 Args, ClassDecl, BoxingMethod);
111 return Builder.CreateBitCast(result.getScalarVal(),
112 ConvertType(E->getType()));
115 llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
116 const ObjCMethodDecl *MethodWithObjects) {
117 ASTContext &Context = CGM.getContext();
118 const ObjCDictionaryLiteral *DLE = nullptr;
119 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
121 DLE = cast<ObjCDictionaryLiteral>(E);
123 // Compute the type of the array we're initializing.
124 uint64_t NumElements =
125 ALE ? ALE->getNumElements() : DLE->getNumElements();
126 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
128 QualType ElementType = Context.getObjCIdType().withConst();
129 QualType ElementArrayType
130 = Context.getConstantArrayType(ElementType, APNumElements,
131 ArrayType::Normal, /*IndexTypeQuals=*/0);
133 // Allocate the temporary array(s).
134 llvm::AllocaInst *Objects = CreateMemTemp(ElementArrayType, "objects");
135 llvm::AllocaInst *Keys = nullptr;
137 Keys = CreateMemTemp(ElementArrayType, "keys");
139 // In ARC, we may need to do extra work to keep all the keys and
140 // values alive until after the call.
141 SmallVector<llvm::Value *, 16> NeededObjects;
142 bool TrackNeededObjects =
143 (getLangOpts().ObjCAutoRefCount &&
144 CGM.getCodeGenOpts().OptimizationLevel != 0);
146 // Perform the actual initialialization of the array(s).
147 for (uint64_t i = 0; i < NumElements; i++) {
149 // Emit the element and store it to the appropriate array slot.
150 const Expr *Rhs = ALE->getElement(i);
151 LValue LV = LValue::MakeAddr(
152 Builder.CreateStructGEP(Objects->getAllocatedType(), Objects, i),
153 ElementType, Context.getTypeAlignInChars(Rhs->getType()), Context);
155 llvm::Value *value = EmitScalarExpr(Rhs);
156 EmitStoreThroughLValue(RValue::get(value), LV, true);
157 if (TrackNeededObjects) {
158 NeededObjects.push_back(value);
161 // Emit the key and store it to the appropriate array slot.
162 const Expr *Key = DLE->getKeyValueElement(i).Key;
163 LValue KeyLV = LValue::MakeAddr(
164 Builder.CreateStructGEP(Keys->getAllocatedType(), Keys, i),
165 ElementType, Context.getTypeAlignInChars(Key->getType()), Context);
166 llvm::Value *keyValue = EmitScalarExpr(Key);
167 EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
169 // Emit the value and store it to the appropriate array slot.
170 const Expr *Value = DLE->getKeyValueElement(i).Value;
171 LValue ValueLV = LValue::MakeAddr(
172 Builder.CreateStructGEP(Objects->getAllocatedType(), Objects, i),
173 ElementType, Context.getTypeAlignInChars(Value->getType()), Context);
174 llvm::Value *valueValue = EmitScalarExpr(Value);
175 EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
176 if (TrackNeededObjects) {
177 NeededObjects.push_back(keyValue);
178 NeededObjects.push_back(valueValue);
183 // Generate the argument list.
185 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
186 const ParmVarDecl *argDecl = *PI++;
187 QualType ArgQT = argDecl->getType().getUnqualifiedType();
188 Args.add(RValue::get(Objects), ArgQT);
191 ArgQT = argDecl->getType().getUnqualifiedType();
192 Args.add(RValue::get(Keys), ArgQT);
195 ArgQT = argDecl->getType().getUnqualifiedType();
197 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
198 Args.add(RValue::get(Count), ArgQT);
200 // Generate a reference to the class pointer, which will be the receiver.
201 Selector Sel = MethodWithObjects->getSelector();
202 QualType ResultType = E->getType();
203 const ObjCObjectPointerType *InterfacePointerType
204 = ResultType->getAsObjCInterfacePointerType();
205 ObjCInterfaceDecl *Class
206 = InterfacePointerType->getObjectType()->getInterface();
207 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
208 llvm::Value *Receiver = Runtime.GetClass(*this, Class);
210 // Generate the message send.
211 RValue result = Runtime.GenerateMessageSend(
212 *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
213 Receiver, Args, Class, MethodWithObjects);
215 // The above message send needs these objects, but in ARC they are
216 // passed in a buffer that is essentially __unsafe_unretained.
217 // Therefore we must prevent the optimizer from releasing them until
219 if (TrackNeededObjects) {
220 EmitARCIntrinsicUse(NeededObjects);
223 return Builder.CreateBitCast(result.getScalarVal(),
224 ConvertType(E->getType()));
227 llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
228 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
231 llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
232 const ObjCDictionaryLiteral *E) {
233 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
237 llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
239 // Note that this implementation allows for non-constant strings to be passed
240 // as arguments to @selector(). Currently, the only thing preventing this
241 // behaviour is the type checking in the front end.
242 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
245 llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
246 // FIXME: This should pass the Decl not the name.
247 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
250 /// \brief Adjust the type of an Objective-C object that doesn't match up due
251 /// to type erasure at various points, e.g., related result types or the use
252 /// of parameterized classes.
253 static RValue AdjustObjCObjectType(CodeGenFunction &CGF, QualType ExpT,
255 if (!ExpT->isObjCRetainableType())
258 // If the converted types are the same, we're done.
259 llvm::Type *ExpLLVMTy = CGF.ConvertType(ExpT);
260 if (ExpLLVMTy == Result.getScalarVal()->getType())
263 // We have applied a substitution. Cast the rvalue appropriately.
264 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
268 /// Decide whether to extend the lifetime of the receiver of a
269 /// returns-inner-pointer message.
271 shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
272 switch (message->getReceiverKind()) {
274 // For a normal instance message, we should extend unless the
275 // receiver is loaded from a variable with precise lifetime.
276 case ObjCMessageExpr::Instance: {
277 const Expr *receiver = message->getInstanceReceiver();
278 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
279 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
280 receiver = ice->getSubExpr()->IgnoreParens();
282 // Only __strong variables.
283 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
286 // All ivars and fields have precise lifetime.
287 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
290 // Otherwise, check for variables.
291 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
292 if (!declRef) return true;
293 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
294 if (!var) return true;
296 // All variables have precise lifetime except local variables with
297 // automatic storage duration that aren't specially marked.
298 return (var->hasLocalStorage() &&
299 !var->hasAttr<ObjCPreciseLifetimeAttr>());
302 case ObjCMessageExpr::Class:
303 case ObjCMessageExpr::SuperClass:
304 // It's never necessary for class objects.
307 case ObjCMessageExpr::SuperInstance:
308 // We generally assume that 'self' lives throughout a method call.
312 llvm_unreachable("invalid receiver kind");
315 RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
316 ReturnValueSlot Return) {
317 // Only the lookup mechanism and first two arguments of the method
318 // implementation vary between runtimes. We can get the receiver and
319 // arguments in generic code.
321 bool isDelegateInit = E->isDelegateInitCall();
323 const ObjCMethodDecl *method = E->getMethodDecl();
325 // We don't retain the receiver in delegate init calls, and this is
326 // safe because the receiver value is always loaded from 'self',
327 // which we zero out. We don't want to Block_copy block receivers,
331 CGM.getLangOpts().ObjCAutoRefCount &&
333 method->hasAttr<NSConsumesSelfAttr>());
335 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
336 bool isSuperMessage = false;
337 bool isClassMessage = false;
338 ObjCInterfaceDecl *OID = nullptr;
340 QualType ReceiverType;
341 llvm::Value *Receiver = nullptr;
342 switch (E->getReceiverKind()) {
343 case ObjCMessageExpr::Instance:
344 ReceiverType = E->getInstanceReceiver()->getType();
346 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
347 E->getInstanceReceiver());
348 Receiver = ter.getPointer();
349 if (ter.getInt()) retainSelf = false;
351 Receiver = EmitScalarExpr(E->getInstanceReceiver());
354 case ObjCMessageExpr::Class: {
355 ReceiverType = E->getClassReceiver();
356 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
357 assert(ObjTy && "Invalid Objective-C class message send");
358 OID = ObjTy->getInterface();
359 assert(OID && "Invalid Objective-C class message send");
360 Receiver = Runtime.GetClass(*this, OID);
361 isClassMessage = true;
365 case ObjCMessageExpr::SuperInstance:
366 ReceiverType = E->getSuperType();
367 Receiver = LoadObjCSelf();
368 isSuperMessage = true;
371 case ObjCMessageExpr::SuperClass:
372 ReceiverType = E->getSuperType();
373 Receiver = LoadObjCSelf();
374 isSuperMessage = true;
375 isClassMessage = true;
380 Receiver = EmitARCRetainNonBlock(Receiver);
382 // In ARC, we sometimes want to "extend the lifetime"
383 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
385 if (getLangOpts().ObjCAutoRefCount && method &&
386 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
387 shouldExtendReceiverForInnerPointerMessage(E))
388 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
390 QualType ResultType = method ? method->getReturnType() : E->getType();
393 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end());
395 // For delegate init calls in ARC, do an unsafe store of null into
396 // self. This represents the call taking direct ownership of that
397 // value. We have to do this after emitting the other call
398 // arguments because they might also reference self, but we don't
399 // have to worry about any of them modifying self because that would
400 // be an undefined read and write of an object in unordered
402 if (isDelegateInit) {
403 assert(getLangOpts().ObjCAutoRefCount &&
404 "delegate init calls should only be marked in ARC");
406 // Do an unsafe store of null into self.
407 llvm::Value *selfAddr =
408 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
409 assert(selfAddr && "no self entry for a delegate init call?");
411 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
415 if (isSuperMessage) {
416 // super is only valid in an Objective-C method
417 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
418 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
419 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
421 OMD->getClassInterface(),
428 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
434 // For delegate init calls in ARC, implicitly store the result of
435 // the call back into self. This takes ownership of the value.
436 if (isDelegateInit) {
437 llvm::Value *selfAddr =
438 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
439 llvm::Value *newSelf = result.getScalarVal();
441 // The delegate return type isn't necessarily a matching type; in
442 // fact, it's quite likely to be 'id'.
444 cast<llvm::PointerType>(selfAddr->getType())->getElementType();
445 newSelf = Builder.CreateBitCast(newSelf, selfTy);
447 Builder.CreateStore(newSelf, selfAddr);
450 return AdjustObjCObjectType(*this, E->getType(), result);
454 struct FinishARCDealloc : EHScopeStack::Cleanup {
455 void Emit(CodeGenFunction &CGF, Flags flags) override {
456 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
458 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
459 const ObjCInterfaceDecl *iface = impl->getClassInterface();
460 if (!iface->getSuperClass()) return;
462 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
464 // Call [super dealloc] if we have a superclass.
465 llvm::Value *self = CGF.LoadObjCSelf();
468 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
469 CGF.getContext().VoidTy,
470 method->getSelector(),
474 /*is class msg*/ false,
481 /// StartObjCMethod - Begin emission of an ObjCMethod. This generates
482 /// the LLVM function and sets the other context used by
484 void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
485 const ObjCContainerDecl *CD) {
486 SourceLocation StartLoc = OMD->getLocStart();
487 FunctionArgList args;
488 // Check if we should generate debug info for this method.
489 if (OMD->hasAttr<NoDebugAttr>())
490 DebugInfo = nullptr; // disable debug info indefinitely for this function
492 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
494 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
495 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
497 args.push_back(OMD->getSelfDecl());
498 args.push_back(OMD->getCmdDecl());
500 args.append(OMD->param_begin(), OMD->param_end());
503 CurEHLocation = OMD->getLocEnd();
505 StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
506 OMD->getLocation(), StartLoc);
508 // In ARC, certain methods get an extra cleanup.
509 if (CGM.getLangOpts().ObjCAutoRefCount &&
510 OMD->isInstanceMethod() &&
511 OMD->getSelector().isUnarySelector()) {
512 const IdentifierInfo *ident =
513 OMD->getSelector().getIdentifierInfoForSlot(0);
514 if (ident->isStr("dealloc"))
515 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
519 static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
520 LValue lvalue, QualType type);
522 /// Generate an Objective-C method. An Objective-C method is a C function with
523 /// its pointer, name, and types registered in the class struture.
524 void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
525 StartObjCMethod(OMD, OMD->getClassInterface());
526 PGO.assignRegionCounters(OMD, CurFn);
527 assert(isa<CompoundStmt>(OMD->getBody()));
528 incrementProfileCounter(OMD->getBody());
529 EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
530 FinishFunction(OMD->getBodyRBrace());
533 /// emitStructGetterCall - Call the runtime function to load a property
534 /// into the return value slot.
535 static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
536 bool isAtomic, bool hasStrong) {
537 ASTContext &Context = CGF.getContext();
540 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(),
541 ivar, 0).getAddress();
543 // objc_copyStruct (ReturnValue, &structIvar,
544 // sizeof (Type of Ivar), isAtomic, false);
547 llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
548 args.add(RValue::get(dest), Context.VoidPtrTy);
550 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
551 args.add(RValue::get(src), Context.VoidPtrTy);
553 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
554 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
555 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
556 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
558 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
559 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(Context.VoidTy, args,
560 FunctionType::ExtInfo(),
562 fn, ReturnValueSlot(), args);
565 /// Determine whether the given architecture supports unaligned atomic
566 /// accesses. They don't have to be fast, just faster than a function
567 /// call and a mutex.
568 static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
569 // FIXME: Allow unaligned atomic load/store on x86. (It is not
570 // currently supported by the backend.)
574 /// Return the maximum size that permits atomic accesses for the given
576 static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
577 llvm::Triple::ArchType arch) {
578 // ARM has 8-byte atomic accesses, but it's not clear whether we
579 // want to rely on them here.
581 // In the default case, just assume that any size up to a pointer is
582 // fine given adequate alignment.
583 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
587 class PropertyImplStrategy {
590 /// The 'native' strategy is to use the architecture's provided
591 /// reads and writes.
594 /// Use objc_setProperty and objc_getProperty.
597 /// Use objc_setProperty for the setter, but use expression
598 /// evaluation for the getter.
599 SetPropertyAndExpressionGet,
601 /// Use objc_copyStruct.
604 /// The 'expression' strategy is to emit normal assignment or
605 /// lvalue-to-rvalue expressions.
609 StrategyKind getKind() const { return StrategyKind(Kind); }
611 bool hasStrongMember() const { return HasStrong; }
612 bool isAtomic() const { return IsAtomic; }
613 bool isCopy() const { return IsCopy; }
615 CharUnits getIvarSize() const { return IvarSize; }
616 CharUnits getIvarAlignment() const { return IvarAlignment; }
618 PropertyImplStrategy(CodeGenModule &CGM,
619 const ObjCPropertyImplDecl *propImpl);
623 unsigned IsAtomic : 1;
625 unsigned HasStrong : 1;
628 CharUnits IvarAlignment;
632 /// Pick an implementation strategy for the given property synthesis.
633 PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
634 const ObjCPropertyImplDecl *propImpl) {
635 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
636 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
638 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
639 IsAtomic = prop->isAtomic();
640 HasStrong = false; // doesn't matter here.
642 // Evaluate the ivar's size and alignment.
643 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
644 QualType ivarType = ivar->getType();
645 std::tie(IvarSize, IvarAlignment) =
646 CGM.getContext().getTypeInfoInChars(ivarType);
648 // If we have a copy property, we always have to use getProperty/setProperty.
649 // TODO: we could actually use setProperty and an expression for non-atomics.
651 Kind = GetSetProperty;
656 if (setterKind == ObjCPropertyDecl::Retain) {
657 // In GC-only, there's nothing special that needs to be done.
658 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
661 // In ARC, if the property is non-atomic, use expression emission,
662 // which translates to objc_storeStrong. This isn't required, but
663 // it's slightly nicer.
664 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
665 // Using standard expression emission for the setter is only
666 // acceptable if the ivar is __strong, which won't be true if
667 // the property is annotated with __attribute__((NSObject)).
668 // TODO: falling all the way back to objc_setProperty here is
669 // just laziness, though; we could still use objc_storeStrong
670 // if we hacked it right.
671 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
674 Kind = SetPropertyAndExpressionGet;
677 // Otherwise, we need to at least use setProperty. However, if
678 // the property isn't atomic, we can use normal expression
679 // emission for the getter.
680 } else if (!IsAtomic) {
681 Kind = SetPropertyAndExpressionGet;
684 // Otherwise, we have to use both setProperty and getProperty.
686 Kind = GetSetProperty;
691 // If we're not atomic, just use expression accesses.
697 // Properties on bitfield ivars need to be emitted using expression
698 // accesses even if they're nominally atomic.
699 if (ivar->isBitField()) {
704 // GC-qualified or ARC-qualified ivars need to be emitted as
705 // expressions. This actually works out to being atomic anyway,
706 // except for ARC __strong, but that should trigger the above code.
707 if (ivarType.hasNonTrivialObjCLifetime() ||
708 (CGM.getLangOpts().getGC() &&
709 CGM.getContext().getObjCGCAttrKind(ivarType))) {
714 // Compute whether the ivar has strong members.
715 if (CGM.getLangOpts().getGC())
716 if (const RecordType *recordType = ivarType->getAs<RecordType>())
717 HasStrong = recordType->getDecl()->hasObjectMember();
719 // We can never access structs with object members with a native
720 // access, because we need to use write barriers. This is what
721 // objc_copyStruct is for.
727 // Otherwise, this is target-dependent and based on the size and
728 // alignment of the ivar.
730 // If the size of the ivar is not a power of two, give up. We don't
731 // want to get into the business of doing compare-and-swaps.
732 if (!IvarSize.isPowerOfTwo()) {
737 llvm::Triple::ArchType arch =
738 CGM.getTarget().getTriple().getArch();
740 // Most architectures require memory to fit within a single cache
741 // line, so the alignment has to be at least the size of the access.
742 // Otherwise we have to grab a lock.
743 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
748 // If the ivar's size exceeds the architecture's maximum atomic
749 // access size, we have to use CopyStruct.
750 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
755 // Otherwise, we can use native loads and stores.
759 /// \brief Generate an Objective-C property getter function.
761 /// The given Decl must be an ObjCImplementationDecl. \@synthesize
762 /// is illegal within a category.
763 void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
764 const ObjCPropertyImplDecl *PID) {
765 llvm::Constant *AtomicHelperFn =
766 CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
767 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
768 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
769 assert(OMD && "Invalid call to generate getter (empty method)");
770 StartObjCMethod(OMD, IMP->getClassInterface());
772 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
777 static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
778 const Expr *getter = propImpl->getGetterCXXConstructor();
779 if (!getter) return true;
781 // Sema only makes only of these when the ivar has a C++ class type,
782 // so the form is pretty constrained.
784 // If the property has a reference type, we might just be binding a
785 // reference, in which case the result will be a gl-value. We should
786 // treat this as a non-trivial operation.
787 if (getter->isGLValue())
790 // If we selected a trivial copy-constructor, we're okay.
791 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
792 return (construct->getConstructor()->isTrivial());
794 // The constructor might require cleanups (in which case it's never
796 assert(isa<ExprWithCleanups>(getter));
800 /// emitCPPObjectAtomicGetterCall - Call the runtime function to
801 /// copy the ivar into the resturn slot.
802 static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
803 llvm::Value *returnAddr,
805 llvm::Constant *AtomicHelperFn) {
806 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
810 // The 1st argument is the return Slot.
811 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
813 // The 2nd argument is the address of the ivar.
814 llvm::Value *ivarAddr =
815 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
816 CGF.LoadObjCSelf(), ivar, 0).getAddress();
817 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
818 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
820 // Third argument is the helper function.
821 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
823 llvm::Value *copyCppAtomicObjectFn =
824 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
825 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
827 FunctionType::ExtInfo(),
829 copyCppAtomicObjectFn, ReturnValueSlot(), args);
833 CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
834 const ObjCPropertyImplDecl *propImpl,
835 const ObjCMethodDecl *GetterMethodDecl,
836 llvm::Constant *AtomicHelperFn) {
837 // If there's a non-trivial 'get' expression, we just have to emit that.
838 if (!hasTrivialGetExpr(propImpl)) {
839 if (!AtomicHelperFn) {
840 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
845 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
846 emitCPPObjectAtomicGetterCall(*this, ReturnValue,
847 ivar, AtomicHelperFn);
852 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
853 QualType propType = prop->getType();
854 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
856 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
858 // Pick an implementation strategy.
859 PropertyImplStrategy strategy(CGM, propImpl);
860 switch (strategy.getKind()) {
861 case PropertyImplStrategy::Native: {
862 // We don't need to do anything for a zero-size struct.
863 if (strategy.getIvarSize().isZero())
866 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
868 // Currently, all atomic accesses have to be through integer
869 // types, so there's no point in trying to pick a prettier type.
870 llvm::Type *bitcastType =
871 llvm::Type::getIntNTy(getLLVMContext(),
872 getContext().toBits(strategy.getIvarSize()));
873 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
875 // Perform an atomic load. This does not impose ordering constraints.
876 llvm::Value *ivarAddr = LV.getAddress();
877 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
878 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
879 load->setAlignment(strategy.getIvarAlignment().getQuantity());
880 load->setAtomic(llvm::Unordered);
882 // Store that value into the return address. Doing this with a
883 // bitcast is likely to produce some pretty ugly IR, but it's not
884 // the *most* terrible thing in the world.
885 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
887 // Make sure we don't do an autorelease.
888 AutoreleaseResult = false;
892 case PropertyImplStrategy::GetSetProperty: {
893 llvm::Value *getPropertyFn =
894 CGM.getObjCRuntime().GetPropertyGetFunction();
895 if (!getPropertyFn) {
896 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
900 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
901 // FIXME: Can't this be simpler? This might even be worse than the
902 // corresponding gcc code.
904 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
905 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
906 llvm::Value *ivarOffset =
907 EmitIvarOffset(classImpl->getClassInterface(), ivar);
910 args.add(RValue::get(self), getContext().getObjCIdType());
911 args.add(RValue::get(cmd), getContext().getObjCSelType());
912 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
913 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
914 getContext().BoolTy);
916 // FIXME: We shouldn't need to get the function info here, the
917 // runtime already should have computed it to build the function.
918 llvm::Instruction *CallInstruction;
919 RValue RV = EmitCall(getTypes().arrangeFreeFunctionCall(propType, args,
920 FunctionType::ExtInfo(),
922 getPropertyFn, ReturnValueSlot(), args, nullptr,
924 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
927 // We need to fix the type here. Ivars with copy & retain are
928 // always objects so we don't need to worry about complex or
930 RV = RValue::get(Builder.CreateBitCast(
932 getTypes().ConvertType(getterMethod->getReturnType())));
934 EmitReturnOfRValue(RV, propType);
936 // objc_getProperty does an autorelease, so we should suppress ours.
937 AutoreleaseResult = false;
942 case PropertyImplStrategy::CopyStruct:
943 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
944 strategy.hasStrongMember());
947 case PropertyImplStrategy::Expression:
948 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
949 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
951 QualType ivarType = ivar->getType();
952 switch (getEvaluationKind(ivarType)) {
954 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
955 EmitStoreOfComplex(pair,
956 MakeNaturalAlignAddrLValue(ReturnValue, ivarType),
961 // The return value slot is guaranteed to not be aliased, but
962 // that's not necessarily the same as "on the stack", so
963 // we still potentially need objc_memmove_collectable.
964 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
968 if (propType->isReferenceType()) {
969 value = LV.getAddress();
971 // We want to load and autoreleaseReturnValue ARC __weak ivars.
972 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
973 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
975 // Otherwise we want to do a simple load, suppressing the
976 // final autorelease.
978 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
979 AutoreleaseResult = false;
982 value = Builder.CreateBitCast(value, ConvertType(propType));
983 value = Builder.CreateBitCast(
984 value, ConvertType(GetterMethodDecl->getReturnType()));
987 EmitReturnOfRValue(RValue::get(value), propType);
991 llvm_unreachable("bad evaluation kind");
995 llvm_unreachable("bad @property implementation strategy!");
998 /// emitStructSetterCall - Call the runtime function to store the value
999 /// from the first formal parameter into the given ivar.
1000 static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
1001 ObjCIvarDecl *ivar) {
1002 // objc_copyStruct (&structIvar, &Arg,
1003 // sizeof (struct something), true, false);
1006 // The first argument is the address of the ivar.
1007 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1008 CGF.LoadObjCSelf(), ivar, 0)
1010 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1011 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1013 // The second argument is the address of the parameter variable.
1014 ParmVarDecl *argVar = *OMD->param_begin();
1015 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
1016 VK_LValue, SourceLocation());
1017 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
1018 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1019 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1021 // The third argument is the sizeof the type.
1023 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1024 args.add(RValue::get(size), CGF.getContext().getSizeType());
1026 // The fourth argument is the 'isAtomic' flag.
1027 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
1029 // The fifth argument is the 'hasStrong' flag.
1030 // FIXME: should this really always be false?
1031 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1033 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
1034 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1036 FunctionType::ExtInfo(),
1038 copyStructFn, ReturnValueSlot(), args);
1041 /// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1042 /// the value from the first formal parameter into the given ivar, using
1043 /// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
1044 static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
1045 ObjCMethodDecl *OMD,
1047 llvm::Constant *AtomicHelperFn) {
1048 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
1052 // The first argument is the address of the ivar.
1053 llvm::Value *ivarAddr =
1054 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1055 CGF.LoadObjCSelf(), ivar, 0).getAddress();
1056 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1057 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1059 // The second argument is the address of the parameter variable.
1060 ParmVarDecl *argVar = *OMD->param_begin();
1061 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
1062 VK_LValue, SourceLocation());
1063 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
1064 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1065 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1067 // Third argument is the helper function.
1068 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1070 llvm::Value *copyCppAtomicObjectFn =
1071 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
1072 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1074 FunctionType::ExtInfo(),
1076 copyCppAtomicObjectFn, ReturnValueSlot(), args);
1080 static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1081 Expr *setter = PID->getSetterCXXAssignment();
1082 if (!setter) return true;
1084 // Sema only makes only of these when the ivar has a C++ class type,
1085 // so the form is pretty constrained.
1087 // An operator call is trivial if the function it calls is trivial.
1088 // This also implies that there's nothing non-trivial going on with
1089 // the arguments, because operator= can only be trivial if it's a
1090 // synthesized assignment operator and therefore both parameters are
1092 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
1093 if (const FunctionDecl *callee
1094 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1095 if (callee->isTrivial())
1100 assert(isa<ExprWithCleanups>(setter));
1104 static bool UseOptimizedSetter(CodeGenModule &CGM) {
1105 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
1107 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
1111 CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
1112 const ObjCPropertyImplDecl *propImpl,
1113 llvm::Constant *AtomicHelperFn) {
1114 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
1115 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1116 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
1118 // Just use the setter expression if Sema gave us one and it's
1120 if (!hasTrivialSetExpr(propImpl)) {
1121 if (!AtomicHelperFn)
1122 // If non-atomic, assignment is called directly.
1123 EmitStmt(propImpl->getSetterCXXAssignment());
1125 // If atomic, assignment is called via a locking api.
1126 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1131 PropertyImplStrategy strategy(CGM, propImpl);
1132 switch (strategy.getKind()) {
1133 case PropertyImplStrategy::Native: {
1134 // We don't need to do anything for a zero-size struct.
1135 if (strategy.getIvarSize().isZero())
1138 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
1141 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1142 llvm::Value *ivarAddr = ivarLValue.getAddress();
1144 // Currently, all atomic accesses have to be through integer
1145 // types, so there's no point in trying to pick a prettier type.
1146 llvm::Type *bitcastType =
1147 llvm::Type::getIntNTy(getLLVMContext(),
1148 getContext().toBits(strategy.getIvarSize()));
1149 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1151 // Cast both arguments to the chosen operation type.
1152 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
1153 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1155 // This bitcast load is likely to cause some nasty IR.
1156 llvm::Value *load = Builder.CreateLoad(argAddr);
1158 // Perform an atomic store. There are no memory ordering requirements.
1159 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1160 store->setAlignment(strategy.getIvarAlignment().getQuantity());
1161 store->setAtomic(llvm::Unordered);
1165 case PropertyImplStrategy::GetSetProperty:
1166 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1168 llvm::Value *setOptimizedPropertyFn = nullptr;
1169 llvm::Value *setPropertyFn = nullptr;
1170 if (UseOptimizedSetter(CGM)) {
1171 // 10.8 and iOS 6.0 code and GC is off
1172 setOptimizedPropertyFn =
1173 CGM.getObjCRuntime()
1174 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1176 if (!setOptimizedPropertyFn) {
1177 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1182 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1183 if (!setPropertyFn) {
1184 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1189 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1190 // <is-atomic>, <is-copy>).
1192 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
1194 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1195 llvm::Value *ivarOffset =
1196 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1197 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
1198 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
1201 args.add(RValue::get(self), getContext().getObjCIdType());
1202 args.add(RValue::get(cmd), getContext().getObjCSelType());
1203 if (setOptimizedPropertyFn) {
1204 args.add(RValue::get(arg), getContext().getObjCIdType());
1205 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1206 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1207 FunctionType::ExtInfo(),
1209 setOptimizedPropertyFn, ReturnValueSlot(), args);
1211 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1212 args.add(RValue::get(arg), getContext().getObjCIdType());
1213 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1214 getContext().BoolTy);
1215 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1216 getContext().BoolTy);
1217 // FIXME: We shouldn't need to get the function info here, the runtime
1218 // already should have computed it to build the function.
1219 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1220 FunctionType::ExtInfo(),
1222 setPropertyFn, ReturnValueSlot(), args);
1228 case PropertyImplStrategy::CopyStruct:
1229 emitStructSetterCall(*this, setterMethod, ivar);
1232 case PropertyImplStrategy::Expression:
1236 // Otherwise, fake up some ASTs and emit a normal assignment.
1237 ValueDecl *selfDecl = setterMethod->getSelfDecl();
1238 DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1239 VK_LValue, SourceLocation());
1240 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1241 selfDecl->getType(), CK_LValueToRValue, &self,
1243 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
1244 SourceLocation(), SourceLocation(),
1245 &selfLoad, true, true);
1247 ParmVarDecl *argDecl = *setterMethod->param_begin();
1248 QualType argType = argDecl->getType().getNonReferenceType();
1249 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
1250 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1251 argType.getUnqualifiedType(), CK_LValueToRValue,
1254 // The property type can differ from the ivar type in some situations with
1255 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1256 // The following absurdity is just to ensure well-formed IR.
1257 CastKind argCK = CK_NoOp;
1258 if (ivarRef.getType()->isObjCObjectPointerType()) {
1259 if (argLoad.getType()->isObjCObjectPointerType())
1261 else if (argLoad.getType()->isBlockPointerType())
1262 argCK = CK_BlockPointerToObjCPointerCast;
1264 argCK = CK_CPointerToObjCPointerCast;
1265 } else if (ivarRef.getType()->isBlockPointerType()) {
1266 if (argLoad.getType()->isBlockPointerType())
1269 argCK = CK_AnyPointerToBlockPointerCast;
1270 } else if (ivarRef.getType()->isPointerType()) {
1273 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1274 ivarRef.getType(), argCK, &argLoad,
1276 Expr *finalArg = &argLoad;
1277 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1279 finalArg = &argCast;
1282 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1283 ivarRef.getType(), VK_RValue, OK_Ordinary,
1284 SourceLocation(), false);
1288 /// \brief Generate an Objective-C property setter function.
1290 /// The given Decl must be an ObjCImplementationDecl. \@synthesize
1291 /// is illegal within a category.
1292 void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1293 const ObjCPropertyImplDecl *PID) {
1294 llvm::Constant *AtomicHelperFn =
1295 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
1296 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1297 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1298 assert(OMD && "Invalid call to generate setter (empty method)");
1299 StartObjCMethod(OMD, IMP->getClassInterface());
1301 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
1307 struct DestroyIvar : EHScopeStack::Cleanup {
1310 const ObjCIvarDecl *ivar;
1311 CodeGenFunction::Destroyer *destroyer;
1312 bool useEHCleanupForArray;
1314 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1315 CodeGenFunction::Destroyer *destroyer,
1316 bool useEHCleanupForArray)
1317 : addr(addr), ivar(ivar), destroyer(destroyer),
1318 useEHCleanupForArray(useEHCleanupForArray) {}
1320 void Emit(CodeGenFunction &CGF, Flags flags) override {
1322 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1323 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
1324 flags.isForNormalCleanup() && useEHCleanupForArray);
1329 /// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1330 static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1333 llvm::Value *null = getNullForVariable(addr);
1334 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1337 static void emitCXXDestructMethod(CodeGenFunction &CGF,
1338 ObjCImplementationDecl *impl) {
1339 CodeGenFunction::RunCleanupsScope scope(CGF);
1341 llvm::Value *self = CGF.LoadObjCSelf();
1343 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1344 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
1345 ivar; ivar = ivar->getNextIvar()) {
1346 QualType type = ivar->getType();
1348 // Check whether the ivar is a destructible type.
1349 QualType::DestructionKind dtorKind = type.isDestructedType();
1350 if (!dtorKind) continue;
1352 CodeGenFunction::Destroyer *destroyer = nullptr;
1354 // Use a call to objc_storeStrong to destroy strong ivars, for the
1355 // general benefit of the tools.
1356 if (dtorKind == QualType::DK_objc_strong_lifetime) {
1357 destroyer = destroyARCStrongWithStore;
1359 // Otherwise use the default for the destruction kind.
1361 destroyer = CGF.getDestroyer(dtorKind);
1364 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1366 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1367 cleanupKind & EHCleanup);
1370 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1373 void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1376 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
1377 StartObjCMethod(MD, IMP->getClassInterface());
1379 // Emit .cxx_construct.
1381 // Suppress the final autorelease in ARC.
1382 AutoreleaseResult = false;
1384 for (const auto *IvarInit : IMP->inits()) {
1385 FieldDecl *Field = IvarInit->getAnyMember();
1386 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
1387 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1388 LoadObjCSelf(), Ivar, 0);
1389 EmitAggExpr(IvarInit->getInit(),
1390 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
1391 AggValueSlot::DoesNotNeedGCBarriers,
1392 AggValueSlot::IsNotAliased));
1394 // constructor returns 'self'.
1395 CodeGenTypes &Types = CGM.getTypes();
1396 QualType IdTy(CGM.getContext().getObjCIdType());
1397 llvm::Value *SelfAsId =
1398 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1399 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
1401 // Emit .cxx_destruct.
1403 emitCXXDestructMethod(*this, IMP);
1408 bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1409 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1411 const ABIArgInfo &AI = it->info;
1412 // FIXME. Is this sufficient check?
1413 return (AI.getKind() == ABIArgInfo::Indirect);
1416 bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
1417 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
1419 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1420 return FDTTy->getDecl()->hasObjectMember();
1424 llvm::Value *CodeGenFunction::LoadObjCSelf() {
1425 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
1426 DeclRefExpr DRE(Self, /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
1427 Self->getType(), VK_LValue, SourceLocation());
1428 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
1431 QualType CodeGenFunction::TypeOfSelfObject() {
1432 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1433 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
1434 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1435 getContext().getCanonicalType(selfDecl->getType()));
1436 return PTy->getPointeeType();
1439 void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
1440 llvm::Constant *EnumerationMutationFn =
1441 CGM.getObjCRuntime().EnumerationMutationFunction();
1443 if (!EnumerationMutationFn) {
1444 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1448 CGDebugInfo *DI = getDebugInfo();
1450 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
1452 // The local variable comes into scope immediately.
1453 AutoVarEmission variable = AutoVarEmission::invalid();
1454 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1455 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1457 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
1459 // Fast enumeration state.
1460 QualType StateTy = CGM.getObjCFastEnumerationStateType();
1461 llvm::AllocaInst *StatePtr = CreateMemTemp(StateTy, "state.ptr");
1462 EmitNullInitialization(StatePtr, StateTy);
1464 // Number of elements in the items array.
1465 static const unsigned NumItems = 16;
1467 // Fetch the countByEnumeratingWithState:objects:count: selector.
1468 IdentifierInfo *II[] = {
1469 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1470 &CGM.getContext().Idents.get("objects"),
1471 &CGM.getContext().Idents.get("count")
1473 Selector FastEnumSel =
1474 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
1477 getContext().getConstantArrayType(getContext().getObjCIdType(),
1478 llvm::APInt(32, NumItems),
1479 ArrayType::Normal, 0);
1480 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
1482 // Emit the collection pointer. In ARC, we do a retain.
1483 llvm::Value *Collection;
1484 if (getLangOpts().ObjCAutoRefCount) {
1485 Collection = EmitARCRetainScalarExpr(S.getCollection());
1487 // Enter a cleanup to do the release.
1488 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1490 Collection = EmitScalarExpr(S.getCollection());
1493 // The 'continue' label needs to appear within the cleanup for the
1494 // collection object.
1495 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1497 // Send it our message:
1500 // The first argument is a temporary of the enumeration-state type.
1501 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
1503 // The second argument is a temporary array with space for NumItems
1504 // pointers. We'll actually be loading elements from the array
1505 // pointer written into the control state; this buffer is so that
1506 // collections that *aren't* backed by arrays can still queue up
1507 // batches of elements.
1508 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
1510 // The third argument is the capacity of that temporary array.
1511 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
1512 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
1513 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
1515 // Start the enumeration.
1517 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1518 getContext().UnsignedLongTy,
1522 // The initial number of objects that were returned in the buffer.
1523 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
1525 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1526 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
1528 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
1530 // If the limit pointer was zero to begin with, the collection is
1531 // empty; skip all this. Set the branch weight assuming this has the same
1532 // probability of exiting the loop as any other loop exit.
1533 uint64_t EntryCount = getCurrentProfileCount();
1534 Builder.CreateCondBr(
1535 Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1537 createProfileWeights(EntryCount, getProfileCount(S.getBody())));
1539 // Otherwise, initialize the loop.
1540 EmitBlock(LoopInitBB);
1542 // Save the initial mutations value. This is the value at an
1543 // address that was written into the state object by
1544 // countByEnumeratingWithState:objects:count:.
1545 llvm::Value *StateMutationsPtrPtr = Builder.CreateStructGEP(
1546 StatePtr->getAllocatedType(), StatePtr, 2, "mutationsptr.ptr");
1547 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
1550 llvm::Value *initialMutations =
1551 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
1553 // Start looping. This is the point we return to whenever we have a
1554 // fresh, non-empty batch of objects.
1555 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1556 EmitBlock(LoopBodyBB);
1558 // The current index into the buffer.
1559 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
1560 index->addIncoming(zero, LoopInitBB);
1562 // The current buffer size.
1563 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
1564 count->addIncoming(initialBufferLimit, LoopInitBB);
1566 incrementProfileCounter(&S);
1568 // Check whether the mutations value has changed from where it was
1569 // at start. StateMutationsPtr should actually be invariant between
1571 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
1572 llvm::Value *currentMutations
1573 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
1575 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
1576 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
1578 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1579 WasNotMutatedBB, WasMutatedBB);
1581 // If so, call the enumeration-mutation function.
1582 EmitBlock(WasMutatedBB);
1584 Builder.CreateBitCast(Collection,
1585 ConvertType(getContext().getObjCIdType()));
1587 Args2.add(RValue::get(V), getContext().getObjCIdType());
1588 // FIXME: We shouldn't need to get the function info here, the runtime already
1589 // should have computed it to build the function.
1590 EmitCall(CGM.getTypes().arrangeFreeFunctionCall(getContext().VoidTy, Args2,
1591 FunctionType::ExtInfo(),
1593 EnumerationMutationFn, ReturnValueSlot(), Args2);
1595 // Otherwise, or if the mutation function returns, just continue.
1596 EmitBlock(WasNotMutatedBB);
1598 // Initialize the element variable.
1599 RunCleanupsScope elementVariableScope(*this);
1600 bool elementIsVariable;
1601 LValue elementLValue;
1602 QualType elementType;
1603 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
1604 // Initialize the variable, in case it's a __block variable or something.
1605 EmitAutoVarInit(variable);
1607 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
1608 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
1609 VK_LValue, SourceLocation());
1610 elementLValue = EmitLValue(&tempDRE);
1611 elementType = D->getType();
1612 elementIsVariable = true;
1614 if (D->isARCPseudoStrong())
1615 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
1617 elementLValue = LValue(); // suppress warning
1618 elementType = cast<Expr>(S.getElement())->getType();
1619 elementIsVariable = false;
1621 llvm::Type *convertedElementType = ConvertType(elementType);
1623 // Fetch the buffer out of the enumeration state.
1624 // TODO: this pointer should actually be invariant between
1625 // refreshes, which would help us do certain loop optimizations.
1626 llvm::Value *StateItemsPtr = Builder.CreateStructGEP(
1627 StatePtr->getAllocatedType(), StatePtr, 1, "stateitems.ptr");
1628 llvm::Value *EnumStateItems =
1629 Builder.CreateLoad(StateItemsPtr, "stateitems");
1631 // Fetch the value at the current index from the buffer.
1632 llvm::Value *CurrentItemPtr =
1633 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1634 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
1636 // Cast that value to the right type.
1637 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1640 // Make sure we have an l-value. Yes, this gets evaluated every
1641 // time through the loop.
1642 if (!elementIsVariable) {
1643 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
1644 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
1646 EmitScalarInit(CurrentItem, elementLValue);
1649 // If we do have an element variable, this assignment is the end of
1650 // its initialization.
1651 if (elementIsVariable)
1652 EmitAutoVarCleanups(variable);
1654 // Perform the loop body, setting up break and continue labels.
1655 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
1657 RunCleanupsScope Scope(*this);
1658 EmitStmt(S.getBody());
1660 BreakContinueStack.pop_back();
1662 // Destroy the element variable now.
1663 elementVariableScope.ForceCleanup();
1665 // Check whether there are more elements.
1666 EmitBlock(AfterBody.getBlock());
1668 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
1670 // First we check in the local buffer.
1671 llvm::Value *indexPlusOne
1672 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
1674 // If we haven't overrun the buffer yet, we can continue.
1675 // Set the branch weights based on the simplifying assumption that this is
1676 // like a while-loop, i.e., ignoring that the false branch fetches more
1677 // elements and then returns to the loop.
1678 Builder.CreateCondBr(
1679 Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
1680 createProfileWeights(getProfileCount(S.getBody()), EntryCount));
1682 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1683 count->addIncoming(count, AfterBody.getBlock());
1685 // Otherwise, we have to fetch more elements.
1686 EmitBlock(FetchMoreBB);
1689 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1690 getContext().UnsignedLongTy,
1694 // If we got a zero count, we're done.
1695 llvm::Value *refetchCount = CountRV.getScalarVal();
1697 // (note that the message send might split FetchMoreBB)
1698 index->addIncoming(zero, Builder.GetInsertBlock());
1699 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1701 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1702 EmptyBB, LoopBodyBB);
1704 // No more elements.
1707 if (!elementIsVariable) {
1708 // If the element was not a declaration, set it to be null.
1710 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1711 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
1712 EmitStoreThroughLValue(RValue::get(null), elementLValue);
1716 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
1718 // Leave the cleanup we entered in ARC.
1719 if (getLangOpts().ObjCAutoRefCount)
1722 EmitBlock(LoopEnd.getBlock());
1725 void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
1726 CGM.getObjCRuntime().EmitTryStmt(*this, S);
1729 void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
1730 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1733 void CodeGenFunction::EmitObjCAtSynchronizedStmt(
1734 const ObjCAtSynchronizedStmt &S) {
1735 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
1738 /// Produce the code for a CK_ARCProduceObject. Just does a
1739 /// primitive retain.
1740 llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1741 llvm::Value *value) {
1742 return EmitARCRetain(type, value);
1746 struct CallObjCRelease : EHScopeStack::Cleanup {
1747 CallObjCRelease(llvm::Value *object) : object(object) {}
1748 llvm::Value *object;
1750 void Emit(CodeGenFunction &CGF, Flags flags) override {
1751 // Releases at the end of the full-expression are imprecise.
1752 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
1757 /// Produce the code for a CK_ARCConsumeObject. Does a primitive
1758 /// release at the end of the full-expression.
1759 llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1760 llvm::Value *object) {
1761 // If we're in a conditional branch, we need to make the cleanup
1763 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
1767 llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1768 llvm::Value *value) {
1769 return EmitARCRetainAutorelease(type, value);
1772 /// Given a number of pointers, inform the optimizer that they're
1773 /// being intrinsically used up until this point in the program.
1774 void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
1775 llvm::Constant *&fn = CGM.getARCEntrypoints().clang_arc_use;
1777 llvm::FunctionType *fnType =
1778 llvm::FunctionType::get(CGM.VoidTy, None, true);
1779 fn = CGM.CreateRuntimeFunction(fnType, "clang.arc.use");
1782 // This isn't really a "runtime" function, but as an intrinsic it
1783 // doesn't really matter as long as we align things up.
1784 EmitNounwindRuntimeCall(fn, values);
1788 static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
1789 llvm::FunctionType *type,
1791 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1793 if (llvm::Function *f = dyn_cast<llvm::Function>(fn)) {
1794 // If the target runtime doesn't naturally support ARC, emit weak
1795 // references to the runtime support library. We don't really
1796 // permit this to fail, but we need a particular relocation style.
1797 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
1798 f->setLinkage(llvm::Function::ExternalWeakLinkage);
1799 } else if (fnName == "objc_retain" || fnName == "objc_release") {
1800 // If we have Native ARC, set nonlazybind attribute for these APIs for
1802 f->addFnAttr(llvm::Attribute::NonLazyBind);
1809 /// Perform an operation having the signature
1811 /// where a null input causes a no-op and returns null.
1812 static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1814 llvm::Constant *&fn,
1816 bool isTailCall = false) {
1817 if (isa<llvm::ConstantPointerNull>(value)) return value;
1820 llvm::FunctionType *fnType =
1821 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
1822 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1825 // Cast the argument to 'id'.
1826 llvm::Type *origType = value->getType();
1827 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1829 // Call the function.
1830 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
1832 call->setTailCall();
1834 // Cast the result back to the original type.
1835 return CGF.Builder.CreateBitCast(call, origType);
1838 /// Perform an operation having the following signature:
1840 static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1842 llvm::Constant *&fn,
1845 llvm::FunctionType *fnType =
1846 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrPtrTy, false);
1847 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1850 // Cast the argument to 'id*'.
1851 llvm::Type *origType = addr->getType();
1852 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1854 // Call the function.
1855 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr);
1857 // Cast the result back to a dereference of the original type.
1858 if (origType != CGF.Int8PtrPtrTy)
1859 result = CGF.Builder.CreateBitCast(result,
1860 cast<llvm::PointerType>(origType)->getElementType());
1865 /// Perform an operation having the following signature:
1867 static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1870 llvm::Constant *&fn,
1873 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1874 == value->getType());
1877 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
1879 llvm::FunctionType *fnType
1880 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1881 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1884 llvm::Type *origType = value->getType();
1886 llvm::Value *args[] = {
1887 CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy),
1888 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
1890 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
1892 if (ignored) return nullptr;
1894 return CGF.Builder.CreateBitCast(result, origType);
1897 /// Perform an operation having the following signature:
1898 /// void (i8**, i8**)
1899 static void emitARCCopyOperation(CodeGenFunction &CGF,
1902 llvm::Constant *&fn,
1904 assert(dst->getType() == src->getType());
1907 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrPtrTy };
1909 llvm::FunctionType *fnType
1910 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1911 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1914 llvm::Value *args[] = {
1915 CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy),
1916 CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy)
1918 CGF.EmitNounwindRuntimeCall(fn, args);
1921 /// Produce the code to do a retain. Based on the type, calls one of:
1922 /// call i8* \@objc_retain(i8* %value)
1923 /// call i8* \@objc_retainBlock(i8* %value)
1924 llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1925 if (type->isBlockPointerType())
1926 return EmitARCRetainBlock(value, /*mandatory*/ false);
1928 return EmitARCRetainNonBlock(value);
1931 /// Retain the given object, with normal retain semantics.
1932 /// call i8* \@objc_retain(i8* %value)
1933 llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1934 return emitARCValueOperation(*this, value,
1935 CGM.getARCEntrypoints().objc_retain,
1939 /// Retain the given block, with _Block_copy semantics.
1940 /// call i8* \@objc_retainBlock(i8* %value)
1942 /// \param mandatory - If false, emit the call with metadata
1943 /// indicating that it's okay for the optimizer to eliminate this call
1944 /// if it can prove that the block never escapes except down the stack.
1945 llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1948 = emitARCValueOperation(*this, value,
1949 CGM.getARCEntrypoints().objc_retainBlock,
1950 "objc_retainBlock");
1952 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1953 // tell the optimizer that it doesn't need to do this copy if the
1954 // block doesn't escape, where being passed as an argument doesn't
1955 // count as escaping.
1956 if (!mandatory && isa<llvm::Instruction>(result)) {
1957 llvm::CallInst *call
1958 = cast<llvm::CallInst>(result->stripPointerCasts());
1959 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1961 call->setMetadata("clang.arc.copy_on_escape",
1962 llvm::MDNode::get(Builder.getContext(), None));
1968 /// Retain the given object which is the result of a function call.
1969 /// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
1971 /// Yes, this function name is one character away from a different
1972 /// call with completely different semantics.
1974 CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1975 // Fetch the void(void) inline asm which marks that we're going to
1976 // retain the autoreleased return value.
1977 llvm::InlineAsm *&marker
1978 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1981 = CGM.getTargetCodeGenInfo()
1982 .getARCRetainAutoreleasedReturnValueMarker();
1984 // If we have an empty assembly string, there's nothing to do.
1985 if (assembly.empty()) {
1987 // Otherwise, at -O0, build an inline asm that we're going to call
1989 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1990 llvm::FunctionType *type =
1991 llvm::FunctionType::get(VoidTy, /*variadic*/false);
1993 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1995 // If we're at -O1 and above, we don't want to litter the code
1996 // with this marker yet, so leave a breadcrumb for the ARC
1997 // optimizer to pick up.
1999 llvm::NamedMDNode *metadata =
2000 CGM.getModule().getOrInsertNamedMetadata(
2001 "clang.arc.retainAutoreleasedReturnValueMarker");
2002 assert(metadata->getNumOperands() <= 1);
2003 if (metadata->getNumOperands() == 0) {
2004 metadata->addOperand(llvm::MDNode::get(
2005 getLLVMContext(), llvm::MDString::get(getLLVMContext(), assembly)));
2010 // Call the marker asm if we made one, which we do only at -O0.
2012 Builder.CreateCall(marker);
2014 return emitARCValueOperation(*this, value,
2015 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
2016 "objc_retainAutoreleasedReturnValue");
2019 /// Release the given object.
2020 /// call void \@objc_release(i8* %value)
2021 void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2022 ARCPreciseLifetime_t precise) {
2023 if (isa<llvm::ConstantPointerNull>(value)) return;
2025 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
2027 llvm::FunctionType *fnType =
2028 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2029 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
2032 // Cast the argument to 'id'.
2033 value = Builder.CreateBitCast(value, Int8PtrTy);
2035 // Call objc_release.
2036 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
2038 if (precise == ARCImpreciseLifetime) {
2039 call->setMetadata("clang.imprecise_release",
2040 llvm::MDNode::get(Builder.getContext(), None));
2044 /// Destroy a __strong variable.
2046 /// At -O0, emit a call to store 'null' into the address;
2047 /// instrumenting tools prefer this because the address is exposed,
2048 /// but it's relatively cumbersome to optimize.
2050 /// At -O1 and above, just load and call objc_release.
2052 /// call void \@objc_storeStrong(i8** %addr, i8* null)
2053 void CodeGenFunction::EmitARCDestroyStrong(llvm::Value *addr,
2054 ARCPreciseLifetime_t precise) {
2055 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2056 llvm::PointerType *addrTy = cast<llvm::PointerType>(addr->getType());
2057 llvm::Value *null = llvm::ConstantPointerNull::get(
2058 cast<llvm::PointerType>(addrTy->getElementType()));
2059 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2063 llvm::Value *value = Builder.CreateLoad(addr);
2064 EmitARCRelease(value, precise);
2067 /// Store into a strong object. Always calls this:
2068 /// call void \@objc_storeStrong(i8** %addr, i8* %value)
2069 llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
2072 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
2073 == value->getType());
2075 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
2077 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
2078 llvm::FunctionType *fnType
2079 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
2080 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
2083 llvm::Value *args[] = {
2084 Builder.CreateBitCast(addr, Int8PtrPtrTy),
2085 Builder.CreateBitCast(value, Int8PtrTy)
2087 EmitNounwindRuntimeCall(fn, args);
2089 if (ignored) return nullptr;
2093 /// Store into a strong object. Sometimes calls this:
2094 /// call void \@objc_storeStrong(i8** %addr, i8* %value)
2095 /// Other times, breaks it down into components.
2096 llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
2097 llvm::Value *newValue,
2099 QualType type = dst.getType();
2100 bool isBlock = type->isBlockPointerType();
2102 // Use a store barrier at -O0 unless this is a block type or the
2103 // lvalue is inadequately aligned.
2104 if (shouldUseFusedARCCalls() &&
2106 (dst.getAlignment().isZero() ||
2107 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
2108 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2111 // Otherwise, split it out.
2113 // Retain the new value.
2114 newValue = EmitARCRetain(type, newValue);
2116 // Read the old value.
2117 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
2119 // Store. We do this before the release so that any deallocs won't
2120 // see the old value.
2121 EmitStoreOfScalar(newValue, dst);
2123 // Finally, release the old value.
2124 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
2129 /// Autorelease the given object.
2130 /// call i8* \@objc_autorelease(i8* %value)
2131 llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2132 return emitARCValueOperation(*this, value,
2133 CGM.getARCEntrypoints().objc_autorelease,
2134 "objc_autorelease");
2137 /// Autorelease the given object.
2138 /// call i8* \@objc_autoreleaseReturnValue(i8* %value)
2140 CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2141 return emitARCValueOperation(*this, value,
2142 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
2143 "objc_autoreleaseReturnValue",
2144 /*isTailCall*/ true);
2147 /// Do a fused retain/autorelease of the given object.
2148 /// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
2150 CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2151 return emitARCValueOperation(*this, value,
2152 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
2153 "objc_retainAutoreleaseReturnValue",
2154 /*isTailCall*/ true);
2157 /// Do a fused retain/autorelease of the given object.
2158 /// call i8* \@objc_retainAutorelease(i8* %value)
2160 /// %retain = call i8* \@objc_retainBlock(i8* %value)
2161 /// call i8* \@objc_autorelease(i8* %retain)
2162 llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2163 llvm::Value *value) {
2164 if (!type->isBlockPointerType())
2165 return EmitARCRetainAutoreleaseNonBlock(value);
2167 if (isa<llvm::ConstantPointerNull>(value)) return value;
2169 llvm::Type *origType = value->getType();
2170 value = Builder.CreateBitCast(value, Int8PtrTy);
2171 value = EmitARCRetainBlock(value, /*mandatory*/ true);
2172 value = EmitARCAutorelease(value);
2173 return Builder.CreateBitCast(value, origType);
2176 /// Do a fused retain/autorelease of the given object.
2177 /// call i8* \@objc_retainAutorelease(i8* %value)
2179 CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2180 return emitARCValueOperation(*this, value,
2181 CGM.getARCEntrypoints().objc_retainAutorelease,
2182 "objc_retainAutorelease");
2185 /// i8* \@objc_loadWeak(i8** %addr)
2186 /// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2187 llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
2188 return emitARCLoadOperation(*this, addr,
2189 CGM.getARCEntrypoints().objc_loadWeak,
2193 /// i8* \@objc_loadWeakRetained(i8** %addr)
2194 llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
2195 return emitARCLoadOperation(*this, addr,
2196 CGM.getARCEntrypoints().objc_loadWeakRetained,
2197 "objc_loadWeakRetained");
2200 /// i8* \@objc_storeWeak(i8** %addr, i8* %value)
2202 llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
2205 return emitARCStoreOperation(*this, addr, value,
2206 CGM.getARCEntrypoints().objc_storeWeak,
2207 "objc_storeWeak", ignored);
2210 /// i8* \@objc_initWeak(i8** %addr, i8* %value)
2211 /// Returns %value. %addr is known to not have a current weak entry.
2212 /// Essentially equivalent to:
2213 /// *addr = nil; objc_storeWeak(addr, value);
2214 void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
2215 // If we're initializing to null, just write null to memory; no need
2216 // to get the runtime involved. But don't do this if optimization
2217 // is enabled, because accounting for this would make the optimizer
2218 // much more complicated.
2219 if (isa<llvm::ConstantPointerNull>(value) &&
2220 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2221 Builder.CreateStore(value, addr);
2225 emitARCStoreOperation(*this, addr, value,
2226 CGM.getARCEntrypoints().objc_initWeak,
2227 "objc_initWeak", /*ignored*/ true);
2230 /// void \@objc_destroyWeak(i8** %addr)
2231 /// Essentially objc_storeWeak(addr, nil).
2232 void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
2233 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
2235 llvm::FunctionType *fnType =
2236 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrPtrTy, false);
2237 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2240 // Cast the argument to 'id*'.
2241 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2243 EmitNounwindRuntimeCall(fn, addr);
2246 /// void \@objc_moveWeak(i8** %dest, i8** %src)
2247 /// Disregards the current value in %dest. Leaves %src pointing to nothing.
2248 /// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2249 void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
2250 emitARCCopyOperation(*this, dst, src,
2251 CGM.getARCEntrypoints().objc_moveWeak,
2255 /// void \@objc_copyWeak(i8** %dest, i8** %src)
2256 /// Disregards the current value in %dest. Essentially
2257 /// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2258 void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
2259 emitARCCopyOperation(*this, dst, src,
2260 CGM.getARCEntrypoints().objc_copyWeak,
2264 /// Produce the code to do a objc_autoreleasepool_push.
2265 /// call i8* \@objc_autoreleasePoolPush(void)
2266 llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2267 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
2269 llvm::FunctionType *fnType =
2270 llvm::FunctionType::get(Int8PtrTy, false);
2271 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2274 return EmitNounwindRuntimeCall(fn);
2277 /// Produce the code to do a primitive release.
2278 /// call void \@objc_autoreleasePoolPop(i8* %ptr)
2279 void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2280 assert(value->getType() == Int8PtrTy);
2282 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
2284 llvm::FunctionType *fnType =
2285 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2287 // We don't want to use a weak import here; instead we should not
2288 // fall into this path.
2289 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2292 // objc_autoreleasePoolPop can throw.
2293 EmitRuntimeCallOrInvoke(fn, value);
2296 /// Produce the code to do an MRR version objc_autoreleasepool_push.
2297 /// Which is: [[NSAutoreleasePool alloc] init];
2298 /// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2299 /// init is declared as: - (id) init; in its NSObject super class.
2301 llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2302 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2303 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
2304 // [NSAutoreleasePool alloc]
2305 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2306 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2309 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2310 getContext().getObjCIdType(),
2311 AllocSel, Receiver, Args);
2314 Receiver = AllocRV.getScalarVal();
2315 II = &CGM.getContext().Idents.get("init");
2316 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2318 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2319 getContext().getObjCIdType(),
2320 InitSel, Receiver, Args);
2321 return InitRV.getScalarVal();
2324 /// Produce the code to do a primitive release.
2326 void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2327 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2328 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2330 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2331 getContext().VoidTy, DrainSel, Arg, Args);
2334 void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2337 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
2340 void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2343 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
2346 void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2349 CGF.EmitARCDestroyWeak(addr);
2353 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2356 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2358 void Emit(CodeGenFunction &CGF, Flags flags) override {
2359 CGF.EmitObjCAutoreleasePoolPop(Token);
2362 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2365 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2367 void Emit(CodeGenFunction &CGF, Flags flags) override {
2368 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2373 void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
2374 if (CGM.getLangOpts().ObjCAutoRefCount)
2375 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2377 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2380 static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2383 switch (type.getObjCLifetime()) {
2384 case Qualifiers::OCL_None:
2385 case Qualifiers::OCL_ExplicitNone:
2386 case Qualifiers::OCL_Strong:
2387 case Qualifiers::OCL_Autoreleasing:
2388 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue,
2389 SourceLocation()).getScalarVal(),
2392 case Qualifiers::OCL_Weak:
2393 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2397 llvm_unreachable("impossible lifetime!");
2400 static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2402 e = e->IgnoreParens();
2403 QualType type = e->getType();
2405 // If we're loading retained from a __strong xvalue, we can avoid
2406 // an extra retain/release pair by zeroing out the source of this
2407 // "move" operation.
2408 if (e->isXValue() &&
2409 !type.isConstQualified() &&
2410 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2412 LValue lv = CGF.EmitLValue(e);
2414 // Load the object pointer.
2415 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2416 SourceLocation()).getScalarVal();
2418 // Set the source pointer to NULL.
2419 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2421 return TryEmitResult(result, true);
2424 // As a very special optimization, in ARC++, if the l-value is the
2425 // result of a non-volatile assignment, do a simple retain of the
2426 // result of the call to objc_storeWeak instead of reloading.
2427 if (CGF.getLangOpts().CPlusPlus &&
2428 !type.isVolatileQualified() &&
2429 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2430 isa<BinaryOperator>(e) &&
2431 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2432 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2434 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2437 static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2438 llvm::Value *value);
2440 /// Given that the given expression is some sort of call (which does
2441 /// not return retained), emit a retain following it.
2442 static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2443 llvm::Value *value = CGF.EmitScalarExpr(e);
2444 return emitARCRetainAfterCall(CGF, value);
2447 static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2448 llvm::Value *value) {
2449 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2450 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2452 // Place the retain immediately following the call.
2453 CGF.Builder.SetInsertPoint(call->getParent(),
2454 ++llvm::BasicBlock::iterator(call));
2455 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2457 CGF.Builder.restoreIP(ip);
2459 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2460 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2462 // Place the retain at the beginning of the normal destination block.
2463 llvm::BasicBlock *BB = invoke->getNormalDest();
2464 CGF.Builder.SetInsertPoint(BB, BB->begin());
2465 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2467 CGF.Builder.restoreIP(ip);
2470 // Bitcasts can arise because of related-result returns. Rewrite
2472 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2473 llvm::Value *operand = bitcast->getOperand(0);
2474 operand = emitARCRetainAfterCall(CGF, operand);
2475 bitcast->setOperand(0, operand);
2478 // Generic fall-back case.
2480 // Retain using the non-block variant: we never need to do a copy
2481 // of a block that's been returned to us.
2482 return CGF.EmitARCRetainNonBlock(value);
2486 /// Determine whether it might be important to emit a separate
2487 /// objc_retain_block on the result of the given expression, or
2488 /// whether it's okay to just emit it in a +1 context.
2489 static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2490 assert(e->getType()->isBlockPointerType());
2491 e = e->IgnoreParens();
2493 // For future goodness, emit block expressions directly in +1
2494 // contexts if we can.
2495 if (isa<BlockExpr>(e))
2498 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2499 switch (cast->getCastKind()) {
2500 // Emitting these operations in +1 contexts is goodness.
2501 case CK_LValueToRValue:
2502 case CK_ARCReclaimReturnedObject:
2503 case CK_ARCConsumeObject:
2504 case CK_ARCProduceObject:
2507 // These operations preserve a block type.
2510 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2512 // These operations are known to be bad (or haven't been considered).
2513 case CK_AnyPointerToBlockPointerCast:
2522 /// Try to emit a PseudoObjectExpr at +1.
2524 /// This massively duplicates emitPseudoObjectRValue.
2525 static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2526 const PseudoObjectExpr *E) {
2527 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
2529 // Find the result expression.
2530 const Expr *resultExpr = E->getResultExpr();
2532 TryEmitResult result;
2534 for (PseudoObjectExpr::const_semantics_iterator
2535 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2536 const Expr *semantic = *i;
2538 // If this semantic expression is an opaque value, bind it
2539 // to the result of its source expression.
2540 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2541 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2544 // If this semantic is the result of the pseudo-object
2545 // expression, try to evaluate the source as +1.
2546 if (ov == resultExpr) {
2547 assert(!OVMA::shouldBindAsLValue(ov));
2548 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2549 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2551 // Otherwise, just bind it.
2553 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2555 opaques.push_back(opaqueData);
2557 // Otherwise, if the expression is the result, evaluate it
2558 // and remember the result.
2559 } else if (semantic == resultExpr) {
2560 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2562 // Otherwise, evaluate the expression in an ignored context.
2564 CGF.EmitIgnoredExpr(semantic);
2568 // Unbind all the opaques now.
2569 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2570 opaques[i].unbind(CGF);
2575 static TryEmitResult
2576 tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
2577 // We should *never* see a nested full-expression here, because if
2578 // we fail to emit at +1, our caller must not retain after we close
2579 // out the full-expression.
2580 assert(!isa<ExprWithCleanups>(e));
2582 // The desired result type, if it differs from the type of the
2583 // ultimate opaque expression.
2584 llvm::Type *resultType = nullptr;
2587 e = e->IgnoreParens();
2589 // There's a break at the end of this if-chain; anything
2590 // that wants to keep looping has to explicitly continue.
2591 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2592 switch (ce->getCastKind()) {
2593 // No-op casts don't change the type, so we just ignore them.
2595 e = ce->getSubExpr();
2598 case CK_LValueToRValue: {
2599 TryEmitResult loadResult
2600 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2602 llvm::Value *value = loadResult.getPointer();
2603 value = CGF.Builder.CreateBitCast(value, resultType);
2604 loadResult.setPointer(value);
2609 // These casts can change the type, so remember that and
2610 // soldier on. We only need to remember the outermost such
2612 case CK_CPointerToObjCPointerCast:
2613 case CK_BlockPointerToObjCPointerCast:
2614 case CK_AnyPointerToBlockPointerCast:
2617 resultType = CGF.ConvertType(ce->getType());
2618 e = ce->getSubExpr();
2619 assert(e->getType()->hasPointerRepresentation());
2622 // For consumptions, just emit the subexpression and thus elide
2623 // the retain/release pair.
2624 case CK_ARCConsumeObject: {
2625 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2626 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2627 return TryEmitResult(result, true);
2630 // Block extends are net +0. Naively, we could just recurse on
2631 // the subexpression, but actually we need to ensure that the
2632 // value is copied as a block, so there's a little filter here.
2633 case CK_ARCExtendBlockObject: {
2634 llvm::Value *result; // will be a +0 value
2636 // If we can't safely assume the sub-expression will produce a
2637 // block-copied value, emit the sub-expression at +0.
2638 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2639 result = CGF.EmitScalarExpr(ce->getSubExpr());
2641 // Otherwise, try to emit the sub-expression at +1 recursively.
2643 TryEmitResult subresult
2644 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2645 result = subresult.getPointer();
2647 // If that produced a retained value, just use that,
2648 // possibly casting down.
2649 if (subresult.getInt()) {
2651 result = CGF.Builder.CreateBitCast(result, resultType);
2652 return TryEmitResult(result, true);
2655 // Otherwise it's +0.
2658 // Retain the object as a block, then cast down.
2659 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
2660 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2661 return TryEmitResult(result, true);
2664 // For reclaims, emit the subexpression as a retained call and
2665 // skip the consumption.
2666 case CK_ARCReclaimReturnedObject: {
2667 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2668 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2669 return TryEmitResult(result, true);
2676 // Skip __extension__.
2677 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2678 if (op->getOpcode() == UO_Extension) {
2679 e = op->getSubExpr();
2683 // For calls and message sends, use the retained-call logic.
2684 // Delegate inits are a special case in that they're the only
2685 // returns-retained expression that *isn't* surrounded by
2687 } else if (isa<CallExpr>(e) ||
2688 (isa<ObjCMessageExpr>(e) &&
2689 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2690 llvm::Value *result = emitARCRetainCall(CGF, e);
2691 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2692 return TryEmitResult(result, true);
2694 // Look through pseudo-object expressions.
2695 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2696 TryEmitResult result
2697 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2699 llvm::Value *value = result.getPointer();
2700 value = CGF.Builder.CreateBitCast(value, resultType);
2701 result.setPointer(value);
2706 // Conservatively halt the search at any other expression kind.
2710 // We didn't find an obvious production, so emit what we've got and
2711 // tell the caller that we didn't manage to retain.
2712 llvm::Value *result = CGF.EmitScalarExpr(e);
2713 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2714 return TryEmitResult(result, false);
2717 static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2720 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2721 llvm::Value *value = result.getPointer();
2722 if (!result.getInt())
2723 value = CGF.EmitARCRetain(type, value);
2727 /// EmitARCRetainScalarExpr - Semantically equivalent to
2728 /// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2729 /// best-effort attempt to peephole expressions that naturally produce
2730 /// retained objects.
2731 llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2732 // The retain needs to happen within the full-expression.
2733 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2734 enterFullExpression(cleanups);
2735 RunCleanupsScope scope(*this);
2736 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
2739 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2740 llvm::Value *value = result.getPointer();
2741 if (!result.getInt())
2742 value = EmitARCRetain(e->getType(), value);
2747 CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2748 // The retain needs to happen within the full-expression.
2749 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2750 enterFullExpression(cleanups);
2751 RunCleanupsScope scope(*this);
2752 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
2755 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2756 llvm::Value *value = result.getPointer();
2757 if (result.getInt())
2758 value = EmitARCAutorelease(value);
2760 value = EmitARCRetainAutorelease(e->getType(), value);
2764 llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2765 llvm::Value *result;
2768 if (shouldEmitSeparateBlockRetain(e)) {
2769 result = EmitScalarExpr(e);
2772 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2773 result = subresult.getPointer();
2774 doRetain = !subresult.getInt();
2778 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2779 return EmitObjCConsumeObject(e->getType(), result);
2782 llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2783 // In ARC, retain and autorelease the expression.
2784 if (getLangOpts().ObjCAutoRefCount) {
2785 // Do so before running any cleanups for the full-expression.
2786 // EmitARCRetainAutoreleaseScalarExpr does this for us.
2787 return EmitARCRetainAutoreleaseScalarExpr(expr);
2790 // Otherwise, use the normal scalar-expression emission. The
2791 // exception machinery doesn't do anything special with the
2792 // exception like retaining it, so there's no safety associated with
2793 // only running cleanups after the throw has started, and when it
2794 // matters it tends to be substantially inferior code.
2795 return EmitScalarExpr(expr);
2798 std::pair<LValue,llvm::Value*>
2799 CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2801 // Evaluate the RHS first.
2802 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2803 llvm::Value *value = result.getPointer();
2805 bool hasImmediateRetain = result.getInt();
2807 // If we didn't emit a retained object, and the l-value is of block
2808 // type, then we need to emit the block-retain immediately in case
2809 // it invalidates the l-value.
2810 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
2811 value = EmitARCRetainBlock(value, /*mandatory*/ false);
2812 hasImmediateRetain = true;
2815 LValue lvalue = EmitLValue(e->getLHS());
2817 // If the RHS was emitted retained, expand this.
2818 if (hasImmediateRetain) {
2819 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
2820 EmitStoreOfScalar(value, lvalue);
2821 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
2823 value = EmitARCStoreStrong(lvalue, value, ignored);
2826 return std::pair<LValue,llvm::Value*>(lvalue, value);
2829 std::pair<LValue,llvm::Value*>
2830 CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2831 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2832 LValue lvalue = EmitLValue(e->getLHS());
2834 EmitStoreOfScalar(value, lvalue);
2836 return std::pair<LValue,llvm::Value*>(lvalue, value);
2839 void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
2840 const ObjCAutoreleasePoolStmt &ARPS) {
2841 const Stmt *subStmt = ARPS.getSubStmt();
2842 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2844 CGDebugInfo *DI = getDebugInfo();
2846 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
2848 // Keep track of the current cleanup stack depth.
2849 RunCleanupsScope Scope(*this);
2850 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
2851 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2852 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2854 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2855 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2858 for (const auto *I : S.body())
2862 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
2865 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2866 /// make sure it survives garbage collection until this point.
2867 void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2868 // We just use an inline assembly.
2869 llvm::FunctionType *extenderType
2870 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
2871 llvm::Value *extender
2872 = llvm::InlineAsm::get(extenderType,
2874 /* constraints */ "r",
2875 /* side effects */ true);
2877 object = Builder.CreateBitCast(object, VoidPtrTy);
2878 EmitNounwindRuntimeCall(extender, object);
2881 /// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
2882 /// non-trivial copy assignment function, produce following helper function.
2883 /// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
2886 CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
2887 const ObjCPropertyImplDecl *PID) {
2888 if (!getLangOpts().CPlusPlus ||
2889 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
2891 QualType Ty = PID->getPropertyIvarDecl()->getType();
2892 if (!Ty->isRecordType())
2894 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2895 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
2897 llvm::Constant *HelperFn = nullptr;
2898 if (hasTrivialSetExpr(PID))
2900 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
2901 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
2904 ASTContext &C = getContext();
2906 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
2907 FunctionDecl *FD = FunctionDecl::Create(C,
2908 C.getTranslationUnitDecl(),
2910 SourceLocation(), II, C.VoidTy,
2915 QualType DestTy = C.getPointerType(Ty);
2916 QualType SrcTy = Ty;
2918 SrcTy = C.getPointerType(SrcTy);
2920 FunctionArgList args;
2921 ImplicitParamDecl dstDecl(getContext(), FD, SourceLocation(), nullptr,DestTy);
2922 args.push_back(&dstDecl);
2923 ImplicitParamDecl srcDecl(getContext(), FD, SourceLocation(), nullptr, SrcTy);
2924 args.push_back(&srcDecl);
2926 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2927 C.VoidTy, args, FunctionType::ExtInfo(), RequiredArgs::All);
2929 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
2931 llvm::Function *Fn =
2932 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2933 "__assign_helper_atomic_property_",
2936 StartFunction(FD, C.VoidTy, Fn, FI, args);
2938 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2939 VK_RValue, SourceLocation());
2940 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
2941 VK_LValue, OK_Ordinary, SourceLocation());
2943 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
2944 VK_RValue, SourceLocation());
2945 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2946 VK_LValue, OK_Ordinary, SourceLocation());
2948 Expr *Args[2] = { &DST, &SRC };
2949 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
2950 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
2951 Args, DestTy->getPointeeType(),
2952 VK_LValue, SourceLocation(), false);
2957 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2958 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
2963 CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
2964 const ObjCPropertyImplDecl *PID) {
2965 if (!getLangOpts().CPlusPlus ||
2966 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
2968 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2969 QualType Ty = PD->getType();
2970 if (!Ty->isRecordType())
2972 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
2974 llvm::Constant *HelperFn = nullptr;
2976 if (hasTrivialGetExpr(PID))
2978 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
2979 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
2983 ASTContext &C = getContext();
2985 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2986 FunctionDecl *FD = FunctionDecl::Create(C,
2987 C.getTranslationUnitDecl(),
2989 SourceLocation(), II, C.VoidTy,
2994 QualType DestTy = C.getPointerType(Ty);
2995 QualType SrcTy = Ty;
2997 SrcTy = C.getPointerType(SrcTy);
2999 FunctionArgList args;
3000 ImplicitParamDecl dstDecl(getContext(), FD, SourceLocation(), nullptr,DestTy);
3001 args.push_back(&dstDecl);
3002 ImplicitParamDecl srcDecl(getContext(), FD, SourceLocation(), nullptr, SrcTy);
3003 args.push_back(&srcDecl);
3005 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
3006 C.VoidTy, args, FunctionType::ExtInfo(), RequiredArgs::All);
3008 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
3010 llvm::Function *Fn =
3011 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
3012 "__copy_helper_atomic_property_", &CGM.getModule());
3014 StartFunction(FD, C.VoidTy, Fn, FI, args);
3016 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
3017 VK_RValue, SourceLocation());
3019 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
3020 VK_LValue, OK_Ordinary, SourceLocation());
3022 CXXConstructExpr *CXXConstExpr =
3023 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
3025 SmallVector<Expr*, 4> ConstructorArgs;
3026 ConstructorArgs.push_back(&SRC);
3027 ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
3028 CXXConstExpr->arg_end());
3030 CXXConstructExpr *TheCXXConstructExpr =
3031 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3032 CXXConstExpr->getConstructor(),
3033 CXXConstExpr->isElidable(),
3035 CXXConstExpr->hadMultipleCandidates(),
3036 CXXConstExpr->isListInitialization(),
3037 CXXConstExpr->isStdInitListInitialization(),
3038 CXXConstExpr->requiresZeroInitialization(),
3039 CXXConstExpr->getConstructionKind(),
3042 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
3043 VK_RValue, SourceLocation());
3045 RValue DV = EmitAnyExpr(&DstExpr);
3047 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
3048 EmitAggExpr(TheCXXConstructExpr,
3049 AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(),
3050 AggValueSlot::IsDestructed,
3051 AggValueSlot::DoesNotNeedGCBarriers,
3052 AggValueSlot::IsNotAliased));
3055 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3056 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3061 CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3062 // Get selectors for retain/autorelease.
3063 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3064 Selector CopySelector =
3065 getContext().Selectors.getNullarySelector(CopyID);
3066 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3067 Selector AutoreleaseSelector =
3068 getContext().Selectors.getNullarySelector(AutoreleaseID);
3070 // Emit calls to retain/autorelease.
3071 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3072 llvm::Value *Val = Block;
3074 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3076 Val, CallArgList(), nullptr, nullptr);
3077 Val = Result.getScalarVal();
3078 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3079 Ty, AutoreleaseSelector,
3080 Val, CallArgList(), nullptr, nullptr);
3081 Val = Result.getScalarVal();
3086 CGObjCRuntime::~CGObjCRuntime() {}