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 "llvm/ADT/STLExtras.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/InlineAsm.h"
26 using namespace clang;
27 using namespace CodeGen;
29 typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
31 tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
33 /// Given the address of a variable of pointer type, find the correct
34 /// null to store into it.
35 static llvm::Constant *getNullForVariable(llvm::Value *addr) {
36 const llvm::Type *type =
37 cast<llvm::PointerType>(addr->getType())->getElementType();
38 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
41 /// Emits an instance of NSConstantString representing the object.
42 llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
45 CGM.getObjCRuntime().GenerateConstantString(E->getString());
46 // FIXME: This bitcast should just be made an invariant on the Runtime.
47 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
51 llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
53 // Note that this implementation allows for non-constant strings to be passed
54 // as arguments to @selector(). Currently, the only thing preventing this
55 // behaviour is the type checking in the front end.
56 return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
59 llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
60 // FIXME: This should pass the Decl not the name.
61 return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
64 /// \brief Adjust the type of the result of an Objective-C message send
65 /// expression when the method has a related result type.
66 static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
68 const ObjCMethodDecl *Method,
73 if (!Method->hasRelatedResultType() ||
74 CGF.getContext().hasSameType(E->getType(), Method->getResultType()) ||
78 // We have applied a related result type. Cast the rvalue appropriately.
79 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
80 CGF.ConvertType(E->getType())));
83 RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
84 ReturnValueSlot Return) {
85 // Only the lookup mechanism and first two arguments of the method
86 // implementation vary between runtimes. We can get the receiver and
87 // arguments in generic code.
89 bool isDelegateInit = E->isDelegateInitCall();
91 // We don't retain the receiver in delegate init calls, and this is
92 // safe because the receiver value is always loaded from 'self',
93 // which we zero out. We don't want to Block_copy block receivers,
97 CGM.getLangOptions().ObjCAutoRefCount &&
99 E->getMethodDecl()->hasAttr<NSConsumesSelfAttr>());
101 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
102 bool isSuperMessage = false;
103 bool isClassMessage = false;
104 ObjCInterfaceDecl *OID = 0;
106 QualType ReceiverType;
107 llvm::Value *Receiver = 0;
108 switch (E->getReceiverKind()) {
109 case ObjCMessageExpr::Instance:
110 ReceiverType = E->getInstanceReceiver()->getType();
112 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
113 E->getInstanceReceiver());
114 Receiver = ter.getPointer();
116 Receiver = EmitARCRetainNonBlock(Receiver);
118 Receiver = EmitScalarExpr(E->getInstanceReceiver());
121 case ObjCMessageExpr::Class: {
122 ReceiverType = E->getClassReceiver();
123 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
124 assert(ObjTy && "Invalid Objective-C class message send");
125 OID = ObjTy->getInterface();
126 assert(OID && "Invalid Objective-C class message send");
127 Receiver = Runtime.GetClass(Builder, OID);
128 isClassMessage = true;
131 Receiver = EmitARCRetainNonBlock(Receiver);
135 case ObjCMessageExpr::SuperInstance:
136 ReceiverType = E->getSuperType();
137 Receiver = LoadObjCSelf();
138 isSuperMessage = true;
141 Receiver = EmitARCRetainNonBlock(Receiver);
144 case ObjCMessageExpr::SuperClass:
145 ReceiverType = E->getSuperType();
146 Receiver = LoadObjCSelf();
147 isSuperMessage = true;
148 isClassMessage = true;
151 Receiver = EmitARCRetainNonBlock(Receiver);
155 QualType ResultType =
156 E->getMethodDecl() ? E->getMethodDecl()->getResultType() : E->getType();
159 EmitCallArgs(Args, E->getMethodDecl(), E->arg_begin(), E->arg_end());
161 // For delegate init calls in ARC, do an unsafe store of null into
162 // self. This represents the call taking direct ownership of that
163 // value. We have to do this after emitting the other call
164 // arguments because they might also reference self, but we don't
165 // have to worry about any of them modifying self because that would
166 // be an undefined read and write of an object in unordered
168 if (isDelegateInit) {
169 assert(getLangOptions().ObjCAutoRefCount &&
170 "delegate init calls should only be marked in ARC");
172 // Do an unsafe store of null into self.
173 llvm::Value *selfAddr =
174 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
175 assert(selfAddr && "no self entry for a delegate init call?");
177 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
181 if (isSuperMessage) {
182 // super is only valid in an Objective-C method
183 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
184 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
185 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
187 OMD->getClassInterface(),
194 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
200 // For delegate init calls in ARC, implicitly store the result of
201 // the call back into self. This takes ownership of the value.
202 if (isDelegateInit) {
203 llvm::Value *selfAddr =
204 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
205 llvm::Value *newSelf = result.getScalarVal();
207 // The delegate return type isn't necessarily a matching type; in
208 // fact, it's quite likely to be 'id'.
209 const llvm::Type *selfTy =
210 cast<llvm::PointerType>(selfAddr->getType())->getElementType();
211 newSelf = Builder.CreateBitCast(newSelf, selfTy);
213 Builder.CreateStore(newSelf, selfAddr);
216 return AdjustRelatedResultType(*this, E, E->getMethodDecl(), result);
220 struct FinishARCDealloc : EHScopeStack::Cleanup {
221 void Emit(CodeGenFunction &CGF, Flags flags) {
222 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
224 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
225 const ObjCInterfaceDecl *iface = impl->getClassInterface();
226 if (!iface->getSuperClass()) return;
228 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
230 // Call [super dealloc] if we have a superclass.
231 llvm::Value *self = CGF.LoadObjCSelf();
234 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
235 CGF.getContext().VoidTy,
236 method->getSelector(),
240 /*is class msg*/ false,
247 /// StartObjCMethod - Begin emission of an ObjCMethod. This generates
248 /// the LLVM function and sets the other context used by
250 void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
251 const ObjCContainerDecl *CD,
252 SourceLocation StartLoc) {
253 FunctionArgList args;
254 // Check if we should generate debug info for this method.
255 if (CGM.getModuleDebugInfo() && !OMD->hasAttr<NoDebugAttr>())
256 DebugInfo = CGM.getModuleDebugInfo();
258 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
260 const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(OMD);
261 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
263 args.push_back(OMD->getSelfDecl());
264 args.push_back(OMD->getCmdDecl());
266 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
267 E = OMD->param_end(); PI != E; ++PI)
272 StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc);
274 // In ARC, certain methods get an extra cleanup.
275 if (CGM.getLangOptions().ObjCAutoRefCount &&
276 OMD->isInstanceMethod() &&
277 OMD->getSelector().isUnarySelector()) {
278 const IdentifierInfo *ident =
279 OMD->getSelector().getIdentifierInfoForSlot(0);
280 if (ident->isStr("dealloc"))
281 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
285 static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
286 LValue lvalue, QualType type);
288 void CodeGenFunction::GenerateObjCGetterBody(ObjCIvarDecl *Ivar,
289 bool IsAtomic, bool IsStrong) {
290 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
292 llvm::Value *GetCopyStructFn =
293 CGM.getObjCRuntime().GetGetStructFunction();
294 CodeGenTypes &Types = CGM.getTypes();
295 // objc_copyStruct (ReturnValue, &structIvar,
296 // sizeof (Type of Ivar), isAtomic, false);
298 RValue RV = RValue::get(Builder.CreateBitCast(ReturnValue, VoidPtrTy));
299 Args.add(RV, getContext().VoidPtrTy);
300 RV = RValue::get(Builder.CreateBitCast(LV.getAddress(), VoidPtrTy));
301 Args.add(RV, getContext().VoidPtrTy);
302 // sizeof (Type of Ivar)
303 CharUnits Size = getContext().getTypeSizeInChars(Ivar->getType());
304 llvm::Value *SizeVal =
305 llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy),
307 Args.add(RValue::get(SizeVal), getContext().LongTy);
308 llvm::Value *isAtomic =
309 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy),
311 Args.add(RValue::get(isAtomic), getContext().BoolTy);
312 llvm::Value *hasStrong =
313 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy),
315 Args.add(RValue::get(hasStrong), getContext().BoolTy);
316 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
317 FunctionType::ExtInfo()),
318 GetCopyStructFn, ReturnValueSlot(), Args);
321 /// Generate an Objective-C method. An Objective-C method is a C function with
322 /// its pointer, name, and types registered in the class struture.
323 void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
324 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
325 EmitStmt(OMD->getBody());
326 FinishFunction(OMD->getBodyRBrace());
329 // FIXME: I wasn't sure about the synthesis approach. If we end up generating an
330 // AST for the whole body we can just fall back to having a GenerateFunction
331 // which takes the body Stmt.
333 /// GenerateObjCGetter - Generate an Objective-C property getter
334 /// function. The given Decl must be an ObjCImplementationDecl. @synthesize
335 /// is illegal within a category.
336 void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
337 const ObjCPropertyImplDecl *PID) {
338 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
339 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
341 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
342 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
343 assert(OMD && "Invalid call to generate getter (empty method)");
344 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
346 // Determine if we should use an objc_getProperty call for
347 // this. Non-atomic properties are directly evaluated.
348 // atomic 'copy' and 'retain' properties are also directly
349 // evaluated in gc-only mode.
350 if (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
352 (PD->getSetterKind() == ObjCPropertyDecl::Copy ||
353 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
354 llvm::Value *GetPropertyFn =
355 CGM.getObjCRuntime().GetPropertyGetFunction();
357 if (!GetPropertyFn) {
358 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
363 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
364 // FIXME: Can't this be simpler? This might even be worse than the
365 // corresponding gcc code.
366 CodeGenTypes &Types = CGM.getTypes();
367 ValueDecl *Cmd = OMD->getCmdDecl();
368 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
369 QualType IdTy = getContext().getObjCIdType();
370 llvm::Value *SelfAsId =
371 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
372 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
374 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
376 Args.add(RValue::get(SelfAsId), IdTy);
377 Args.add(RValue::get(CmdVal), Cmd->getType());
378 Args.add(RValue::get(Offset), getContext().getPointerDiffType());
379 Args.add(RValue::get(True), getContext().BoolTy);
380 // FIXME: We shouldn't need to get the function info here, the
381 // runtime already should have computed it to build the function.
382 RValue RV = EmitCall(Types.getFunctionInfo(PD->getType(), Args,
383 FunctionType::ExtInfo()),
384 GetPropertyFn, ReturnValueSlot(), Args);
385 // We need to fix the type here. Ivars with copy & retain are
386 // always objects so we don't need to worry about complex or
388 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
389 Types.ConvertType(PD->getType())));
390 EmitReturnOfRValue(RV, PD->getType());
392 // objc_getProperty does an autorelease, so we should suppress ours.
393 AutoreleaseResult = false;
395 const llvm::Triple &Triple = getContext().Target.getTriple();
396 QualType IVART = Ivar->getType();
398 IVART->isScalarType() &&
399 (Triple.getArch() == llvm::Triple::arm ||
400 Triple.getArch() == llvm::Triple::thumb) &&
401 (getContext().getTypeSizeInChars(IVART)
402 > CharUnits::fromQuantity(4)) &&
403 CGM.getObjCRuntime().GetGetStructFunction()) {
404 GenerateObjCGetterBody(Ivar, true, false);
407 (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
408 Triple.getArch() == llvm::Triple::x86 &&
409 (getContext().getTypeSizeInChars(IVART)
410 > CharUnits::fromQuantity(4)) &&
411 CGM.getObjCRuntime().GetGetStructFunction()) {
412 GenerateObjCGetterBody(Ivar, true, false);
415 (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
416 Triple.getArch() == llvm::Triple::x86_64 &&
417 (getContext().getTypeSizeInChars(IVART)
418 > CharUnits::fromQuantity(8)) &&
419 CGM.getObjCRuntime().GetGetStructFunction()) {
420 GenerateObjCGetterBody(Ivar, true, false);
422 else if (IVART->isAnyComplexType()) {
423 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
425 ComplexPairTy Pair = LoadComplexFromAddr(LV.getAddress(),
426 LV.isVolatileQualified());
427 StoreComplexToAddr(Pair, ReturnValue, LV.isVolatileQualified());
429 else if (hasAggregateLLVMType(IVART)) {
430 bool IsStrong = false;
431 if ((IsStrong = IvarTypeWithAggrGCObjects(IVART))
432 && CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect
433 && CGM.getObjCRuntime().GetGetStructFunction()) {
434 GenerateObjCGetterBody(Ivar, IsAtomic, IsStrong);
437 const CXXRecordDecl *classDecl = IVART->getAsCXXRecordDecl();
439 if (PID->getGetterCXXConstructor() &&
440 classDecl && !classDecl->hasTrivialDefaultConstructor()) {
442 new (getContext()) ReturnStmt(SourceLocation(),
443 PID->getGetterCXXConstructor(),
445 EmitReturnStmt(*Stmt);
446 } else if (IsAtomic &&
447 !IVART->isAnyComplexType() &&
448 Triple.getArch() == llvm::Triple::x86 &&
449 (getContext().getTypeSizeInChars(IVART)
450 > CharUnits::fromQuantity(4)) &&
451 CGM.getObjCRuntime().GetGetStructFunction()) {
452 GenerateObjCGetterBody(Ivar, true, false);
455 !IVART->isAnyComplexType() &&
456 Triple.getArch() == llvm::Triple::x86_64 &&
457 (getContext().getTypeSizeInChars(IVART)
458 > CharUnits::fromQuantity(8)) &&
459 CGM.getObjCRuntime().GetGetStructFunction()) {
460 GenerateObjCGetterBody(Ivar, true, false);
463 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
465 EmitAggregateCopy(ReturnValue, LV.getAddress(), IVART);
470 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
472 QualType propType = PD->getType();
475 if (propType->isReferenceType()) {
476 value = LV.getAddress();
478 // In ARC, we want to emit this retained.
479 if (getLangOptions().ObjCAutoRefCount &&
480 PD->getType()->isObjCRetainableType())
481 value = emitARCRetainLoadOfScalar(*this, LV, IVART);
483 value = EmitLoadOfLValue(LV).getScalarVal();
485 value = Builder.CreateBitCast(value, ConvertType(propType));
488 EmitReturnOfRValue(RValue::get(value), propType);
495 void CodeGenFunction::GenerateObjCAtomicSetterBody(ObjCMethodDecl *OMD,
496 ObjCIvarDecl *Ivar) {
497 // objc_copyStruct (&structIvar, &Arg,
498 // sizeof (struct something), true, false);
499 llvm::Value *GetCopyStructFn =
500 CGM.getObjCRuntime().GetSetStructFunction();
501 CodeGenTypes &Types = CGM.getTypes();
503 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), Ivar, 0);
505 RValue::get(Builder.CreateBitCast(LV.getAddress(),
506 Types.ConvertType(getContext().VoidPtrTy)));
507 Args.add(RV, getContext().VoidPtrTy);
508 llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
509 llvm::Value *ArgAsPtrTy =
510 Builder.CreateBitCast(Arg,
511 Types.ConvertType(getContext().VoidPtrTy));
512 RV = RValue::get(ArgAsPtrTy);
513 Args.add(RV, getContext().VoidPtrTy);
514 // sizeof (Type of Ivar)
515 CharUnits Size = getContext().getTypeSizeInChars(Ivar->getType());
516 llvm::Value *SizeVal =
517 llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy),
519 Args.add(RValue::get(SizeVal), getContext().LongTy);
521 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
522 Args.add(RValue::get(True), getContext().BoolTy);
524 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
525 Args.add(RValue::get(False), getContext().BoolTy);
526 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
527 FunctionType::ExtInfo()),
528 GetCopyStructFn, ReturnValueSlot(), Args);
532 IvarAssignHasTrvialAssignment(const ObjCPropertyImplDecl *PID,
534 bool HasTrvialAssignment = true;
535 if (PID->getSetterCXXAssignment()) {
536 const CXXRecordDecl *classDecl = IvarT->getAsCXXRecordDecl();
537 HasTrvialAssignment =
538 (!classDecl || classDecl->hasTrivialCopyAssignment());
540 return HasTrvialAssignment;
543 /// GenerateObjCSetter - Generate an Objective-C property setter
544 /// function. The given Decl must be an ObjCImplementationDecl. @synthesize
545 /// is illegal within a category.
546 void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
547 const ObjCPropertyImplDecl *PID) {
548 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
549 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
550 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
551 assert(OMD && "Invalid call to generate setter (empty method)");
552 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
553 const llvm::Triple &Triple = getContext().Target.getTriple();
554 QualType IVART = Ivar->getType();
555 bool IsCopy = PD->getSetterKind() == ObjCPropertyDecl::Copy;
557 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
559 // Determine if we should use an objc_setProperty call for
560 // this. Properties with 'copy' semantics always use it, as do
561 // non-atomic properties with 'release' semantics as long as we are
562 // not in gc-only mode.
564 (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
565 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
566 llvm::Value *SetPropertyFn =
567 CGM.getObjCRuntime().GetPropertySetFunction();
569 if (!SetPropertyFn) {
570 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
575 // Emit objc_setProperty((id) self, _cmd, offset, arg,
576 // <is-atomic>, <is-copy>).
577 // FIXME: Can't this be simpler? This might even be worse than the
578 // corresponding gcc code.
579 CodeGenTypes &Types = CGM.getTypes();
580 ValueDecl *Cmd = OMD->getCmdDecl();
581 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
582 QualType IdTy = getContext().getObjCIdType();
583 llvm::Value *SelfAsId =
584 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
585 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
586 llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
587 llvm::Value *ArgAsId =
588 Builder.CreateBitCast(Builder.CreateLoad(Arg, "arg"),
589 Types.ConvertType(IdTy));
591 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
593 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
595 Args.add(RValue::get(SelfAsId), IdTy);
596 Args.add(RValue::get(CmdVal), Cmd->getType());
597 Args.add(RValue::get(Offset), getContext().getPointerDiffType());
598 Args.add(RValue::get(ArgAsId), IdTy);
599 Args.add(RValue::get(IsAtomic ? True : False), getContext().BoolTy);
600 Args.add(RValue::get(IsCopy ? True : False), getContext().BoolTy);
601 // FIXME: We shouldn't need to get the function info here, the runtime
602 // already should have computed it to build the function.
603 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
604 FunctionType::ExtInfo()),
606 ReturnValueSlot(), Args);
607 } else if (IsAtomic && hasAggregateLLVMType(IVART) &&
608 !IVART->isAnyComplexType() &&
609 IvarAssignHasTrvialAssignment(PID, IVART) &&
610 ((Triple.getArch() == llvm::Triple::x86 &&
611 (getContext().getTypeSizeInChars(IVART)
612 > CharUnits::fromQuantity(4))) ||
613 (Triple.getArch() == llvm::Triple::x86_64 &&
614 (getContext().getTypeSizeInChars(IVART)
615 > CharUnits::fromQuantity(8))))
616 && CGM.getObjCRuntime().GetSetStructFunction()) {
617 // objc_copyStruct (&structIvar, &Arg,
618 // sizeof (struct something), true, false);
619 GenerateObjCAtomicSetterBody(OMD, Ivar);
620 } else if (PID->getSetterCXXAssignment()) {
621 EmitIgnoredExpr(PID->getSetterCXXAssignment());
624 IVART->isScalarType() &&
625 (Triple.getArch() == llvm::Triple::arm ||
626 Triple.getArch() == llvm::Triple::thumb) &&
627 (getContext().getTypeSizeInChars(IVART)
628 > CharUnits::fromQuantity(4)) &&
629 CGM.getObjCRuntime().GetGetStructFunction()) {
630 GenerateObjCAtomicSetterBody(OMD, Ivar);
633 (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
634 Triple.getArch() == llvm::Triple::x86 &&
635 (getContext().getTypeSizeInChars(IVART)
636 > CharUnits::fromQuantity(4)) &&
637 CGM.getObjCRuntime().GetGetStructFunction()) {
638 GenerateObjCAtomicSetterBody(OMD, Ivar);
641 (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
642 Triple.getArch() == llvm::Triple::x86_64 &&
643 (getContext().getTypeSizeInChars(IVART)
644 > CharUnits::fromQuantity(8)) &&
645 CGM.getObjCRuntime().GetGetStructFunction()) {
646 GenerateObjCAtomicSetterBody(OMD, Ivar);
649 // FIXME: Find a clean way to avoid AST node creation.
650 SourceLocation Loc = PID->getLocStart();
651 ValueDecl *Self = OMD->getSelfDecl();
652 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
653 DeclRefExpr Base(Self, Self->getType(), VK_RValue, Loc);
654 ParmVarDecl *ArgDecl = *OMD->param_begin();
655 QualType T = ArgDecl->getType();
656 if (T->isReferenceType())
657 T = cast<ReferenceType>(T)->getPointeeType();
658 DeclRefExpr Arg(ArgDecl, T, VK_LValue, Loc);
659 ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base, true, true);
661 // The property type can differ from the ivar type in some situations with
662 // Objective-C pointer types, we can always bit cast the RHS in these cases.
663 if (getContext().getCanonicalType(Ivar->getType()) !=
664 getContext().getCanonicalType(ArgDecl->getType())) {
665 ImplicitCastExpr ArgCasted(ImplicitCastExpr::OnStack,
666 Ivar->getType(), CK_BitCast, &Arg,
668 BinaryOperator Assign(&IvarRef, &ArgCasted, BO_Assign,
669 Ivar->getType(), VK_RValue, OK_Ordinary, Loc);
672 BinaryOperator Assign(&IvarRef, &Arg, BO_Assign,
673 Ivar->getType(), VK_RValue, OK_Ordinary, Loc);
683 struct DestroyIvar : EHScopeStack::Cleanup {
686 const ObjCIvarDecl *ivar;
687 CodeGenFunction::Destroyer &destroyer;
688 bool useEHCleanupForArray;
690 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
691 CodeGenFunction::Destroyer *destroyer,
692 bool useEHCleanupForArray)
693 : addr(addr), ivar(ivar), destroyer(*destroyer),
694 useEHCleanupForArray(useEHCleanupForArray) {}
696 void Emit(CodeGenFunction &CGF, Flags flags) {
698 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
699 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
700 flags.isForNormalCleanup() && useEHCleanupForArray);
705 /// Like CodeGenFunction::destroyARCStrong, but do it with a call.
706 static void destroyARCStrongWithStore(CodeGenFunction &CGF,
709 llvm::Value *null = getNullForVariable(addr);
710 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
713 static void emitCXXDestructMethod(CodeGenFunction &CGF,
714 ObjCImplementationDecl *impl) {
715 CodeGenFunction::RunCleanupsScope scope(CGF);
717 llvm::Value *self = CGF.LoadObjCSelf();
719 ObjCInterfaceDecl *iface
720 = const_cast<ObjCInterfaceDecl*>(impl->getClassInterface());
721 for (ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
722 ivar; ivar = ivar->getNextIvar()) {
723 QualType type = ivar->getType();
725 // Check whether the ivar is a destructible type.
726 QualType::DestructionKind dtorKind = type.isDestructedType();
727 if (!dtorKind) continue;
729 CodeGenFunction::Destroyer *destroyer = 0;
731 // Use a call to objc_storeStrong to destroy strong ivars, for the
732 // general benefit of the tools.
733 if (dtorKind == QualType::DK_objc_strong_lifetime) {
734 destroyer = &destroyARCStrongWithStore;
736 // Otherwise use the default for the destruction kind.
738 destroyer = &CGF.getDestroyer(dtorKind);
741 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
743 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
744 cleanupKind & EHCleanup);
747 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
750 void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
753 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
754 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
756 // Emit .cxx_construct.
758 // Suppress the final autorelease in ARC.
759 AutoreleaseResult = false;
761 llvm::SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
762 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
763 E = IMP->init_end(); B != E; ++B) {
764 CXXCtorInitializer *IvarInit = (*B);
765 FieldDecl *Field = IvarInit->getAnyMember();
766 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
767 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
768 LoadObjCSelf(), Ivar, 0);
769 EmitAggExpr(IvarInit->getInit(), AggValueSlot::forLValue(LV, true));
771 // constructor returns 'self'.
772 CodeGenTypes &Types = CGM.getTypes();
773 QualType IdTy(CGM.getContext().getObjCIdType());
774 llvm::Value *SelfAsId =
775 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
776 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
778 // Emit .cxx_destruct.
780 emitCXXDestructMethod(*this, IMP);
785 bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
786 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
788 const ABIArgInfo &AI = it->info;
789 // FIXME. Is this sufficient check?
790 return (AI.getKind() == ABIArgInfo::Indirect);
793 bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
794 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
796 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
797 return FDTTy->getDecl()->hasObjectMember();
801 llvm::Value *CodeGenFunction::LoadObjCSelf() {
802 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
803 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
806 QualType CodeGenFunction::TypeOfSelfObject() {
807 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
808 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
809 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
810 getContext().getCanonicalType(selfDecl->getType()));
811 return PTy->getPointeeType();
815 CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
816 // This is a special l-value that just issues sends when we load or
819 // For certain base kinds, we need to emit the base immediately.
821 if (E->isSuperReceiver())
822 Base = LoadObjCSelf();
823 else if (E->isClassReceiver())
824 Base = CGM.getObjCRuntime().GetClass(Builder, E->getClassReceiver());
826 Base = EmitScalarExpr(E->getBase());
827 return LValue::MakePropertyRef(E, Base);
830 static RValue GenerateMessageSendSuper(CodeGenFunction &CGF,
831 ReturnValueSlot Return,
834 llvm::Value *Receiver,
835 const CallArgList &CallArgs) {
836 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CGF.CurFuncDecl);
837 bool isClassMessage = OMD->isClassMethod();
838 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
839 return CGF.CGM.getObjCRuntime()
840 .GenerateMessageSendSuper(CGF, Return, ResultType,
841 S, OMD->getClassInterface(),
842 isCategoryImpl, Receiver,
843 isClassMessage, CallArgs);
846 RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
847 ReturnValueSlot Return) {
848 const ObjCPropertyRefExpr *E = LV.getPropertyRefExpr();
849 QualType ResultType = E->getGetterResultType();
851 const ObjCMethodDecl *method;
852 if (E->isExplicitProperty()) {
853 const ObjCPropertyDecl *Property = E->getExplicitProperty();
854 S = Property->getGetterName();
855 method = Property->getGetterMethodDecl();
857 method = E->getImplicitPropertyGetter();
858 S = method->getSelector();
861 llvm::Value *Receiver = LV.getPropertyRefBaseAddr();
863 if (CGM.getLangOptions().ObjCAutoRefCount) {
864 QualType receiverType;
865 if (E->isSuperReceiver())
866 receiverType = E->getSuperReceiverType();
867 else if (E->isClassReceiver())
868 receiverType = getContext().getObjCClassType();
870 receiverType = E->getBase()->getType();
873 // Accesses to 'super' follow a different code path.
874 if (E->isSuperReceiver())
875 return AdjustRelatedResultType(*this, E, method,
876 GenerateMessageSendSuper(*this, Return,
880 const ObjCInterfaceDecl *ReceiverClass
881 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
882 return AdjustRelatedResultType(*this, E, method,
883 CGM.getObjCRuntime().
884 GenerateMessageSend(*this, Return, ResultType, S,
885 Receiver, CallArgList(), ReceiverClass));
888 void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
890 const ObjCPropertyRefExpr *E = Dst.getPropertyRefExpr();
891 Selector S = E->getSetterSelector();
892 QualType ArgType = E->getSetterArgType();
894 // FIXME. Other than scalars, AST is not adequate for setter and
895 // getter type mismatches which require conversion.
896 if (Src.isScalar()) {
897 llvm::Value *SrcVal = Src.getScalarVal();
898 QualType DstType = getContext().getCanonicalType(ArgType);
899 const llvm::Type *DstTy = ConvertType(DstType);
900 if (SrcVal->getType() != DstTy)
902 RValue::get(EmitScalarConversion(SrcVal, E->getType(), DstType));
906 Args.add(Src, ArgType);
908 llvm::Value *Receiver = Dst.getPropertyRefBaseAddr();
909 QualType ResultType = getContext().VoidTy;
911 if (E->isSuperReceiver()) {
912 GenerateMessageSendSuper(*this, ReturnValueSlot(),
913 ResultType, S, Receiver, Args);
917 const ObjCInterfaceDecl *ReceiverClass
918 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
920 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
921 ResultType, S, Receiver, Args,
925 void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
926 llvm::Constant *EnumerationMutationFn =
927 CGM.getObjCRuntime().EnumerationMutationFunction();
929 if (!EnumerationMutationFn) {
930 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
934 CGDebugInfo *DI = getDebugInfo();
936 DI->setLocation(S.getSourceRange().getBegin());
937 DI->EmitRegionStart(Builder);
940 // The local variable comes into scope immediately.
941 AutoVarEmission variable = AutoVarEmission::invalid();
942 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
943 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
945 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
946 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
948 // Fast enumeration state.
949 QualType StateTy = getContext().getObjCFastEnumerationStateType();
950 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
951 EmitNullInitialization(StatePtr, StateTy);
953 // Number of elements in the items array.
954 static const unsigned NumItems = 16;
956 // Fetch the countByEnumeratingWithState:objects:count: selector.
957 IdentifierInfo *II[] = {
958 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
959 &CGM.getContext().Idents.get("objects"),
960 &CGM.getContext().Idents.get("count")
962 Selector FastEnumSel =
963 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
966 getContext().getConstantArrayType(getContext().getObjCIdType(),
967 llvm::APInt(32, NumItems),
968 ArrayType::Normal, 0);
969 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
971 // Emit the collection pointer.
972 llvm::Value *Collection = EmitScalarExpr(S.getCollection());
974 // Send it our message:
977 // The first argument is a temporary of the enumeration-state type.
978 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
980 // The second argument is a temporary array with space for NumItems
981 // pointers. We'll actually be loading elements from the array
982 // pointer written into the control state; this buffer is so that
983 // collections that *aren't* backed by arrays can still queue up
984 // batches of elements.
985 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
987 // The third argument is the capacity of that temporary array.
988 const llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
989 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
990 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
992 // Start the enumeration.
994 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
995 getContext().UnsignedLongTy,
999 // The initial number of objects that were returned in the buffer.
1000 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
1002 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1003 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
1005 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
1007 // If the limit pointer was zero to begin with, the collection is
1008 // empty; skip all this.
1009 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1010 EmptyBB, LoopInitBB);
1012 // Otherwise, initialize the loop.
1013 EmitBlock(LoopInitBB);
1015 // Save the initial mutations value. This is the value at an
1016 // address that was written into the state object by
1017 // countByEnumeratingWithState:objects:count:.
1018 llvm::Value *StateMutationsPtrPtr =
1019 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
1020 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
1023 llvm::Value *initialMutations =
1024 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
1026 // Start looping. This is the point we return to whenever we have a
1027 // fresh, non-empty batch of objects.
1028 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1029 EmitBlock(LoopBodyBB);
1031 // The current index into the buffer.
1032 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
1033 index->addIncoming(zero, LoopInitBB);
1035 // The current buffer size.
1036 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
1037 count->addIncoming(initialBufferLimit, LoopInitBB);
1039 // Check whether the mutations value has changed from where it was
1040 // at start. StateMutationsPtr should actually be invariant between
1042 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
1043 llvm::Value *currentMutations
1044 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
1046 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
1047 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
1049 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1050 WasNotMutatedBB, WasMutatedBB);
1052 // If so, call the enumeration-mutation function.
1053 EmitBlock(WasMutatedBB);
1055 Builder.CreateBitCast(Collection,
1056 ConvertType(getContext().getObjCIdType()),
1059 Args2.add(RValue::get(V), getContext().getObjCIdType());
1060 // FIXME: We shouldn't need to get the function info here, the runtime already
1061 // should have computed it to build the function.
1062 EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2,
1063 FunctionType::ExtInfo()),
1064 EnumerationMutationFn, ReturnValueSlot(), Args2);
1066 // Otherwise, or if the mutation function returns, just continue.
1067 EmitBlock(WasNotMutatedBB);
1069 // Initialize the element variable.
1070 RunCleanupsScope elementVariableScope(*this);
1071 bool elementIsVariable;
1072 LValue elementLValue;
1073 QualType elementType;
1074 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
1075 // Initialize the variable, in case it's a __block variable or something.
1076 EmitAutoVarInit(variable);
1078 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
1079 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), D->getType(),
1080 VK_LValue, SourceLocation());
1081 elementLValue = EmitLValue(&tempDRE);
1082 elementType = D->getType();
1083 elementIsVariable = true;
1085 if (D->isARCPseudoStrong())
1086 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
1088 elementLValue = LValue(); // suppress warning
1089 elementType = cast<Expr>(S.getElement())->getType();
1090 elementIsVariable = false;
1092 const llvm::Type *convertedElementType = ConvertType(elementType);
1094 // Fetch the buffer out of the enumeration state.
1095 // TODO: this pointer should actually be invariant between
1096 // refreshes, which would help us do certain loop optimizations.
1097 llvm::Value *StateItemsPtr =
1098 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
1099 llvm::Value *EnumStateItems =
1100 Builder.CreateLoad(StateItemsPtr, "stateitems");
1102 // Fetch the value at the current index from the buffer.
1103 llvm::Value *CurrentItemPtr =
1104 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1105 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
1107 // Cast that value to the right type.
1108 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1111 // Make sure we have an l-value. Yes, this gets evaluated every
1112 // time through the loop.
1113 if (!elementIsVariable) {
1114 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
1115 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
1117 EmitScalarInit(CurrentItem, elementLValue);
1120 // If we do have an element variable, this assignment is the end of
1121 // its initialization.
1122 if (elementIsVariable)
1123 EmitAutoVarCleanups(variable);
1125 // Perform the loop body, setting up break and continue labels.
1126 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
1128 RunCleanupsScope Scope(*this);
1129 EmitStmt(S.getBody());
1131 BreakContinueStack.pop_back();
1133 // Destroy the element variable now.
1134 elementVariableScope.ForceCleanup();
1136 // Check whether there are more elements.
1137 EmitBlock(AfterBody.getBlock());
1139 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
1141 // First we check in the local buffer.
1142 llvm::Value *indexPlusOne
1143 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
1145 // If we haven't overrun the buffer yet, we can continue.
1146 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1147 LoopBodyBB, FetchMoreBB);
1149 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1150 count->addIncoming(count, AfterBody.getBlock());
1152 // Otherwise, we have to fetch more elements.
1153 EmitBlock(FetchMoreBB);
1156 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1157 getContext().UnsignedLongTy,
1161 // If we got a zero count, we're done.
1162 llvm::Value *refetchCount = CountRV.getScalarVal();
1164 // (note that the message send might split FetchMoreBB)
1165 index->addIncoming(zero, Builder.GetInsertBlock());
1166 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1168 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1169 EmptyBB, LoopBodyBB);
1171 // No more elements.
1174 if (!elementIsVariable) {
1175 // If the element was not a declaration, set it to be null.
1177 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1178 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
1179 EmitStoreThroughLValue(RValue::get(null), elementLValue);
1183 DI->setLocation(S.getSourceRange().getEnd());
1184 DI->EmitRegionEnd(Builder);
1187 EmitBlock(LoopEnd.getBlock());
1190 void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
1191 CGM.getObjCRuntime().EmitTryStmt(*this, S);
1194 void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
1195 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1198 void CodeGenFunction::EmitObjCAtSynchronizedStmt(
1199 const ObjCAtSynchronizedStmt &S) {
1200 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
1203 /// Produce the code for a CK_ObjCProduceObject. Just does a
1204 /// primitive retain.
1205 llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1206 llvm::Value *value) {
1207 return EmitARCRetain(type, value);
1211 struct CallObjCRelease : EHScopeStack::Cleanup {
1212 CallObjCRelease(QualType type, llvm::Value *ptr, llvm::Value *condition)
1213 : type(type), ptr(ptr), condition(condition) {}
1216 llvm::Value *condition;
1218 void Emit(CodeGenFunction &CGF, Flags flags) {
1219 llvm::Value *object;
1221 // If we're in a conditional branch, we had to stash away in an
1222 // alloca the pointer to be released.
1223 llvm::BasicBlock *cont = 0;
1225 llvm::BasicBlock *release = CGF.createBasicBlock("release.yes");
1226 cont = CGF.createBasicBlock("release.cont");
1228 llvm::Value *cond = CGF.Builder.CreateLoad(condition);
1229 CGF.Builder.CreateCondBr(cond, release, cont);
1230 CGF.EmitBlock(release);
1231 object = CGF.Builder.CreateLoad(ptr);
1236 CGF.EmitARCRelease(object, /*precise*/ true);
1238 if (cont) CGF.EmitBlock(cont);
1243 /// Produce the code for a CK_ObjCConsumeObject. Does a primitive
1244 /// release at the end of the full-expression.
1245 llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1246 llvm::Value *object) {
1247 // If we're in a conditional branch, we need to make the cleanup
1248 // conditional. FIXME: this really needs to be supported by the
1250 llvm::AllocaInst *cond;
1252 if (isInConditionalBranch()) {
1253 cond = CreateTempAlloca(Builder.getInt1Ty(), "release.cond");
1254 ptr = CreateTempAlloca(object->getType(), "release.value");
1256 // The alloca is false until we get here.
1257 // FIXME: er. doesn't this need to be set at the start of the condition?
1258 InitTempAlloca(cond, Builder.getFalse());
1260 // Then it turns true.
1261 Builder.CreateStore(Builder.getTrue(), cond);
1262 Builder.CreateStore(object, ptr);
1268 EHStack.pushCleanup<CallObjCRelease>(getARCCleanupKind(), type, ptr, cond);
1272 llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1273 llvm::Value *value) {
1274 return EmitARCRetainAutorelease(type, value);
1278 static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
1279 const llvm::FunctionType *type,
1280 llvm::StringRef fnName) {
1281 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1283 // In -fobjc-no-arc-runtime, emit weak references to the runtime
1285 if (!CGM.getCodeGenOpts().ObjCRuntimeHasARC)
1286 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
1287 f->setLinkage(llvm::Function::ExternalWeakLinkage);
1292 /// Perform an operation having the signature
1294 /// where a null input causes a no-op and returns null.
1295 static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1297 llvm::Constant *&fn,
1298 llvm::StringRef fnName) {
1299 if (isa<llvm::ConstantPointerNull>(value)) return value;
1302 std::vector<llvm::Type*> args(1, CGF.Int8PtrTy);
1303 const llvm::FunctionType *fnType =
1304 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1305 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1308 // Cast the argument to 'id'.
1309 const llvm::Type *origType = value->getType();
1310 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1312 // Call the function.
1313 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value);
1314 call->setDoesNotThrow();
1316 // Cast the result back to the original type.
1317 return CGF.Builder.CreateBitCast(call, origType);
1320 /// Perform an operation having the following signature:
1322 static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1324 llvm::Constant *&fn,
1325 llvm::StringRef fnName) {
1327 std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy);
1328 const llvm::FunctionType *fnType =
1329 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1330 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1333 // Cast the argument to 'id*'.
1334 const llvm::Type *origType = addr->getType();
1335 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1337 // Call the function.
1338 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr);
1339 call->setDoesNotThrow();
1341 // Cast the result back to a dereference of the original type.
1342 llvm::Value *result = call;
1343 if (origType != CGF.Int8PtrPtrTy)
1344 result = CGF.Builder.CreateBitCast(result,
1345 cast<llvm::PointerType>(origType)->getElementType());
1350 /// Perform an operation having the following signature:
1352 static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1355 llvm::Constant *&fn,
1356 llvm::StringRef fnName,
1358 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1359 == value->getType());
1362 std::vector<llvm::Type*> argTypes(2);
1363 argTypes[0] = CGF.Int8PtrPtrTy;
1364 argTypes[1] = CGF.Int8PtrTy;
1366 const llvm::FunctionType *fnType
1367 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1368 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1371 const llvm::Type *origType = value->getType();
1373 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1374 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1376 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value);
1377 result->setDoesNotThrow();
1379 if (ignored) return 0;
1381 return CGF.Builder.CreateBitCast(result, origType);
1384 /// Perform an operation having the following signature:
1385 /// void (i8**, i8**)
1386 static void emitARCCopyOperation(CodeGenFunction &CGF,
1389 llvm::Constant *&fn,
1390 llvm::StringRef fnName) {
1391 assert(dst->getType() == src->getType());
1394 std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy);
1395 const llvm::FunctionType *fnType
1396 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1397 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1400 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy);
1401 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy);
1403 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src);
1404 result->setDoesNotThrow();
1407 /// Produce the code to do a retain. Based on the type, calls one of:
1408 /// call i8* @objc_retain(i8* %value)
1409 /// call i8* @objc_retainBlock(i8* %value)
1410 llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1411 if (type->isBlockPointerType())
1412 return EmitARCRetainBlock(value);
1414 return EmitARCRetainNonBlock(value);
1417 /// Retain the given object, with normal retain semantics.
1418 /// call i8* @objc_retain(i8* %value)
1419 llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1420 return emitARCValueOperation(*this, value,
1421 CGM.getARCEntrypoints().objc_retain,
1425 /// Retain the given block, with _Block_copy semantics.
1426 /// call i8* @objc_retainBlock(i8* %value)
1427 llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value) {
1428 return emitARCValueOperation(*this, value,
1429 CGM.getARCEntrypoints().objc_retainBlock,
1430 "objc_retainBlock");
1433 /// Retain the given object which is the result of a function call.
1434 /// call i8* @objc_retainAutoreleasedReturnValue(i8* %value)
1436 /// Yes, this function name is one character away from a different
1437 /// call with completely different semantics.
1439 CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1440 // Fetch the void(void) inline asm which marks that we're going to
1441 // retain the autoreleased return value.
1442 llvm::InlineAsm *&marker
1443 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1445 llvm::StringRef assembly
1446 = CGM.getTargetCodeGenInfo()
1447 .getARCRetainAutoreleasedReturnValueMarker();
1449 // If we have an empty assembly string, there's nothing to do.
1450 if (assembly.empty()) {
1452 // Otherwise, at -O0, build an inline asm that we're going to call
1454 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1455 llvm::FunctionType *type =
1456 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
1457 /*variadic*/ false);
1459 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1461 // If we're at -O1 and above, we don't want to litter the code
1462 // with this marker yet, so leave a breadcrumb for the ARC
1463 // optimizer to pick up.
1465 llvm::NamedMDNode *metadata =
1466 CGM.getModule().getOrInsertNamedMetadata(
1467 "clang.arc.retainAutoreleasedReturnValueMarker");
1468 assert(metadata->getNumOperands() <= 1);
1469 if (metadata->getNumOperands() == 0) {
1470 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
1471 llvm::Value *args[] = { string };
1472 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), args));
1477 // Call the marker asm if we made one, which we do only at -O0.
1478 if (marker) Builder.CreateCall(marker);
1480 return emitARCValueOperation(*this, value,
1481 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1482 "objc_retainAutoreleasedReturnValue");
1485 /// Release the given object.
1486 /// call void @objc_release(i8* %value)
1487 void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
1488 if (isa<llvm::ConstantPointerNull>(value)) return;
1490 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1492 std::vector<llvm::Type*> args(1, Int8PtrTy);
1493 const llvm::FunctionType *fnType =
1494 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1495 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1498 // Cast the argument to 'id'.
1499 value = Builder.CreateBitCast(value, Int8PtrTy);
1501 // Call objc_release.
1502 llvm::CallInst *call = Builder.CreateCall(fn, value);
1503 call->setDoesNotThrow();
1506 llvm::SmallVector<llvm::Value*,1> args;
1507 call->setMetadata("clang.imprecise_release",
1508 llvm::MDNode::get(Builder.getContext(), args));
1512 /// Store into a strong object. Always calls this:
1513 /// call void @objc_storeStrong(i8** %addr, i8* %value)
1514 llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1517 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1518 == value->getType());
1520 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
1522 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
1523 const llvm::FunctionType *fnType
1524 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
1525 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
1528 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1529 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy);
1531 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow();
1533 if (ignored) return 0;
1537 /// Store into a strong object. Sometimes calls this:
1538 /// call void @objc_storeStrong(i8** %addr, i8* %value)
1539 /// Other times, breaks it down into components.
1540 llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
1541 llvm::Value *newValue,
1543 QualType type = dst.getType();
1544 bool isBlock = type->isBlockPointerType();
1546 // Use a store barrier at -O0 unless this is a block type or the
1547 // lvalue is inadequately aligned.
1548 if (shouldUseFusedARCCalls() &&
1550 !(dst.getAlignment() && dst.getAlignment() < PointerAlignInBytes)) {
1551 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
1554 // Otherwise, split it out.
1556 // Retain the new value.
1557 newValue = EmitARCRetain(type, newValue);
1559 // Read the old value.
1560 llvm::Value *oldValue = EmitLoadOfScalar(dst);
1562 // Store. We do this before the release so that any deallocs won't
1563 // see the old value.
1564 EmitStoreOfScalar(newValue, dst);
1566 // Finally, release the old value.
1567 EmitARCRelease(oldValue, /*precise*/ false);
1572 /// Autorelease the given object.
1573 /// call i8* @objc_autorelease(i8* %value)
1574 llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
1575 return emitARCValueOperation(*this, value,
1576 CGM.getARCEntrypoints().objc_autorelease,
1577 "objc_autorelease");
1580 /// Autorelease the given object.
1581 /// call i8* @objc_autoreleaseReturnValue(i8* %value)
1583 CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
1584 return emitARCValueOperation(*this, value,
1585 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
1586 "objc_autoreleaseReturnValue");
1589 /// Do a fused retain/autorelease of the given object.
1590 /// call i8* @objc_retainAutoreleaseReturnValue(i8* %value)
1592 CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
1593 return emitARCValueOperation(*this, value,
1594 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
1595 "objc_retainAutoreleaseReturnValue");
1598 /// Do a fused retain/autorelease of the given object.
1599 /// call i8* @objc_retainAutorelease(i8* %value)
1601 /// %retain = call i8* @objc_retainBlock(i8* %value)
1602 /// call i8* @objc_autorelease(i8* %retain)
1603 llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
1604 llvm::Value *value) {
1605 if (!type->isBlockPointerType())
1606 return EmitARCRetainAutoreleaseNonBlock(value);
1608 if (isa<llvm::ConstantPointerNull>(value)) return value;
1610 const llvm::Type *origType = value->getType();
1611 value = Builder.CreateBitCast(value, Int8PtrTy);
1612 value = EmitARCRetainBlock(value);
1613 value = EmitARCAutorelease(value);
1614 return Builder.CreateBitCast(value, origType);
1617 /// Do a fused retain/autorelease of the given object.
1618 /// call i8* @objc_retainAutorelease(i8* %value)
1620 CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
1621 return emitARCValueOperation(*this, value,
1622 CGM.getARCEntrypoints().objc_retainAutorelease,
1623 "objc_retainAutorelease");
1626 /// i8* @objc_loadWeak(i8** %addr)
1627 /// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
1628 llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
1629 return emitARCLoadOperation(*this, addr,
1630 CGM.getARCEntrypoints().objc_loadWeak,
1634 /// i8* @objc_loadWeakRetained(i8** %addr)
1635 llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
1636 return emitARCLoadOperation(*this, addr,
1637 CGM.getARCEntrypoints().objc_loadWeakRetained,
1638 "objc_loadWeakRetained");
1641 /// i8* @objc_storeWeak(i8** %addr, i8* %value)
1643 llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
1646 return emitARCStoreOperation(*this, addr, value,
1647 CGM.getARCEntrypoints().objc_storeWeak,
1648 "objc_storeWeak", ignored);
1651 /// i8* @objc_initWeak(i8** %addr, i8* %value)
1652 /// Returns %value. %addr is known to not have a current weak entry.
1653 /// Essentially equivalent to:
1654 /// *addr = nil; objc_storeWeak(addr, value);
1655 void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
1656 // If we're initializing to null, just write null to memory; no need
1657 // to get the runtime involved. But don't do this if optimization
1658 // is enabled, because accounting for this would make the optimizer
1659 // much more complicated.
1660 if (isa<llvm::ConstantPointerNull>(value) &&
1661 CGM.getCodeGenOpts().OptimizationLevel == 0) {
1662 Builder.CreateStore(value, addr);
1666 emitARCStoreOperation(*this, addr, value,
1667 CGM.getARCEntrypoints().objc_initWeak,
1668 "objc_initWeak", /*ignored*/ true);
1671 /// void @objc_destroyWeak(i8** %addr)
1672 /// Essentially objc_storeWeak(addr, nil).
1673 void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
1674 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
1676 std::vector<llvm::Type*> args(1, Int8PtrPtrTy);
1677 const llvm::FunctionType *fnType =
1678 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1679 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
1682 // Cast the argument to 'id*'.
1683 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1685 llvm::CallInst *call = Builder.CreateCall(fn, addr);
1686 call->setDoesNotThrow();
1689 /// void @objc_moveWeak(i8** %dest, i8** %src)
1690 /// Disregards the current value in %dest. Leaves %src pointing to nothing.
1691 /// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
1692 void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
1693 emitARCCopyOperation(*this, dst, src,
1694 CGM.getARCEntrypoints().objc_moveWeak,
1698 /// void @objc_copyWeak(i8** %dest, i8** %src)
1699 /// Disregards the current value in %dest. Essentially
1700 /// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
1701 void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
1702 emitARCCopyOperation(*this, dst, src,
1703 CGM.getARCEntrypoints().objc_copyWeak,
1707 /// Produce the code to do a objc_autoreleasepool_push.
1708 /// call i8* @objc_autoreleasePoolPush(void)
1709 llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
1710 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
1712 const llvm::FunctionType *fnType =
1713 llvm::FunctionType::get(Int8PtrTy, false);
1714 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
1717 llvm::CallInst *call = Builder.CreateCall(fn);
1718 call->setDoesNotThrow();
1723 /// Produce the code to do a primitive release.
1724 /// call void @objc_autoreleasePoolPop(i8* %ptr)
1725 void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
1726 assert(value->getType() == Int8PtrTy);
1728 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
1730 std::vector<llvm::Type*> args(1, Int8PtrTy);
1731 const llvm::FunctionType *fnType =
1732 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1734 // We don't want to use a weak import here; instead we should not
1735 // fall into this path.
1736 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
1739 llvm::CallInst *call = Builder.CreateCall(fn, value);
1740 call->setDoesNotThrow();
1743 /// Produce the code to do an MRR version objc_autoreleasepool_push.
1744 /// Which is: [[NSAutoreleasePool alloc] init];
1745 /// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
1746 /// init is declared as: - (id) init; in its NSObject super class.
1748 llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
1749 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
1750 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder);
1751 // [NSAutoreleasePool alloc]
1752 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
1753 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
1756 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
1757 getContext().getObjCIdType(),
1758 AllocSel, Receiver, Args);
1761 Receiver = AllocRV.getScalarVal();
1762 II = &CGM.getContext().Idents.get("init");
1763 Selector InitSel = getContext().Selectors.getSelector(0, &II);
1765 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
1766 getContext().getObjCIdType(),
1767 InitSel, Receiver, Args);
1768 return InitRV.getScalarVal();
1771 /// Produce the code to do a primitive release.
1773 void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
1774 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
1775 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
1777 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1778 getContext().VoidTy, DrainSel, Arg, Args);
1781 void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
1784 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
1785 CGF.EmitARCRelease(ptr, /*precise*/ true);
1788 void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
1791 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
1792 CGF.EmitARCRelease(ptr, /*precise*/ false);
1795 void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
1798 CGF.EmitARCDestroyWeak(addr);
1802 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
1805 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
1807 void Emit(CodeGenFunction &CGF, Flags flags) {
1808 CGF.EmitObjCAutoreleasePoolPop(Token);
1811 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
1814 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
1816 void Emit(CodeGenFunction &CGF, Flags flags) {
1817 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
1822 void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
1823 if (CGM.getLangOptions().ObjCAutoRefCount)
1824 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
1826 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
1829 static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
1832 switch (type.getObjCLifetime()) {
1833 case Qualifiers::OCL_None:
1834 case Qualifiers::OCL_ExplicitNone:
1835 case Qualifiers::OCL_Strong:
1836 case Qualifiers::OCL_Autoreleasing:
1837 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
1840 case Qualifiers::OCL_Weak:
1841 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
1845 llvm_unreachable("impossible lifetime!");
1846 return TryEmitResult();
1849 static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
1851 e = e->IgnoreParens();
1852 QualType type = e->getType();
1854 // As a very special optimization, in ARC++, if the l-value is the
1855 // result of a non-volatile assignment, do a simple retain of the
1856 // result of the call to objc_storeWeak instead of reloading.
1857 if (CGF.getLangOptions().CPlusPlus &&
1858 !type.isVolatileQualified() &&
1859 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
1860 isa<BinaryOperator>(e) &&
1861 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
1862 return TryEmitResult(CGF.EmitScalarExpr(e), false);
1864 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
1867 static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
1868 llvm::Value *value);
1870 /// Given that the given expression is some sort of call (which does
1871 /// not return retained), emit a retain following it.
1872 static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
1873 llvm::Value *value = CGF.EmitScalarExpr(e);
1874 return emitARCRetainAfterCall(CGF, value);
1877 static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
1878 llvm::Value *value) {
1879 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
1880 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
1882 // Place the retain immediately following the call.
1883 CGF.Builder.SetInsertPoint(call->getParent(),
1884 ++llvm::BasicBlock::iterator(call));
1885 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1887 CGF.Builder.restoreIP(ip);
1889 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
1890 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
1892 // Place the retain at the beginning of the normal destination block.
1893 llvm::BasicBlock *BB = invoke->getNormalDest();
1894 CGF.Builder.SetInsertPoint(BB, BB->begin());
1895 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1897 CGF.Builder.restoreIP(ip);
1900 // Bitcasts can arise because of related-result returns. Rewrite
1902 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
1903 llvm::Value *operand = bitcast->getOperand(0);
1904 operand = emitARCRetainAfterCall(CGF, operand);
1905 bitcast->setOperand(0, operand);
1908 // Generic fall-back case.
1910 // Retain using the non-block variant: we never need to do a copy
1911 // of a block that's been returned to us.
1912 return CGF.EmitARCRetainNonBlock(value);
1916 static TryEmitResult
1917 tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
1918 // The desired result type, if it differs from the type of the
1919 // ultimate opaque expression.
1920 const llvm::Type *resultType = 0;
1922 // If we're loading retained from a __strong xvalue, we can avoid
1923 // an extra retain/release pair by zeroing out the source of this
1924 // "move" operation.
1925 if (e->isXValue() && !e->getType().isConstQualified() &&
1926 e->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
1928 LValue lv = CGF.EmitLValue(e);
1930 // Load the object pointer and cast it to the appropriate type.
1931 QualType exprType = e->getType();
1932 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
1935 result = CGF.Builder.CreateBitCast(result, resultType);
1937 // Set the source pointer to NULL.
1939 = llvm::ConstantPointerNull::get(
1940 cast<llvm::PointerType>(CGF.ConvertType(exprType)));
1941 CGF.EmitStoreOfScalar(null, lv);
1943 return TryEmitResult(result, true);
1947 e = e->IgnoreParens();
1949 // There's a break at the end of this if-chain; anything
1950 // that wants to keep looping has to explicitly continue.
1951 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
1952 switch (ce->getCastKind()) {
1953 // No-op casts don't change the type, so we just ignore them.
1955 e = ce->getSubExpr();
1958 case CK_LValueToRValue: {
1959 TryEmitResult loadResult
1960 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
1962 llvm::Value *value = loadResult.getPointer();
1963 value = CGF.Builder.CreateBitCast(value, resultType);
1964 loadResult.setPointer(value);
1969 // These casts can change the type, so remember that and
1970 // soldier on. We only need to remember the outermost such
1972 case CK_AnyPointerToObjCPointerCast:
1973 case CK_AnyPointerToBlockPointerCast:
1976 resultType = CGF.ConvertType(ce->getType());
1977 e = ce->getSubExpr();
1978 assert(e->getType()->hasPointerRepresentation());
1981 // For consumptions, just emit the subexpression and thus elide
1982 // the retain/release pair.
1983 case CK_ObjCConsumeObject: {
1984 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
1985 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
1986 return TryEmitResult(result, true);
1989 // For reclaims, emit the subexpression as a retained call and
1990 // skip the consumption.
1991 case CK_ObjCReclaimReturnedObject: {
1992 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
1993 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
1994 return TryEmitResult(result, true);
1997 case CK_GetObjCProperty: {
1998 llvm::Value *result = emitARCRetainCall(CGF, ce);
1999 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2000 return TryEmitResult(result, true);
2007 // Skip __extension__.
2008 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2009 if (op->getOpcode() == UO_Extension) {
2010 e = op->getSubExpr();
2014 // For calls and message sends, use the retained-call logic.
2015 // Delegate inits are a special case in that they're the only
2016 // returns-retained expression that *isn't* surrounded by
2018 } else if (isa<CallExpr>(e) ||
2019 (isa<ObjCMessageExpr>(e) &&
2020 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2021 llvm::Value *result = emitARCRetainCall(CGF, e);
2022 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2023 return TryEmitResult(result, true);
2026 // Conservatively halt the search at any other expression kind.
2030 // We didn't find an obvious production, so emit what we've got and
2031 // tell the caller that we didn't manage to retain.
2032 llvm::Value *result = CGF.EmitScalarExpr(e);
2033 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2034 return TryEmitResult(result, false);
2037 static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2040 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2041 llvm::Value *value = result.getPointer();
2042 if (!result.getInt())
2043 value = CGF.EmitARCRetain(type, value);
2047 /// EmitARCRetainScalarExpr - Semantically equivalent to
2048 /// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2049 /// best-effort attempt to peephole expressions that naturally produce
2050 /// retained objects.
2051 llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2052 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2053 llvm::Value *value = result.getPointer();
2054 if (!result.getInt())
2055 value = EmitARCRetain(e->getType(), value);
2060 CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2061 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2062 llvm::Value *value = result.getPointer();
2063 if (result.getInt())
2064 value = EmitARCAutorelease(value);
2066 value = EmitARCRetainAutorelease(e->getType(), value);
2070 std::pair<LValue,llvm::Value*>
2071 CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2073 // Evaluate the RHS first.
2074 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2075 llvm::Value *value = result.getPointer();
2077 LValue lvalue = EmitLValue(e->getLHS());
2079 // If the RHS was emitted retained, expand this.
2080 if (result.getInt()) {
2081 llvm::Value *oldValue =
2082 EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatileQualified(),
2083 lvalue.getAlignment(), e->getType(),
2084 lvalue.getTBAAInfo());
2085 EmitStoreOfScalar(value, lvalue.getAddress(),
2086 lvalue.isVolatileQualified(), lvalue.getAlignment(),
2087 e->getType(), lvalue.getTBAAInfo());
2088 EmitARCRelease(oldValue, /*precise*/ false);
2090 value = EmitARCStoreStrong(lvalue, value, ignored);
2093 return std::pair<LValue,llvm::Value*>(lvalue, value);
2096 std::pair<LValue,llvm::Value*>
2097 CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2098 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2099 LValue lvalue = EmitLValue(e->getLHS());
2101 EmitStoreOfScalar(value, lvalue.getAddress(),
2102 lvalue.isVolatileQualified(), lvalue.getAlignment(),
2103 e->getType(), lvalue.getTBAAInfo());
2105 return std::pair<LValue,llvm::Value*>(lvalue, value);
2108 void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
2109 const ObjCAutoreleasePoolStmt &ARPS) {
2110 const Stmt *subStmt = ARPS.getSubStmt();
2111 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2113 CGDebugInfo *DI = getDebugInfo();
2115 DI->setLocation(S.getLBracLoc());
2116 DI->EmitRegionStart(Builder);
2119 // Keep track of the current cleanup stack depth.
2120 RunCleanupsScope Scope(*this);
2121 if (CGM.getCodeGenOpts().ObjCRuntimeHasARC) {
2122 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2123 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2125 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2126 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2129 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2130 E = S.body_end(); I != E; ++I)
2134 DI->setLocation(S.getRBracLoc());
2135 DI->EmitRegionEnd(Builder);
2139 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2140 /// make sure it survives garbage collection until this point.
2141 void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2142 // We just use an inline assembly.
2143 llvm::Type *paramTypes[] = { VoidPtrTy };
2144 llvm::FunctionType *extenderType
2145 = llvm::FunctionType::get(VoidTy, paramTypes, /*variadic*/ false);
2146 llvm::Value *extender
2147 = llvm::InlineAsm::get(extenderType,
2149 /* constraints */ "r",
2150 /* side effects */ true);
2152 object = Builder.CreateBitCast(object, VoidPtrTy);
2153 Builder.CreateCall(extender, object)->setDoesNotThrow();
2156 CGObjCRuntime::~CGObjCRuntime() {}