1 //===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This contains code to emit Objective-C code as LLVM code. 11 // 12 //===----------------------------------------------------------------------===// 13 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; 28 29 typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult; 30 static TryEmitResult 31 tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e); 32 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 llvm::Type *type = 37 cast<llvm::PointerType>(addr->getType())->getElementType(); 38 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type)); 39 } 40 41 /// Emits an instance of NSConstantString representing the object. 42 llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E) 43 { 44 llvm::Constant *C = 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())); 48 } 49 50 /// Emit a selector. 51 llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) { 52 // Untyped selector. 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()); 57 } 58 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()); 62 } 63 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, 67 const Expr *E, 68 const ObjCMethodDecl *Method, 69 RValue Result) { 70 if (!Method) 71 return Result; 72 73 if (!Method->hasRelatedResultType() || 74 CGF.getContext().hasSameType(E->getType(), Method->getResultType()) || 75 !Result.isScalar()) 76 return Result; 77 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()))); 81 } 82 83 /// Decide whether to extend the lifetime of the receiver of a 84 /// returns-inner-pointer message. 85 static bool 86 shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) { 87 switch (message->getReceiverKind()) { 88 89 // For a normal instance message, we should extend unless the 90 // receiver is loaded from a variable with precise lifetime. 91 case ObjCMessageExpr::Instance: { 92 const Expr *receiver = message->getInstanceReceiver(); 93 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver); 94 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true; 95 receiver = ice->getSubExpr()->IgnoreParens(); 96 97 // Only __strong variables. 98 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 99 return true; 100 101 // All ivars and fields have precise lifetime. 102 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver)) 103 return false; 104 105 // Otherwise, check for variables. 106 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr()); 107 if (!declRef) return true; 108 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl()); 109 if (!var) return true; 110 111 // All variables have precise lifetime except local variables with 112 // automatic storage duration that aren't specially marked. 113 return (var->hasLocalStorage() && 114 !var->hasAttr<ObjCPreciseLifetimeAttr>()); 115 } 116 117 case ObjCMessageExpr::Class: 118 case ObjCMessageExpr::SuperClass: 119 // It's never necessary for class objects. 120 return false; 121 122 case ObjCMessageExpr::SuperInstance: 123 // We generally assume that 'self' lives throughout a method call. 124 return false; 125 } 126 127 llvm_unreachable("invalid receiver kind"); 128 } 129 130 RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E, 131 ReturnValueSlot Return) { 132 // Only the lookup mechanism and first two arguments of the method 133 // implementation vary between runtimes. We can get the receiver and 134 // arguments in generic code. 135 136 bool isDelegateInit = E->isDelegateInitCall(); 137 138 const ObjCMethodDecl *method = E->getMethodDecl(); 139 140 // We don't retain the receiver in delegate init calls, and this is 141 // safe because the receiver value is always loaded from 'self', 142 // which we zero out. We don't want to Block_copy block receivers, 143 // though. 144 bool retainSelf = 145 (!isDelegateInit && 146 CGM.getLangOptions().ObjCAutoRefCount && 147 method && 148 method->hasAttr<NSConsumesSelfAttr>()); 149 150 CGObjCRuntime &Runtime = CGM.getObjCRuntime(); 151 bool isSuperMessage = false; 152 bool isClassMessage = false; 153 ObjCInterfaceDecl *OID = 0; 154 // Find the receiver 155 QualType ReceiverType; 156 llvm::Value *Receiver = 0; 157 switch (E->getReceiverKind()) { 158 case ObjCMessageExpr::Instance: 159 ReceiverType = E->getInstanceReceiver()->getType(); 160 if (retainSelf) { 161 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this, 162 E->getInstanceReceiver()); 163 Receiver = ter.getPointer(); 164 if (ter.getInt()) retainSelf = false; 165 } else 166 Receiver = EmitScalarExpr(E->getInstanceReceiver()); 167 break; 168 169 case ObjCMessageExpr::Class: { 170 ReceiverType = E->getClassReceiver(); 171 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>(); 172 assert(ObjTy && "Invalid Objective-C class message send"); 173 OID = ObjTy->getInterface(); 174 assert(OID && "Invalid Objective-C class message send"); 175 Receiver = Runtime.GetClass(Builder, OID); 176 isClassMessage = true; 177 break; 178 } 179 180 case ObjCMessageExpr::SuperInstance: 181 ReceiverType = E->getSuperType(); 182 Receiver = LoadObjCSelf(); 183 isSuperMessage = true; 184 break; 185 186 case ObjCMessageExpr::SuperClass: 187 ReceiverType = E->getSuperType(); 188 Receiver = LoadObjCSelf(); 189 isSuperMessage = true; 190 isClassMessage = true; 191 break; 192 } 193 194 if (retainSelf) 195 Receiver = EmitARCRetainNonBlock(Receiver); 196 197 // In ARC, we sometimes want to "extend the lifetime" 198 // (i.e. retain+autorelease) of receivers of returns-inner-pointer 199 // messages. 200 if (getLangOptions().ObjCAutoRefCount && method && 201 method->hasAttr<ObjCReturnsInnerPointerAttr>() && 202 shouldExtendReceiverForInnerPointerMessage(E)) 203 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver); 204 205 QualType ResultType = 206 method ? method->getResultType() : E->getType(); 207 208 CallArgList Args; 209 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end()); 210 211 // For delegate init calls in ARC, do an unsafe store of null into 212 // self. This represents the call taking direct ownership of that 213 // value. We have to do this after emitting the other call 214 // arguments because they might also reference self, but we don't 215 // have to worry about any of them modifying self because that would 216 // be an undefined read and write of an object in unordered 217 // expressions. 218 if (isDelegateInit) { 219 assert(getLangOptions().ObjCAutoRefCount && 220 "delegate init calls should only be marked in ARC"); 221 222 // Do an unsafe store of null into self. 223 llvm::Value *selfAddr = 224 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()]; 225 assert(selfAddr && "no self entry for a delegate init call?"); 226 227 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr); 228 } 229 230 RValue result; 231 if (isSuperMessage) { 232 // super is only valid in an Objective-C method 233 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl); 234 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext()); 235 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType, 236 E->getSelector(), 237 OMD->getClassInterface(), 238 isCategoryImpl, 239 Receiver, 240 isClassMessage, 241 Args, 242 method); 243 } else { 244 result = Runtime.GenerateMessageSend(*this, Return, ResultType, 245 E->getSelector(), 246 Receiver, Args, OID, 247 method); 248 } 249 250 // For delegate init calls in ARC, implicitly store the result of 251 // the call back into self. This takes ownership of the value. 252 if (isDelegateInit) { 253 llvm::Value *selfAddr = 254 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()]; 255 llvm::Value *newSelf = result.getScalarVal(); 256 257 // The delegate return type isn't necessarily a matching type; in 258 // fact, it's quite likely to be 'id'. 259 llvm::Type *selfTy = 260 cast<llvm::PointerType>(selfAddr->getType())->getElementType(); 261 newSelf = Builder.CreateBitCast(newSelf, selfTy); 262 263 Builder.CreateStore(newSelf, selfAddr); 264 } 265 266 return AdjustRelatedResultType(*this, E, method, result); 267 } 268 269 namespace { 270 struct FinishARCDealloc : EHScopeStack::Cleanup { 271 void Emit(CodeGenFunction &CGF, Flags flags) { 272 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl); 273 274 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext()); 275 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 276 if (!iface->getSuperClass()) return; 277 278 bool isCategory = isa<ObjCCategoryImplDecl>(impl); 279 280 // Call [super dealloc] if we have a superclass. 281 llvm::Value *self = CGF.LoadObjCSelf(); 282 283 CallArgList args; 284 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(), 285 CGF.getContext().VoidTy, 286 method->getSelector(), 287 iface, 288 isCategory, 289 self, 290 /*is class msg*/ false, 291 args, 292 method); 293 } 294 }; 295 } 296 297 /// StartObjCMethod - Begin emission of an ObjCMethod. This generates 298 /// the LLVM function and sets the other context used by 299 /// CodeGenFunction. 300 void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD, 301 const ObjCContainerDecl *CD, 302 SourceLocation StartLoc) { 303 FunctionArgList args; 304 // Check if we should generate debug info for this method. 305 if (CGM.getModuleDebugInfo() && !OMD->hasAttr<NoDebugAttr>()) 306 DebugInfo = CGM.getModuleDebugInfo(); 307 308 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD); 309 310 const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(OMD); 311 CGM.SetInternalFunctionAttributes(OMD, Fn, FI); 312 313 args.push_back(OMD->getSelfDecl()); 314 args.push_back(OMD->getCmdDecl()); 315 316 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(), 317 E = OMD->param_end(); PI != E; ++PI) 318 args.push_back(*PI); 319 320 CurGD = OMD; 321 322 StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc); 323 324 // In ARC, certain methods get an extra cleanup. 325 if (CGM.getLangOptions().ObjCAutoRefCount && 326 OMD->isInstanceMethod() && 327 OMD->getSelector().isUnarySelector()) { 328 const IdentifierInfo *ident = 329 OMD->getSelector().getIdentifierInfoForSlot(0); 330 if (ident->isStr("dealloc")) 331 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind()); 332 } 333 } 334 335 static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF, 336 LValue lvalue, QualType type); 337 338 void CodeGenFunction::GenerateObjCGetterBody(ObjCIvarDecl *Ivar, 339 bool IsAtomic, bool IsStrong) { 340 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), 341 Ivar, 0); 342 llvm::Value *GetCopyStructFn = 343 CGM.getObjCRuntime().GetGetStructFunction(); 344 CodeGenTypes &Types = CGM.getTypes(); 345 // objc_copyStruct (ReturnValue, &structIvar, 346 // sizeof (Type of Ivar), isAtomic, false); 347 CallArgList Args; 348 RValue RV = RValue::get(Builder.CreateBitCast(ReturnValue, VoidPtrTy)); 349 Args.add(RV, getContext().VoidPtrTy); 350 RV = RValue::get(Builder.CreateBitCast(LV.getAddress(), VoidPtrTy)); 351 Args.add(RV, getContext().VoidPtrTy); 352 // sizeof (Type of Ivar) 353 CharUnits Size = getContext().getTypeSizeInChars(Ivar->getType()); 354 llvm::Value *SizeVal = 355 llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy), 356 Size.getQuantity()); 357 Args.add(RValue::get(SizeVal), getContext().LongTy); 358 llvm::Value *isAtomic = 359 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 360 IsAtomic ? 1 : 0); 361 Args.add(RValue::get(isAtomic), getContext().BoolTy); 362 llvm::Value *hasStrong = 363 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 364 IsStrong ? 1 : 0); 365 Args.add(RValue::get(hasStrong), getContext().BoolTy); 366 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args, 367 FunctionType::ExtInfo()), 368 GetCopyStructFn, ReturnValueSlot(), Args); 369 } 370 371 /// Generate an Objective-C method. An Objective-C method is a C function with 372 /// its pointer, name, and types registered in the class struture. 373 void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) { 374 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart()); 375 EmitStmt(OMD->getBody()); 376 FinishFunction(OMD->getBodyRBrace()); 377 } 378 379 // FIXME: I wasn't sure about the synthesis approach. If we end up generating an 380 // AST for the whole body we can just fall back to having a GenerateFunction 381 // which takes the body Stmt. 382 383 /// GenerateObjCGetter - Generate an Objective-C property getter 384 /// function. The given Decl must be an ObjCImplementationDecl. @synthesize 385 /// is illegal within a category. 386 void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP, 387 const ObjCPropertyImplDecl *PID) { 388 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl(); 389 const ObjCPropertyDecl *PD = PID->getPropertyDecl(); 390 bool IsAtomic = 391 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic); 392 ObjCMethodDecl *OMD = PD->getGetterMethodDecl(); 393 assert(OMD && "Invalid call to generate getter (empty method)"); 394 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart()); 395 396 // Determine if we should use an objc_getProperty call for 397 // this. Non-atomic properties are directly evaluated. 398 // atomic 'copy' and 'retain' properties are also directly 399 // evaluated in gc-only mode. 400 if (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly && 401 IsAtomic && 402 (PD->getSetterKind() == ObjCPropertyDecl::Copy || 403 PD->getSetterKind() == ObjCPropertyDecl::Retain)) { 404 llvm::Value *GetPropertyFn = 405 CGM.getObjCRuntime().GetPropertyGetFunction(); 406 407 if (!GetPropertyFn) { 408 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy"); 409 FinishFunction(); 410 return; 411 } 412 413 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true). 414 // FIXME: Can't this be simpler? This might even be worse than the 415 // corresponding gcc code. 416 CodeGenTypes &Types = CGM.getTypes(); 417 ValueDecl *Cmd = OMD->getCmdDecl(); 418 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd"); 419 QualType IdTy = getContext().getObjCIdType(); 420 llvm::Value *SelfAsId = 421 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy)); 422 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar); 423 llvm::Value *True = 424 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1); 425 CallArgList Args; 426 Args.add(RValue::get(SelfAsId), IdTy); 427 Args.add(RValue::get(CmdVal), Cmd->getType()); 428 Args.add(RValue::get(Offset), getContext().getPointerDiffType()); 429 Args.add(RValue::get(True), getContext().BoolTy); 430 // FIXME: We shouldn't need to get the function info here, the 431 // runtime already should have computed it to build the function. 432 RValue RV = EmitCall(Types.getFunctionInfo(PD->getType(), Args, 433 FunctionType::ExtInfo()), 434 GetPropertyFn, ReturnValueSlot(), Args); 435 // We need to fix the type here. Ivars with copy & retain are 436 // always objects so we don't need to worry about complex or 437 // aggregates. 438 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(), 439 Types.ConvertType(PD->getType()))); 440 EmitReturnOfRValue(RV, PD->getType()); 441 442 // objc_getProperty does an autorelease, so we should suppress ours. 443 AutoreleaseResult = false; 444 } else { 445 const llvm::Triple &Triple = getContext().Target.getTriple(); 446 QualType IVART = Ivar->getType(); 447 if (IsAtomic && 448 IVART->isScalarType() && 449 (Triple.getArch() == llvm::Triple::arm || 450 Triple.getArch() == llvm::Triple::thumb) && 451 (getContext().getTypeSizeInChars(IVART) 452 > CharUnits::fromQuantity(4)) && 453 CGM.getObjCRuntime().GetGetStructFunction()) { 454 GenerateObjCGetterBody(Ivar, true, false); 455 } 456 else if (IsAtomic && 457 (IVART->isScalarType() && !IVART->isRealFloatingType()) && 458 Triple.getArch() == llvm::Triple::x86 && 459 (getContext().getTypeSizeInChars(IVART) 460 > CharUnits::fromQuantity(4)) && 461 CGM.getObjCRuntime().GetGetStructFunction()) { 462 GenerateObjCGetterBody(Ivar, true, false); 463 } 464 else if (IsAtomic && 465 (IVART->isScalarType() && !IVART->isRealFloatingType()) && 466 Triple.getArch() == llvm::Triple::x86_64 && 467 (getContext().getTypeSizeInChars(IVART) 468 > CharUnits::fromQuantity(8)) && 469 CGM.getObjCRuntime().GetGetStructFunction()) { 470 GenerateObjCGetterBody(Ivar, true, false); 471 } 472 else if (IVART->isAnyComplexType()) { 473 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), 474 Ivar, 0); 475 ComplexPairTy Pair = LoadComplexFromAddr(LV.getAddress(), 476 LV.isVolatileQualified()); 477 StoreComplexToAddr(Pair, ReturnValue, LV.isVolatileQualified()); 478 } 479 else if (hasAggregateLLVMType(IVART)) { 480 bool IsStrong = false; 481 if ((IsStrong = IvarTypeWithAggrGCObjects(IVART)) 482 && CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect 483 && CGM.getObjCRuntime().GetGetStructFunction()) { 484 GenerateObjCGetterBody(Ivar, IsAtomic, IsStrong); 485 } 486 else { 487 const CXXRecordDecl *classDecl = IVART->getAsCXXRecordDecl(); 488 489 if (PID->getGetterCXXConstructor() && 490 classDecl && !classDecl->hasTrivialDefaultConstructor()) { 491 ReturnStmt *Stmt = 492 new (getContext()) ReturnStmt(SourceLocation(), 493 PID->getGetterCXXConstructor(), 494 0); 495 EmitReturnStmt(*Stmt); 496 } else if (IsAtomic && 497 !IVART->isAnyComplexType() && 498 Triple.getArch() == llvm::Triple::x86 && 499 (getContext().getTypeSizeInChars(IVART) 500 > CharUnits::fromQuantity(4)) && 501 CGM.getObjCRuntime().GetGetStructFunction()) { 502 GenerateObjCGetterBody(Ivar, true, false); 503 } 504 else if (IsAtomic && 505 !IVART->isAnyComplexType() && 506 Triple.getArch() == llvm::Triple::x86_64 && 507 (getContext().getTypeSizeInChars(IVART) 508 > CharUnits::fromQuantity(8)) && 509 CGM.getObjCRuntime().GetGetStructFunction()) { 510 GenerateObjCGetterBody(Ivar, true, false); 511 } 512 else { 513 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), 514 Ivar, 0); 515 EmitAggregateCopy(ReturnValue, LV.getAddress(), IVART); 516 } 517 } 518 } else { 519 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), 520 Ivar, 0); 521 QualType propType = PD->getType(); 522 523 llvm::Value *value; 524 if (propType->isReferenceType()) { 525 value = LV.getAddress(); 526 } else { 527 // We want to load and autoreleaseReturnValue ARC __weak ivars. 528 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) { 529 value = emitARCRetainLoadOfScalar(*this, LV, IVART); 530 531 // Otherwise we want to do a simple load, suppressing the 532 // final autorelease. 533 } else { 534 value = EmitLoadOfLValue(LV).getScalarVal(); 535 AutoreleaseResult = false; 536 } 537 538 value = Builder.CreateBitCast(value, ConvertType(propType)); 539 } 540 541 EmitReturnOfRValue(RValue::get(value), propType); 542 } 543 } 544 545 FinishFunction(); 546 } 547 548 void CodeGenFunction::GenerateObjCAtomicSetterBody(ObjCMethodDecl *OMD, 549 ObjCIvarDecl *Ivar) { 550 // objc_copyStruct (&structIvar, &Arg, 551 // sizeof (struct something), true, false); 552 llvm::Value *GetCopyStructFn = 553 CGM.getObjCRuntime().GetSetStructFunction(); 554 CodeGenTypes &Types = CGM.getTypes(); 555 CallArgList Args; 556 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), Ivar, 0); 557 RValue RV = 558 RValue::get(Builder.CreateBitCast(LV.getAddress(), 559 Types.ConvertType(getContext().VoidPtrTy))); 560 Args.add(RV, getContext().VoidPtrTy); 561 llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()]; 562 llvm::Value *ArgAsPtrTy = 563 Builder.CreateBitCast(Arg, 564 Types.ConvertType(getContext().VoidPtrTy)); 565 RV = RValue::get(ArgAsPtrTy); 566 Args.add(RV, getContext().VoidPtrTy); 567 // sizeof (Type of Ivar) 568 CharUnits Size = getContext().getTypeSizeInChars(Ivar->getType()); 569 llvm::Value *SizeVal = 570 llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy), 571 Size.getQuantity()); 572 Args.add(RValue::get(SizeVal), getContext().LongTy); 573 llvm::Value *True = 574 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1); 575 Args.add(RValue::get(True), getContext().BoolTy); 576 llvm::Value *False = 577 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0); 578 Args.add(RValue::get(False), getContext().BoolTy); 579 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args, 580 FunctionType::ExtInfo()), 581 GetCopyStructFn, ReturnValueSlot(), Args); 582 } 583 584 static bool 585 IvarAssignHasTrvialAssignment(const ObjCPropertyImplDecl *PID, 586 QualType IvarT) { 587 bool HasTrvialAssignment = true; 588 if (PID->getSetterCXXAssignment()) { 589 const CXXRecordDecl *classDecl = IvarT->getAsCXXRecordDecl(); 590 HasTrvialAssignment = 591 (!classDecl || classDecl->hasTrivialCopyAssignment()); 592 } 593 return HasTrvialAssignment; 594 } 595 596 /// GenerateObjCSetter - Generate an Objective-C property setter 597 /// function. The given Decl must be an ObjCImplementationDecl. @synthesize 598 /// is illegal within a category. 599 void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP, 600 const ObjCPropertyImplDecl *PID) { 601 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl(); 602 const ObjCPropertyDecl *PD = PID->getPropertyDecl(); 603 ObjCMethodDecl *OMD = PD->getSetterMethodDecl(); 604 assert(OMD && "Invalid call to generate setter (empty method)"); 605 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart()); 606 const llvm::Triple &Triple = getContext().Target.getTriple(); 607 QualType IVART = Ivar->getType(); 608 bool IsCopy = PD->getSetterKind() == ObjCPropertyDecl::Copy; 609 bool IsAtomic = 610 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic); 611 612 // Determine if we should use an objc_setProperty call for 613 // this. Properties with 'copy' semantics always use it, as do 614 // non-atomic properties with 'release' semantics as long as we are 615 // not in gc-only mode. 616 if (IsCopy || 617 (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly && 618 PD->getSetterKind() == ObjCPropertyDecl::Retain)) { 619 llvm::Value *SetPropertyFn = 620 CGM.getObjCRuntime().GetPropertySetFunction(); 621 622 if (!SetPropertyFn) { 623 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy"); 624 FinishFunction(); 625 return; 626 } 627 628 // Emit objc_setProperty((id) self, _cmd, offset, arg, 629 // <is-atomic>, <is-copy>). 630 // FIXME: Can't this be simpler? This might even be worse than the 631 // corresponding gcc code. 632 CodeGenTypes &Types = CGM.getTypes(); 633 ValueDecl *Cmd = OMD->getCmdDecl(); 634 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd"); 635 QualType IdTy = getContext().getObjCIdType(); 636 llvm::Value *SelfAsId = 637 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy)); 638 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar); 639 llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()]; 640 llvm::Value *ArgAsId = 641 Builder.CreateBitCast(Builder.CreateLoad(Arg, "arg"), 642 Types.ConvertType(IdTy)); 643 llvm::Value *True = 644 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1); 645 llvm::Value *False = 646 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0); 647 CallArgList Args; 648 Args.add(RValue::get(SelfAsId), IdTy); 649 Args.add(RValue::get(CmdVal), Cmd->getType()); 650 Args.add(RValue::get(Offset), getContext().getPointerDiffType()); 651 Args.add(RValue::get(ArgAsId), IdTy); 652 Args.add(RValue::get(IsAtomic ? True : False), getContext().BoolTy); 653 Args.add(RValue::get(IsCopy ? True : False), getContext().BoolTy); 654 // FIXME: We shouldn't need to get the function info here, the runtime 655 // already should have computed it to build the function. 656 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args, 657 FunctionType::ExtInfo()), 658 SetPropertyFn, 659 ReturnValueSlot(), Args); 660 } else if (IsAtomic && hasAggregateLLVMType(IVART) && 661 !IVART->isAnyComplexType() && 662 IvarAssignHasTrvialAssignment(PID, IVART) && 663 ((Triple.getArch() == llvm::Triple::x86 && 664 (getContext().getTypeSizeInChars(IVART) 665 > CharUnits::fromQuantity(4))) || 666 (Triple.getArch() == llvm::Triple::x86_64 && 667 (getContext().getTypeSizeInChars(IVART) 668 > CharUnits::fromQuantity(8)))) 669 && CGM.getObjCRuntime().GetSetStructFunction()) { 670 // objc_copyStruct (&structIvar, &Arg, 671 // sizeof (struct something), true, false); 672 GenerateObjCAtomicSetterBody(OMD, Ivar); 673 } else if (PID->getSetterCXXAssignment()) { 674 EmitIgnoredExpr(PID->getSetterCXXAssignment()); 675 } else { 676 if (IsAtomic && 677 IVART->isScalarType() && 678 (Triple.getArch() == llvm::Triple::arm || 679 Triple.getArch() == llvm::Triple::thumb) && 680 (getContext().getTypeSizeInChars(IVART) 681 > CharUnits::fromQuantity(4)) && 682 CGM.getObjCRuntime().GetGetStructFunction()) { 683 GenerateObjCAtomicSetterBody(OMD, Ivar); 684 } 685 else if (IsAtomic && 686 (IVART->isScalarType() && !IVART->isRealFloatingType()) && 687 Triple.getArch() == llvm::Triple::x86 && 688 (getContext().getTypeSizeInChars(IVART) 689 > CharUnits::fromQuantity(4)) && 690 CGM.getObjCRuntime().GetGetStructFunction()) { 691 GenerateObjCAtomicSetterBody(OMD, Ivar); 692 } 693 else if (IsAtomic && 694 (IVART->isScalarType() && !IVART->isRealFloatingType()) && 695 Triple.getArch() == llvm::Triple::x86_64 && 696 (getContext().getTypeSizeInChars(IVART) 697 > CharUnits::fromQuantity(8)) && 698 CGM.getObjCRuntime().GetGetStructFunction()) { 699 GenerateObjCAtomicSetterBody(OMD, Ivar); 700 } 701 else { 702 // FIXME: Find a clean way to avoid AST node creation. 703 SourceLocation Loc = PID->getLocStart(); 704 ValueDecl *Self = OMD->getSelfDecl(); 705 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl(); 706 DeclRefExpr Base(Self, Self->getType(), VK_RValue, Loc); 707 ParmVarDecl *ArgDecl = *OMD->param_begin(); 708 QualType T = ArgDecl->getType(); 709 if (T->isReferenceType()) 710 T = cast<ReferenceType>(T)->getPointeeType(); 711 DeclRefExpr Arg(ArgDecl, T, VK_LValue, Loc); 712 ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base, true, true); 713 714 // The property type can differ from the ivar type in some situations with 715 // Objective-C pointer types, we can always bit cast the RHS in these cases. 716 if (getContext().getCanonicalType(Ivar->getType()) != 717 getContext().getCanonicalType(ArgDecl->getType())) { 718 ImplicitCastExpr ArgCasted(ImplicitCastExpr::OnStack, 719 Ivar->getType(), CK_BitCast, &Arg, 720 VK_RValue); 721 BinaryOperator Assign(&IvarRef, &ArgCasted, BO_Assign, 722 Ivar->getType(), VK_RValue, OK_Ordinary, Loc); 723 EmitStmt(&Assign); 724 } else { 725 BinaryOperator Assign(&IvarRef, &Arg, BO_Assign, 726 Ivar->getType(), VK_RValue, OK_Ordinary, Loc); 727 EmitStmt(&Assign); 728 } 729 } 730 } 731 732 FinishFunction(); 733 } 734 735 namespace { 736 struct DestroyIvar : EHScopeStack::Cleanup { 737 private: 738 llvm::Value *addr; 739 const ObjCIvarDecl *ivar; 740 CodeGenFunction::Destroyer &destroyer; 741 bool useEHCleanupForArray; 742 public: 743 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar, 744 CodeGenFunction::Destroyer *destroyer, 745 bool useEHCleanupForArray) 746 : addr(addr), ivar(ivar), destroyer(*destroyer), 747 useEHCleanupForArray(useEHCleanupForArray) {} 748 749 void Emit(CodeGenFunction &CGF, Flags flags) { 750 LValue lvalue 751 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0); 752 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer, 753 flags.isForNormalCleanup() && useEHCleanupForArray); 754 } 755 }; 756 } 757 758 /// Like CodeGenFunction::destroyARCStrong, but do it with a call. 759 static void destroyARCStrongWithStore(CodeGenFunction &CGF, 760 llvm::Value *addr, 761 QualType type) { 762 llvm::Value *null = getNullForVariable(addr); 763 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true); 764 } 765 766 static void emitCXXDestructMethod(CodeGenFunction &CGF, 767 ObjCImplementationDecl *impl) { 768 CodeGenFunction::RunCleanupsScope scope(CGF); 769 770 llvm::Value *self = CGF.LoadObjCSelf(); 771 772 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 773 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 774 ivar; ivar = ivar->getNextIvar()) { 775 QualType type = ivar->getType(); 776 777 // Check whether the ivar is a destructible type. 778 QualType::DestructionKind dtorKind = type.isDestructedType(); 779 if (!dtorKind) continue; 780 781 CodeGenFunction::Destroyer *destroyer = 0; 782 783 // Use a call to objc_storeStrong to destroy strong ivars, for the 784 // general benefit of the tools. 785 if (dtorKind == QualType::DK_objc_strong_lifetime) { 786 destroyer = &destroyARCStrongWithStore; 787 788 // Otherwise use the default for the destruction kind. 789 } else { 790 destroyer = &CGF.getDestroyer(dtorKind); 791 } 792 793 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind); 794 795 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer, 796 cleanupKind & EHCleanup); 797 } 798 799 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?"); 800 } 801 802 void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, 803 ObjCMethodDecl *MD, 804 bool ctor) { 805 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface()); 806 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart()); 807 808 // Emit .cxx_construct. 809 if (ctor) { 810 // Suppress the final autorelease in ARC. 811 AutoreleaseResult = false; 812 813 SmallVector<CXXCtorInitializer *, 8> IvarInitializers; 814 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(), 815 E = IMP->init_end(); B != E; ++B) { 816 CXXCtorInitializer *IvarInit = (*B); 817 FieldDecl *Field = IvarInit->getAnyMember(); 818 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field); 819 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), 820 LoadObjCSelf(), Ivar, 0); 821 EmitAggExpr(IvarInit->getInit(), AggValueSlot::forLValue(LV, true)); 822 } 823 // constructor returns 'self'. 824 CodeGenTypes &Types = CGM.getTypes(); 825 QualType IdTy(CGM.getContext().getObjCIdType()); 826 llvm::Value *SelfAsId = 827 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy)); 828 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy); 829 830 // Emit .cxx_destruct. 831 } else { 832 emitCXXDestructMethod(*this, IMP); 833 } 834 FinishFunction(); 835 } 836 837 bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) { 838 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(); 839 it++; it++; 840 const ABIArgInfo &AI = it->info; 841 // FIXME. Is this sufficient check? 842 return (AI.getKind() == ABIArgInfo::Indirect); 843 } 844 845 bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) { 846 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC) 847 return false; 848 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>()) 849 return FDTTy->getDecl()->hasObjectMember(); 850 return false; 851 } 852 853 llvm::Value *CodeGenFunction::LoadObjCSelf() { 854 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl); 855 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self"); 856 } 857 858 QualType CodeGenFunction::TypeOfSelfObject() { 859 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl); 860 ImplicitParamDecl *selfDecl = OMD->getSelfDecl(); 861 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>( 862 getContext().getCanonicalType(selfDecl->getType())); 863 return PTy->getPointeeType(); 864 } 865 866 LValue 867 CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) { 868 // This is a special l-value that just issues sends when we load or 869 // store through it. 870 871 // For certain base kinds, we need to emit the base immediately. 872 llvm::Value *Base; 873 if (E->isSuperReceiver()) 874 Base = LoadObjCSelf(); 875 else if (E->isClassReceiver()) 876 Base = CGM.getObjCRuntime().GetClass(Builder, E->getClassReceiver()); 877 else 878 Base = EmitScalarExpr(E->getBase()); 879 return LValue::MakePropertyRef(E, Base); 880 } 881 882 static RValue GenerateMessageSendSuper(CodeGenFunction &CGF, 883 ReturnValueSlot Return, 884 QualType ResultType, 885 Selector S, 886 llvm::Value *Receiver, 887 const CallArgList &CallArgs) { 888 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CGF.CurFuncDecl); 889 bool isClassMessage = OMD->isClassMethod(); 890 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext()); 891 return CGF.CGM.getObjCRuntime() 892 .GenerateMessageSendSuper(CGF, Return, ResultType, 893 S, OMD->getClassInterface(), 894 isCategoryImpl, Receiver, 895 isClassMessage, CallArgs); 896 } 897 898 RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV, 899 ReturnValueSlot Return) { 900 const ObjCPropertyRefExpr *E = LV.getPropertyRefExpr(); 901 QualType ResultType = E->getGetterResultType(); 902 Selector S; 903 const ObjCMethodDecl *method; 904 if (E->isExplicitProperty()) { 905 const ObjCPropertyDecl *Property = E->getExplicitProperty(); 906 S = Property->getGetterName(); 907 method = Property->getGetterMethodDecl(); 908 } else { 909 method = E->getImplicitPropertyGetter(); 910 S = method->getSelector(); 911 } 912 913 llvm::Value *Receiver = LV.getPropertyRefBaseAddr(); 914 915 if (CGM.getLangOptions().ObjCAutoRefCount) { 916 QualType receiverType; 917 if (E->isSuperReceiver()) 918 receiverType = E->getSuperReceiverType(); 919 else if (E->isClassReceiver()) 920 receiverType = getContext().getObjCClassType(); 921 else 922 receiverType = E->getBase()->getType(); 923 } 924 925 // Accesses to 'super' follow a different code path. 926 if (E->isSuperReceiver()) 927 return AdjustRelatedResultType(*this, E, method, 928 GenerateMessageSendSuper(*this, Return, 929 ResultType, 930 S, Receiver, 931 CallArgList())); 932 const ObjCInterfaceDecl *ReceiverClass 933 = (E->isClassReceiver() ? E->getClassReceiver() : 0); 934 return AdjustRelatedResultType(*this, E, method, 935 CGM.getObjCRuntime(). 936 GenerateMessageSend(*this, Return, ResultType, S, 937 Receiver, CallArgList(), ReceiverClass)); 938 } 939 940 void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src, 941 LValue Dst) { 942 const ObjCPropertyRefExpr *E = Dst.getPropertyRefExpr(); 943 Selector S = E->getSetterSelector(); 944 QualType ArgType = E->getSetterArgType(); 945 946 // FIXME. Other than scalars, AST is not adequate for setter and 947 // getter type mismatches which require conversion. 948 if (Src.isScalar()) { 949 llvm::Value *SrcVal = Src.getScalarVal(); 950 QualType DstType = getContext().getCanonicalType(ArgType); 951 llvm::Type *DstTy = ConvertType(DstType); 952 if (SrcVal->getType() != DstTy) 953 Src = 954 RValue::get(EmitScalarConversion(SrcVal, E->getType(), DstType)); 955 } 956 957 CallArgList Args; 958 Args.add(Src, ArgType); 959 960 llvm::Value *Receiver = Dst.getPropertyRefBaseAddr(); 961 QualType ResultType = getContext().VoidTy; 962 963 if (E->isSuperReceiver()) { 964 GenerateMessageSendSuper(*this, ReturnValueSlot(), 965 ResultType, S, Receiver, Args); 966 return; 967 } 968 969 const ObjCInterfaceDecl *ReceiverClass 970 = (E->isClassReceiver() ? E->getClassReceiver() : 0); 971 972 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(), 973 ResultType, S, Receiver, Args, 974 ReceiverClass); 975 } 976 977 void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){ 978 llvm::Constant *EnumerationMutationFn = 979 CGM.getObjCRuntime().EnumerationMutationFunction(); 980 981 if (!EnumerationMutationFn) { 982 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime"); 983 return; 984 } 985 986 CGDebugInfo *DI = getDebugInfo(); 987 if (DI) { 988 DI->setLocation(S.getSourceRange().getBegin()); 989 DI->EmitRegionStart(Builder); 990 } 991 992 // The local variable comes into scope immediately. 993 AutoVarEmission variable = AutoVarEmission::invalid(); 994 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) 995 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl())); 996 997 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end"); 998 999 // Fast enumeration state. 1000 QualType StateTy = CGM.getObjCFastEnumerationStateType(); 1001 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr"); 1002 EmitNullInitialization(StatePtr, StateTy); 1003 1004 // Number of elements in the items array. 1005 static const unsigned NumItems = 16; 1006 1007 // Fetch the countByEnumeratingWithState:objects:count: selector. 1008 IdentifierInfo *II[] = { 1009 &CGM.getContext().Idents.get("countByEnumeratingWithState"), 1010 &CGM.getContext().Idents.get("objects"), 1011 &CGM.getContext().Idents.get("count") 1012 }; 1013 Selector FastEnumSel = 1014 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]); 1015 1016 QualType ItemsTy = 1017 getContext().getConstantArrayType(getContext().getObjCIdType(), 1018 llvm::APInt(32, NumItems), 1019 ArrayType::Normal, 0); 1020 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr"); 1021 1022 // Emit the collection pointer. In ARC, we do a retain. 1023 llvm::Value *Collection; 1024 if (getLangOptions().ObjCAutoRefCount) { 1025 Collection = EmitARCRetainScalarExpr(S.getCollection()); 1026 1027 // Enter a cleanup to do the release. 1028 EmitObjCConsumeObject(S.getCollection()->getType(), Collection); 1029 } else { 1030 Collection = EmitScalarExpr(S.getCollection()); 1031 } 1032 1033 // The 'continue' label needs to appear within the cleanup for the 1034 // collection object. 1035 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next"); 1036 1037 // Send it our message: 1038 CallArgList Args; 1039 1040 // The first argument is a temporary of the enumeration-state type. 1041 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy)); 1042 1043 // The second argument is a temporary array with space for NumItems 1044 // pointers. We'll actually be loading elements from the array 1045 // pointer written into the control state; this buffer is so that 1046 // collections that *aren't* backed by arrays can still queue up 1047 // batches of elements. 1048 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy)); 1049 1050 // The third argument is the capacity of that temporary array. 1051 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy); 1052 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems); 1053 Args.add(RValue::get(Count), getContext().UnsignedLongTy); 1054 1055 // Start the enumeration. 1056 RValue CountRV = 1057 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(), 1058 getContext().UnsignedLongTy, 1059 FastEnumSel, 1060 Collection, Args); 1061 1062 // The initial number of objects that were returned in the buffer. 1063 llvm::Value *initialBufferLimit = CountRV.getScalarVal(); 1064 1065 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty"); 1066 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit"); 1067 1068 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy); 1069 1070 // If the limit pointer was zero to begin with, the collection is 1071 // empty; skip all this. 1072 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), 1073 EmptyBB, LoopInitBB); 1074 1075 // Otherwise, initialize the loop. 1076 EmitBlock(LoopInitBB); 1077 1078 // Save the initial mutations value. This is the value at an 1079 // address that was written into the state object by 1080 // countByEnumeratingWithState:objects:count:. 1081 llvm::Value *StateMutationsPtrPtr = 1082 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr"); 1083 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, 1084 "mutationsptr"); 1085 1086 llvm::Value *initialMutations = 1087 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations"); 1088 1089 // Start looping. This is the point we return to whenever we have a 1090 // fresh, non-empty batch of objects. 1091 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody"); 1092 EmitBlock(LoopBodyBB); 1093 1094 // The current index into the buffer. 1095 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index"); 1096 index->addIncoming(zero, LoopInitBB); 1097 1098 // The current buffer size. 1099 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count"); 1100 count->addIncoming(initialBufferLimit, LoopInitBB); 1101 1102 // Check whether the mutations value has changed from where it was 1103 // at start. StateMutationsPtr should actually be invariant between 1104 // refreshes. 1105 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr"); 1106 llvm::Value *currentMutations 1107 = Builder.CreateLoad(StateMutationsPtr, "statemutations"); 1108 1109 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated"); 1110 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated"); 1111 1112 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations), 1113 WasNotMutatedBB, WasMutatedBB); 1114 1115 // If so, call the enumeration-mutation function. 1116 EmitBlock(WasMutatedBB); 1117 llvm::Value *V = 1118 Builder.CreateBitCast(Collection, 1119 ConvertType(getContext().getObjCIdType()), 1120 "tmp"); 1121 CallArgList Args2; 1122 Args2.add(RValue::get(V), getContext().getObjCIdType()); 1123 // FIXME: We shouldn't need to get the function info here, the runtime already 1124 // should have computed it to build the function. 1125 EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2, 1126 FunctionType::ExtInfo()), 1127 EnumerationMutationFn, ReturnValueSlot(), Args2); 1128 1129 // Otherwise, or if the mutation function returns, just continue. 1130 EmitBlock(WasNotMutatedBB); 1131 1132 // Initialize the element variable. 1133 RunCleanupsScope elementVariableScope(*this); 1134 bool elementIsVariable; 1135 LValue elementLValue; 1136 QualType elementType; 1137 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) { 1138 // Initialize the variable, in case it's a __block variable or something. 1139 EmitAutoVarInit(variable); 1140 1141 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl()); 1142 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), D->getType(), 1143 VK_LValue, SourceLocation()); 1144 elementLValue = EmitLValue(&tempDRE); 1145 elementType = D->getType(); 1146 elementIsVariable = true; 1147 1148 if (D->isARCPseudoStrong()) 1149 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone); 1150 } else { 1151 elementLValue = LValue(); // suppress warning 1152 elementType = cast<Expr>(S.getElement())->getType(); 1153 elementIsVariable = false; 1154 } 1155 llvm::Type *convertedElementType = ConvertType(elementType); 1156 1157 // Fetch the buffer out of the enumeration state. 1158 // TODO: this pointer should actually be invariant between 1159 // refreshes, which would help us do certain loop optimizations. 1160 llvm::Value *StateItemsPtr = 1161 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr"); 1162 llvm::Value *EnumStateItems = 1163 Builder.CreateLoad(StateItemsPtr, "stateitems"); 1164 1165 // Fetch the value at the current index from the buffer. 1166 llvm::Value *CurrentItemPtr = 1167 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr"); 1168 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr); 1169 1170 // Cast that value to the right type. 1171 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType, 1172 "currentitem"); 1173 1174 // Make sure we have an l-value. Yes, this gets evaluated every 1175 // time through the loop. 1176 if (!elementIsVariable) { 1177 elementLValue = EmitLValue(cast<Expr>(S.getElement())); 1178 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue); 1179 } else { 1180 EmitScalarInit(CurrentItem, elementLValue); 1181 } 1182 1183 // If we do have an element variable, this assignment is the end of 1184 // its initialization. 1185 if (elementIsVariable) 1186 EmitAutoVarCleanups(variable); 1187 1188 // Perform the loop body, setting up break and continue labels. 1189 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody)); 1190 { 1191 RunCleanupsScope Scope(*this); 1192 EmitStmt(S.getBody()); 1193 } 1194 BreakContinueStack.pop_back(); 1195 1196 // Destroy the element variable now. 1197 elementVariableScope.ForceCleanup(); 1198 1199 // Check whether there are more elements. 1200 EmitBlock(AfterBody.getBlock()); 1201 1202 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch"); 1203 1204 // First we check in the local buffer. 1205 llvm::Value *indexPlusOne 1206 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1)); 1207 1208 // If we haven't overrun the buffer yet, we can continue. 1209 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count), 1210 LoopBodyBB, FetchMoreBB); 1211 1212 index->addIncoming(indexPlusOne, AfterBody.getBlock()); 1213 count->addIncoming(count, AfterBody.getBlock()); 1214 1215 // Otherwise, we have to fetch more elements. 1216 EmitBlock(FetchMoreBB); 1217 1218 CountRV = 1219 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(), 1220 getContext().UnsignedLongTy, 1221 FastEnumSel, 1222 Collection, Args); 1223 1224 // If we got a zero count, we're done. 1225 llvm::Value *refetchCount = CountRV.getScalarVal(); 1226 1227 // (note that the message send might split FetchMoreBB) 1228 index->addIncoming(zero, Builder.GetInsertBlock()); 1229 count->addIncoming(refetchCount, Builder.GetInsertBlock()); 1230 1231 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero), 1232 EmptyBB, LoopBodyBB); 1233 1234 // No more elements. 1235 EmitBlock(EmptyBB); 1236 1237 if (!elementIsVariable) { 1238 // If the element was not a declaration, set it to be null. 1239 1240 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType); 1241 elementLValue = EmitLValue(cast<Expr>(S.getElement())); 1242 EmitStoreThroughLValue(RValue::get(null), elementLValue); 1243 } 1244 1245 if (DI) { 1246 DI->setLocation(S.getSourceRange().getEnd()); 1247 DI->EmitRegionEnd(Builder); 1248 } 1249 1250 // Leave the cleanup we entered in ARC. 1251 if (getLangOptions().ObjCAutoRefCount) 1252 PopCleanupBlock(); 1253 1254 EmitBlock(LoopEnd.getBlock()); 1255 } 1256 1257 void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) { 1258 CGM.getObjCRuntime().EmitTryStmt(*this, S); 1259 } 1260 1261 void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) { 1262 CGM.getObjCRuntime().EmitThrowStmt(*this, S); 1263 } 1264 1265 void CodeGenFunction::EmitObjCAtSynchronizedStmt( 1266 const ObjCAtSynchronizedStmt &S) { 1267 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S); 1268 } 1269 1270 /// Produce the code for a CK_ObjCProduceObject. Just does a 1271 /// primitive retain. 1272 llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type, 1273 llvm::Value *value) { 1274 return EmitARCRetain(type, value); 1275 } 1276 1277 namespace { 1278 struct CallObjCRelease : EHScopeStack::Cleanup { 1279 CallObjCRelease(llvm::Value *object) : object(object) {} 1280 llvm::Value *object; 1281 1282 void Emit(CodeGenFunction &CGF, Flags flags) { 1283 CGF.EmitARCRelease(object, /*precise*/ true); 1284 } 1285 }; 1286 } 1287 1288 /// Produce the code for a CK_ObjCConsumeObject. Does a primitive 1289 /// release at the end of the full-expression. 1290 llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type, 1291 llvm::Value *object) { 1292 // If we're in a conditional branch, we need to make the cleanup 1293 // conditional. 1294 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object); 1295 return object; 1296 } 1297 1298 llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type, 1299 llvm::Value *value) { 1300 return EmitARCRetainAutorelease(type, value); 1301 } 1302 1303 1304 static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM, 1305 llvm::FunctionType *type, 1306 StringRef fnName) { 1307 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName); 1308 1309 // In -fobjc-no-arc-runtime, emit weak references to the runtime 1310 // support library. 1311 if (!CGM.getCodeGenOpts().ObjCRuntimeHasARC) 1312 if (llvm::Function *f = dyn_cast<llvm::Function>(fn)) 1313 f->setLinkage(llvm::Function::ExternalWeakLinkage); 1314 1315 return fn; 1316 } 1317 1318 /// Perform an operation having the signature 1319 /// i8* (i8*) 1320 /// where a null input causes a no-op and returns null. 1321 static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF, 1322 llvm::Value *value, 1323 llvm::Constant *&fn, 1324 StringRef fnName) { 1325 if (isa<llvm::ConstantPointerNull>(value)) return value; 1326 1327 if (!fn) { 1328 std::vector<llvm::Type*> args(1, CGF.Int8PtrTy); 1329 llvm::FunctionType *fnType = 1330 llvm::FunctionType::get(CGF.Int8PtrTy, args, false); 1331 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName); 1332 } 1333 1334 // Cast the argument to 'id'. 1335 llvm::Type *origType = value->getType(); 1336 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy); 1337 1338 // Call the function. 1339 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value); 1340 call->setDoesNotThrow(); 1341 1342 // Cast the result back to the original type. 1343 return CGF.Builder.CreateBitCast(call, origType); 1344 } 1345 1346 /// Perform an operation having the following signature: 1347 /// i8* (i8**) 1348 static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF, 1349 llvm::Value *addr, 1350 llvm::Constant *&fn, 1351 StringRef fnName) { 1352 if (!fn) { 1353 std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy); 1354 llvm::FunctionType *fnType = 1355 llvm::FunctionType::get(CGF.Int8PtrTy, args, false); 1356 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName); 1357 } 1358 1359 // Cast the argument to 'id*'. 1360 llvm::Type *origType = addr->getType(); 1361 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy); 1362 1363 // Call the function. 1364 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr); 1365 call->setDoesNotThrow(); 1366 1367 // Cast the result back to a dereference of the original type. 1368 llvm::Value *result = call; 1369 if (origType != CGF.Int8PtrPtrTy) 1370 result = CGF.Builder.CreateBitCast(result, 1371 cast<llvm::PointerType>(origType)->getElementType()); 1372 1373 return result; 1374 } 1375 1376 /// Perform an operation having the following signature: 1377 /// i8* (i8**, i8*) 1378 static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF, 1379 llvm::Value *addr, 1380 llvm::Value *value, 1381 llvm::Constant *&fn, 1382 StringRef fnName, 1383 bool ignored) { 1384 assert(cast<llvm::PointerType>(addr->getType())->getElementType() 1385 == value->getType()); 1386 1387 if (!fn) { 1388 std::vector<llvm::Type*> argTypes(2); 1389 argTypes[0] = CGF.Int8PtrPtrTy; 1390 argTypes[1] = CGF.Int8PtrTy; 1391 1392 llvm::FunctionType *fnType 1393 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false); 1394 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName); 1395 } 1396 1397 llvm::Type *origType = value->getType(); 1398 1399 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy); 1400 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy); 1401 1402 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value); 1403 result->setDoesNotThrow(); 1404 1405 if (ignored) return 0; 1406 1407 return CGF.Builder.CreateBitCast(result, origType); 1408 } 1409 1410 /// Perform an operation having the following signature: 1411 /// void (i8**, i8**) 1412 static void emitARCCopyOperation(CodeGenFunction &CGF, 1413 llvm::Value *dst, 1414 llvm::Value *src, 1415 llvm::Constant *&fn, 1416 StringRef fnName) { 1417 assert(dst->getType() == src->getType()); 1418 1419 if (!fn) { 1420 std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy); 1421 llvm::FunctionType *fnType 1422 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false); 1423 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName); 1424 } 1425 1426 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy); 1427 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy); 1428 1429 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src); 1430 result->setDoesNotThrow(); 1431 } 1432 1433 /// Produce the code to do a retain. Based on the type, calls one of: 1434 /// call i8* @objc_retain(i8* %value) 1435 /// call i8* @objc_retainBlock(i8* %value) 1436 llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) { 1437 if (type->isBlockPointerType()) 1438 return EmitARCRetainBlock(value); 1439 else 1440 return EmitARCRetainNonBlock(value); 1441 } 1442 1443 /// Retain the given object, with normal retain semantics. 1444 /// call i8* @objc_retain(i8* %value) 1445 llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) { 1446 return emitARCValueOperation(*this, value, 1447 CGM.getARCEntrypoints().objc_retain, 1448 "objc_retain"); 1449 } 1450 1451 /// Retain the given block, with _Block_copy semantics. 1452 /// call i8* @objc_retainBlock(i8* %value) 1453 llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value) { 1454 return emitARCValueOperation(*this, value, 1455 CGM.getARCEntrypoints().objc_retainBlock, 1456 "objc_retainBlock"); 1457 } 1458 1459 /// Retain the given object which is the result of a function call. 1460 /// call i8* @objc_retainAutoreleasedReturnValue(i8* %value) 1461 /// 1462 /// Yes, this function name is one character away from a different 1463 /// call with completely different semantics. 1464 llvm::Value * 1465 CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) { 1466 // Fetch the void(void) inline asm which marks that we're going to 1467 // retain the autoreleased return value. 1468 llvm::InlineAsm *&marker 1469 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker; 1470 if (!marker) { 1471 StringRef assembly 1472 = CGM.getTargetCodeGenInfo() 1473 .getARCRetainAutoreleasedReturnValueMarker(); 1474 1475 // If we have an empty assembly string, there's nothing to do. 1476 if (assembly.empty()) { 1477 1478 // Otherwise, at -O0, build an inline asm that we're going to call 1479 // in a moment. 1480 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) { 1481 llvm::FunctionType *type = 1482 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()), 1483 /*variadic*/ false); 1484 1485 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true); 1486 1487 // If we're at -O1 and above, we don't want to litter the code 1488 // with this marker yet, so leave a breadcrumb for the ARC 1489 // optimizer to pick up. 1490 } else { 1491 llvm::NamedMDNode *metadata = 1492 CGM.getModule().getOrInsertNamedMetadata( 1493 "clang.arc.retainAutoreleasedReturnValueMarker"); 1494 assert(metadata->getNumOperands() <= 1); 1495 if (metadata->getNumOperands() == 0) { 1496 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly); 1497 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string)); 1498 } 1499 } 1500 } 1501 1502 // Call the marker asm if we made one, which we do only at -O0. 1503 if (marker) Builder.CreateCall(marker); 1504 1505 return emitARCValueOperation(*this, value, 1506 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue, 1507 "objc_retainAutoreleasedReturnValue"); 1508 } 1509 1510 /// Release the given object. 1511 /// call void @objc_release(i8* %value) 1512 void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) { 1513 if (isa<llvm::ConstantPointerNull>(value)) return; 1514 1515 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release; 1516 if (!fn) { 1517 std::vector<llvm::Type*> args(1, Int8PtrTy); 1518 llvm::FunctionType *fnType = 1519 llvm::FunctionType::get(Builder.getVoidTy(), args, false); 1520 fn = createARCRuntimeFunction(CGM, fnType, "objc_release"); 1521 } 1522 1523 // Cast the argument to 'id'. 1524 value = Builder.CreateBitCast(value, Int8PtrTy); 1525 1526 // Call objc_release. 1527 llvm::CallInst *call = Builder.CreateCall(fn, value); 1528 call->setDoesNotThrow(); 1529 1530 if (!precise) { 1531 SmallVector<llvm::Value*,1> args; 1532 call->setMetadata("clang.imprecise_release", 1533 llvm::MDNode::get(Builder.getContext(), args)); 1534 } 1535 } 1536 1537 /// Store into a strong object. Always calls this: 1538 /// call void @objc_storeStrong(i8** %addr, i8* %value) 1539 llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr, 1540 llvm::Value *value, 1541 bool ignored) { 1542 assert(cast<llvm::PointerType>(addr->getType())->getElementType() 1543 == value->getType()); 1544 1545 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong; 1546 if (!fn) { 1547 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy }; 1548 llvm::FunctionType *fnType 1549 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false); 1550 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong"); 1551 } 1552 1553 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy); 1554 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy); 1555 1556 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow(); 1557 1558 if (ignored) return 0; 1559 return value; 1560 } 1561 1562 /// Store into a strong object. Sometimes calls this: 1563 /// call void @objc_storeStrong(i8** %addr, i8* %value) 1564 /// Other times, breaks it down into components. 1565 llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst, 1566 llvm::Value *newValue, 1567 bool ignored) { 1568 QualType type = dst.getType(); 1569 bool isBlock = type->isBlockPointerType(); 1570 1571 // Use a store barrier at -O0 unless this is a block type or the 1572 // lvalue is inadequately aligned. 1573 if (shouldUseFusedARCCalls() && 1574 !isBlock && 1575 !(dst.getAlignment() && dst.getAlignment() < PointerAlignInBytes)) { 1576 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored); 1577 } 1578 1579 // Otherwise, split it out. 1580 1581 // Retain the new value. 1582 newValue = EmitARCRetain(type, newValue); 1583 1584 // Read the old value. 1585 llvm::Value *oldValue = EmitLoadOfScalar(dst); 1586 1587 // Store. We do this before the release so that any deallocs won't 1588 // see the old value. 1589 EmitStoreOfScalar(newValue, dst); 1590 1591 // Finally, release the old value. 1592 EmitARCRelease(oldValue, /*precise*/ false); 1593 1594 return newValue; 1595 } 1596 1597 /// Autorelease the given object. 1598 /// call i8* @objc_autorelease(i8* %value) 1599 llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) { 1600 return emitARCValueOperation(*this, value, 1601 CGM.getARCEntrypoints().objc_autorelease, 1602 "objc_autorelease"); 1603 } 1604 1605 /// Autorelease the given object. 1606 /// call i8* @objc_autoreleaseReturnValue(i8* %value) 1607 llvm::Value * 1608 CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) { 1609 return emitARCValueOperation(*this, value, 1610 CGM.getARCEntrypoints().objc_autoreleaseReturnValue, 1611 "objc_autoreleaseReturnValue"); 1612 } 1613 1614 /// Do a fused retain/autorelease of the given object. 1615 /// call i8* @objc_retainAutoreleaseReturnValue(i8* %value) 1616 llvm::Value * 1617 CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) { 1618 return emitARCValueOperation(*this, value, 1619 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue, 1620 "objc_retainAutoreleaseReturnValue"); 1621 } 1622 1623 /// Do a fused retain/autorelease of the given object. 1624 /// call i8* @objc_retainAutorelease(i8* %value) 1625 /// or 1626 /// %retain = call i8* @objc_retainBlock(i8* %value) 1627 /// call i8* @objc_autorelease(i8* %retain) 1628 llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type, 1629 llvm::Value *value) { 1630 if (!type->isBlockPointerType()) 1631 return EmitARCRetainAutoreleaseNonBlock(value); 1632 1633 if (isa<llvm::ConstantPointerNull>(value)) return value; 1634 1635 llvm::Type *origType = value->getType(); 1636 value = Builder.CreateBitCast(value, Int8PtrTy); 1637 value = EmitARCRetainBlock(value); 1638 value = EmitARCAutorelease(value); 1639 return Builder.CreateBitCast(value, origType); 1640 } 1641 1642 /// Do a fused retain/autorelease of the given object. 1643 /// call i8* @objc_retainAutorelease(i8* %value) 1644 llvm::Value * 1645 CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) { 1646 return emitARCValueOperation(*this, value, 1647 CGM.getARCEntrypoints().objc_retainAutorelease, 1648 "objc_retainAutorelease"); 1649 } 1650 1651 /// i8* @objc_loadWeak(i8** %addr) 1652 /// Essentially objc_autorelease(objc_loadWeakRetained(addr)). 1653 llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) { 1654 return emitARCLoadOperation(*this, addr, 1655 CGM.getARCEntrypoints().objc_loadWeak, 1656 "objc_loadWeak"); 1657 } 1658 1659 /// i8* @objc_loadWeakRetained(i8** %addr) 1660 llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) { 1661 return emitARCLoadOperation(*this, addr, 1662 CGM.getARCEntrypoints().objc_loadWeakRetained, 1663 "objc_loadWeakRetained"); 1664 } 1665 1666 /// i8* @objc_storeWeak(i8** %addr, i8* %value) 1667 /// Returns %value. 1668 llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr, 1669 llvm::Value *value, 1670 bool ignored) { 1671 return emitARCStoreOperation(*this, addr, value, 1672 CGM.getARCEntrypoints().objc_storeWeak, 1673 "objc_storeWeak", ignored); 1674 } 1675 1676 /// i8* @objc_initWeak(i8** %addr, i8* %value) 1677 /// Returns %value. %addr is known to not have a current weak entry. 1678 /// Essentially equivalent to: 1679 /// *addr = nil; objc_storeWeak(addr, value); 1680 void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) { 1681 // If we're initializing to null, just write null to memory; no need 1682 // to get the runtime involved. But don't do this if optimization 1683 // is enabled, because accounting for this would make the optimizer 1684 // much more complicated. 1685 if (isa<llvm::ConstantPointerNull>(value) && 1686 CGM.getCodeGenOpts().OptimizationLevel == 0) { 1687 Builder.CreateStore(value, addr); 1688 return; 1689 } 1690 1691 emitARCStoreOperation(*this, addr, value, 1692 CGM.getARCEntrypoints().objc_initWeak, 1693 "objc_initWeak", /*ignored*/ true); 1694 } 1695 1696 /// void @objc_destroyWeak(i8** %addr) 1697 /// Essentially objc_storeWeak(addr, nil). 1698 void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) { 1699 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak; 1700 if (!fn) { 1701 std::vector<llvm::Type*> args(1, Int8PtrPtrTy); 1702 llvm::FunctionType *fnType = 1703 llvm::FunctionType::get(Builder.getVoidTy(), args, false); 1704 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak"); 1705 } 1706 1707 // Cast the argument to 'id*'. 1708 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy); 1709 1710 llvm::CallInst *call = Builder.CreateCall(fn, addr); 1711 call->setDoesNotThrow(); 1712 } 1713 1714 /// void @objc_moveWeak(i8** %dest, i8** %src) 1715 /// Disregards the current value in %dest. Leaves %src pointing to nothing. 1716 /// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)). 1717 void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) { 1718 emitARCCopyOperation(*this, dst, src, 1719 CGM.getARCEntrypoints().objc_moveWeak, 1720 "objc_moveWeak"); 1721 } 1722 1723 /// void @objc_copyWeak(i8** %dest, i8** %src) 1724 /// Disregards the current value in %dest. Essentially 1725 /// objc_release(objc_initWeak(dest, objc_readWeakRetained(src))) 1726 void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) { 1727 emitARCCopyOperation(*this, dst, src, 1728 CGM.getARCEntrypoints().objc_copyWeak, 1729 "objc_copyWeak"); 1730 } 1731 1732 /// Produce the code to do a objc_autoreleasepool_push. 1733 /// call i8* @objc_autoreleasePoolPush(void) 1734 llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() { 1735 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush; 1736 if (!fn) { 1737 llvm::FunctionType *fnType = 1738 llvm::FunctionType::get(Int8PtrTy, false); 1739 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush"); 1740 } 1741 1742 llvm::CallInst *call = Builder.CreateCall(fn); 1743 call->setDoesNotThrow(); 1744 1745 return call; 1746 } 1747 1748 /// Produce the code to do a primitive release. 1749 /// call void @objc_autoreleasePoolPop(i8* %ptr) 1750 void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) { 1751 assert(value->getType() == Int8PtrTy); 1752 1753 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop; 1754 if (!fn) { 1755 std::vector<llvm::Type*> args(1, Int8PtrTy); 1756 llvm::FunctionType *fnType = 1757 llvm::FunctionType::get(Builder.getVoidTy(), args, false); 1758 1759 // We don't want to use a weak import here; instead we should not 1760 // fall into this path. 1761 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop"); 1762 } 1763 1764 llvm::CallInst *call = Builder.CreateCall(fn, value); 1765 call->setDoesNotThrow(); 1766 } 1767 1768 /// Produce the code to do an MRR version objc_autoreleasepool_push. 1769 /// Which is: [[NSAutoreleasePool alloc] init]; 1770 /// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class. 1771 /// init is declared as: - (id) init; in its NSObject super class. 1772 /// 1773 llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() { 1774 CGObjCRuntime &Runtime = CGM.getObjCRuntime(); 1775 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder); 1776 // [NSAutoreleasePool alloc] 1777 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc"); 1778 Selector AllocSel = getContext().Selectors.getSelector(0, &II); 1779 CallArgList Args; 1780 RValue AllocRV = 1781 Runtime.GenerateMessageSend(*this, ReturnValueSlot(), 1782 getContext().getObjCIdType(), 1783 AllocSel, Receiver, Args); 1784 1785 // [Receiver init] 1786 Receiver = AllocRV.getScalarVal(); 1787 II = &CGM.getContext().Idents.get("init"); 1788 Selector InitSel = getContext().Selectors.getSelector(0, &II); 1789 RValue InitRV = 1790 Runtime.GenerateMessageSend(*this, ReturnValueSlot(), 1791 getContext().getObjCIdType(), 1792 InitSel, Receiver, Args); 1793 return InitRV.getScalarVal(); 1794 } 1795 1796 /// Produce the code to do a primitive release. 1797 /// [tmp drain]; 1798 void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) { 1799 IdentifierInfo *II = &CGM.getContext().Idents.get("drain"); 1800 Selector DrainSel = getContext().Selectors.getSelector(0, &II); 1801 CallArgList Args; 1802 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(), 1803 getContext().VoidTy, DrainSel, Arg, Args); 1804 } 1805 1806 void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF, 1807 llvm::Value *addr, 1808 QualType type) { 1809 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy"); 1810 CGF.EmitARCRelease(ptr, /*precise*/ true); 1811 } 1812 1813 void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF, 1814 llvm::Value *addr, 1815 QualType type) { 1816 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy"); 1817 CGF.EmitARCRelease(ptr, /*precise*/ false); 1818 } 1819 1820 void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF, 1821 llvm::Value *addr, 1822 QualType type) { 1823 CGF.EmitARCDestroyWeak(addr); 1824 } 1825 1826 namespace { 1827 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup { 1828 llvm::Value *Token; 1829 1830 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {} 1831 1832 void Emit(CodeGenFunction &CGF, Flags flags) { 1833 CGF.EmitObjCAutoreleasePoolPop(Token); 1834 } 1835 }; 1836 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup { 1837 llvm::Value *Token; 1838 1839 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {} 1840 1841 void Emit(CodeGenFunction &CGF, Flags flags) { 1842 CGF.EmitObjCMRRAutoreleasePoolPop(Token); 1843 } 1844 }; 1845 } 1846 1847 void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) { 1848 if (CGM.getLangOptions().ObjCAutoRefCount) 1849 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr); 1850 else 1851 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr); 1852 } 1853 1854 static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF, 1855 LValue lvalue, 1856 QualType type) { 1857 switch (type.getObjCLifetime()) { 1858 case Qualifiers::OCL_None: 1859 case Qualifiers::OCL_ExplicitNone: 1860 case Qualifiers::OCL_Strong: 1861 case Qualifiers::OCL_Autoreleasing: 1862 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(), 1863 false); 1864 1865 case Qualifiers::OCL_Weak: 1866 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()), 1867 true); 1868 } 1869 1870 llvm_unreachable("impossible lifetime!"); 1871 return TryEmitResult(); 1872 } 1873 1874 static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF, 1875 const Expr *e) { 1876 e = e->IgnoreParens(); 1877 QualType type = e->getType(); 1878 1879 // As a very special optimization, in ARC++, if the l-value is the 1880 // result of a non-volatile assignment, do a simple retain of the 1881 // result of the call to objc_storeWeak instead of reloading. 1882 if (CGF.getLangOptions().CPlusPlus && 1883 !type.isVolatileQualified() && 1884 type.getObjCLifetime() == Qualifiers::OCL_Weak && 1885 isa<BinaryOperator>(e) && 1886 cast<BinaryOperator>(e)->getOpcode() == BO_Assign) 1887 return TryEmitResult(CGF.EmitScalarExpr(e), false); 1888 1889 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type); 1890 } 1891 1892 static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF, 1893 llvm::Value *value); 1894 1895 /// Given that the given expression is some sort of call (which does 1896 /// not return retained), emit a retain following it. 1897 static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) { 1898 llvm::Value *value = CGF.EmitScalarExpr(e); 1899 return emitARCRetainAfterCall(CGF, value); 1900 } 1901 1902 static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF, 1903 llvm::Value *value) { 1904 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) { 1905 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP(); 1906 1907 // Place the retain immediately following the call. 1908 CGF.Builder.SetInsertPoint(call->getParent(), 1909 ++llvm::BasicBlock::iterator(call)); 1910 value = CGF.EmitARCRetainAutoreleasedReturnValue(value); 1911 1912 CGF.Builder.restoreIP(ip); 1913 return value; 1914 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) { 1915 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP(); 1916 1917 // Place the retain at the beginning of the normal destination block. 1918 llvm::BasicBlock *BB = invoke->getNormalDest(); 1919 CGF.Builder.SetInsertPoint(BB, BB->begin()); 1920 value = CGF.EmitARCRetainAutoreleasedReturnValue(value); 1921 1922 CGF.Builder.restoreIP(ip); 1923 return value; 1924 1925 // Bitcasts can arise because of related-result returns. Rewrite 1926 // the operand. 1927 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) { 1928 llvm::Value *operand = bitcast->getOperand(0); 1929 operand = emitARCRetainAfterCall(CGF, operand); 1930 bitcast->setOperand(0, operand); 1931 return bitcast; 1932 1933 // Generic fall-back case. 1934 } else { 1935 // Retain using the non-block variant: we never need to do a copy 1936 // of a block that's been returned to us. 1937 return CGF.EmitARCRetainNonBlock(value); 1938 } 1939 } 1940 1941 static TryEmitResult 1942 tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) { 1943 // Look through cleanups. 1944 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) { 1945 CodeGenFunction::RunCleanupsScope scope(CGF); 1946 return tryEmitARCRetainScalarExpr(CGF, cleanups->getSubExpr()); 1947 } 1948 1949 // The desired result type, if it differs from the type of the 1950 // ultimate opaque expression. 1951 llvm::Type *resultType = 0; 1952 1953 // If we're loading retained from a __strong xvalue, we can avoid 1954 // an extra retain/release pair by zeroing out the source of this 1955 // "move" operation. 1956 if (e->isXValue() && !e->getType().isConstQualified() && 1957 e->getType().getObjCLifetime() == Qualifiers::OCL_Strong) { 1958 // Emit the lvalue 1959 LValue lv = CGF.EmitLValue(e); 1960 1961 // Load the object pointer and cast it to the appropriate type. 1962 QualType exprType = e->getType(); 1963 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal(); 1964 1965 if (resultType) 1966 result = CGF.Builder.CreateBitCast(result, resultType); 1967 1968 // Set the source pointer to NULL. 1969 llvm::Value *null 1970 = llvm::ConstantPointerNull::get( 1971 cast<llvm::PointerType>(CGF.ConvertType(exprType))); 1972 CGF.EmitStoreOfScalar(null, lv); 1973 1974 return TryEmitResult(result, true); 1975 } 1976 1977 while (true) { 1978 e = e->IgnoreParens(); 1979 1980 // There's a break at the end of this if-chain; anything 1981 // that wants to keep looping has to explicitly continue. 1982 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) { 1983 switch (ce->getCastKind()) { 1984 // No-op casts don't change the type, so we just ignore them. 1985 case CK_NoOp: 1986 e = ce->getSubExpr(); 1987 continue; 1988 1989 case CK_LValueToRValue: { 1990 TryEmitResult loadResult 1991 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr()); 1992 if (resultType) { 1993 llvm::Value *value = loadResult.getPointer(); 1994 value = CGF.Builder.CreateBitCast(value, resultType); 1995 loadResult.setPointer(value); 1996 } 1997 return loadResult; 1998 } 1999 2000 // These casts can change the type, so remember that and 2001 // soldier on. We only need to remember the outermost such 2002 // cast, though. 2003 case CK_AnyPointerToObjCPointerCast: 2004 case CK_AnyPointerToBlockPointerCast: 2005 case CK_BitCast: 2006 if (!resultType) 2007 resultType = CGF.ConvertType(ce->getType()); 2008 e = ce->getSubExpr(); 2009 assert(e->getType()->hasPointerRepresentation()); 2010 continue; 2011 2012 // For consumptions, just emit the subexpression and thus elide 2013 // the retain/release pair. 2014 case CK_ObjCConsumeObject: { 2015 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr()); 2016 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType); 2017 return TryEmitResult(result, true); 2018 } 2019 2020 // For reclaims, emit the subexpression as a retained call and 2021 // skip the consumption. 2022 case CK_ObjCReclaimReturnedObject: { 2023 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr()); 2024 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType); 2025 return TryEmitResult(result, true); 2026 } 2027 2028 case CK_GetObjCProperty: { 2029 llvm::Value *result = emitARCRetainCall(CGF, ce); 2030 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType); 2031 return TryEmitResult(result, true); 2032 } 2033 2034 default: 2035 break; 2036 } 2037 2038 // Skip __extension__. 2039 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) { 2040 if (op->getOpcode() == UO_Extension) { 2041 e = op->getSubExpr(); 2042 continue; 2043 } 2044 2045 // For calls and message sends, use the retained-call logic. 2046 // Delegate inits are a special case in that they're the only 2047 // returns-retained expression that *isn't* surrounded by 2048 // a consume. 2049 } else if (isa<CallExpr>(e) || 2050 (isa<ObjCMessageExpr>(e) && 2051 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) { 2052 llvm::Value *result = emitARCRetainCall(CGF, e); 2053 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType); 2054 return TryEmitResult(result, true); 2055 } 2056 2057 // Conservatively halt the search at any other expression kind. 2058 break; 2059 } 2060 2061 // We didn't find an obvious production, so emit what we've got and 2062 // tell the caller that we didn't manage to retain. 2063 llvm::Value *result = CGF.EmitScalarExpr(e); 2064 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType); 2065 return TryEmitResult(result, false); 2066 } 2067 2068 static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF, 2069 LValue lvalue, 2070 QualType type) { 2071 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type); 2072 llvm::Value *value = result.getPointer(); 2073 if (!result.getInt()) 2074 value = CGF.EmitARCRetain(type, value); 2075 return value; 2076 } 2077 2078 /// EmitARCRetainScalarExpr - Semantically equivalent to 2079 /// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a 2080 /// best-effort attempt to peephole expressions that naturally produce 2081 /// retained objects. 2082 llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) { 2083 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e); 2084 llvm::Value *value = result.getPointer(); 2085 if (!result.getInt()) 2086 value = EmitARCRetain(e->getType(), value); 2087 return value; 2088 } 2089 2090 llvm::Value * 2091 CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) { 2092 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e); 2093 llvm::Value *value = result.getPointer(); 2094 if (result.getInt()) 2095 value = EmitARCAutorelease(value); 2096 else 2097 value = EmitARCRetainAutorelease(e->getType(), value); 2098 return value; 2099 } 2100 2101 std::pair<LValue,llvm::Value*> 2102 CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e, 2103 bool ignored) { 2104 // Evaluate the RHS first. 2105 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS()); 2106 llvm::Value *value = result.getPointer(); 2107 2108 bool hasImmediateRetain = result.getInt(); 2109 2110 // If we didn't emit a retained object, and the l-value is of block 2111 // type, then we need to emit the block-retain immediately in case 2112 // it invalidates the l-value. 2113 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) { 2114 value = EmitARCRetainBlock(value); 2115 hasImmediateRetain = true; 2116 } 2117 2118 LValue lvalue = EmitLValue(e->getLHS()); 2119 2120 // If the RHS was emitted retained, expand this. 2121 if (hasImmediateRetain) { 2122 llvm::Value *oldValue = 2123 EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatileQualified(), 2124 lvalue.getAlignment(), e->getType(), 2125 lvalue.getTBAAInfo()); 2126 EmitStoreOfScalar(value, lvalue.getAddress(), 2127 lvalue.isVolatileQualified(), lvalue.getAlignment(), 2128 e->getType(), lvalue.getTBAAInfo()); 2129 EmitARCRelease(oldValue, /*precise*/ false); 2130 } else { 2131 value = EmitARCStoreStrong(lvalue, value, ignored); 2132 } 2133 2134 return std::pair<LValue,llvm::Value*>(lvalue, value); 2135 } 2136 2137 std::pair<LValue,llvm::Value*> 2138 CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) { 2139 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS()); 2140 LValue lvalue = EmitLValue(e->getLHS()); 2141 2142 EmitStoreOfScalar(value, lvalue.getAddress(), 2143 lvalue.isVolatileQualified(), lvalue.getAlignment(), 2144 e->getType(), lvalue.getTBAAInfo()); 2145 2146 return std::pair<LValue,llvm::Value*>(lvalue, value); 2147 } 2148 2149 void CodeGenFunction::EmitObjCAutoreleasePoolStmt( 2150 const ObjCAutoreleasePoolStmt &ARPS) { 2151 const Stmt *subStmt = ARPS.getSubStmt(); 2152 const CompoundStmt &S = cast<CompoundStmt>(*subStmt); 2153 2154 CGDebugInfo *DI = getDebugInfo(); 2155 if (DI) { 2156 DI->setLocation(S.getLBracLoc()); 2157 DI->EmitRegionStart(Builder); 2158 } 2159 2160 // Keep track of the current cleanup stack depth. 2161 RunCleanupsScope Scope(*this); 2162 if (CGM.getCodeGenOpts().ObjCRuntimeHasARC) { 2163 llvm::Value *token = EmitObjCAutoreleasePoolPush(); 2164 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token); 2165 } else { 2166 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush(); 2167 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token); 2168 } 2169 2170 for (CompoundStmt::const_body_iterator I = S.body_begin(), 2171 E = S.body_end(); I != E; ++I) 2172 EmitStmt(*I); 2173 2174 if (DI) { 2175 DI->setLocation(S.getRBracLoc()); 2176 DI->EmitRegionEnd(Builder); 2177 } 2178 } 2179 2180 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object, 2181 /// make sure it survives garbage collection until this point. 2182 void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) { 2183 // We just use an inline assembly. 2184 llvm::FunctionType *extenderType 2185 = llvm::FunctionType::get(VoidTy, VoidPtrTy, /*variadic*/ false); 2186 llvm::Value *extender 2187 = llvm::InlineAsm::get(extenderType, 2188 /* assembly */ "", 2189 /* constraints */ "r", 2190 /* side effects */ true); 2191 2192 object = Builder.CreateBitCast(object, VoidPtrTy); 2193 Builder.CreateCall(extender, object)->setDoesNotThrow(); 2194 } 2195 2196 CGObjCRuntime::~CGObjCRuntime() {} 2197