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/Support/CallSite.h" 25 #include "llvm/IR/DataLayout.h" 26 #include "llvm/IR/InlineAsm.h" 27 using namespace clang; 28 using namespace CodeGen; 29 30 typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult; 31 static TryEmitResult 32 tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e); 33 static RValue AdjustRelatedResultType(CodeGenFunction &CGF, 34 QualType ET, 35 const ObjCMethodDecl *Method, 36 RValue Result); 37 38 /// Given the address of a variable of pointer type, find the correct 39 /// null to store into it. 40 static llvm::Constant *getNullForVariable(llvm::Value *addr) { 41 llvm::Type *type = 42 cast<llvm::PointerType>(addr->getType())->getElementType(); 43 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type)); 44 } 45 46 /// Emits an instance of NSConstantString representing the object. 47 llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E) 48 { 49 llvm::Constant *C = 50 CGM.getObjCRuntime().GenerateConstantString(E->getString()); 51 // FIXME: This bitcast should just be made an invariant on the Runtime. 52 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType())); 53 } 54 55 /// EmitObjCBoxedExpr - This routine generates code to call 56 /// the appropriate expression boxing method. This will either be 57 /// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:]. 58 /// 59 llvm::Value * 60 CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) { 61 // Generate the correct selector for this literal's concrete type. 62 const Expr *SubExpr = E->getSubExpr(); 63 // Get the method. 64 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod(); 65 assert(BoxingMethod && "BoxingMethod is null"); 66 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method"); 67 Selector Sel = BoxingMethod->getSelector(); 68 69 // Generate a reference to the class pointer, which will be the receiver. 70 // Assumes that the method was introduced in the class that should be 71 // messaged (avoids pulling it out of the result type). 72 CGObjCRuntime &Runtime = CGM.getObjCRuntime(); 73 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface(); 74 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl); 75 76 const ParmVarDecl *argDecl = *BoxingMethod->param_begin(); 77 QualType ArgQT = argDecl->getType().getUnqualifiedType(); 78 RValue RV = EmitAnyExpr(SubExpr); 79 CallArgList Args; 80 Args.add(RV, ArgQT); 81 82 RValue result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(), 83 BoxingMethod->getResultType(), Sel, Receiver, Args, 84 ClassDecl, BoxingMethod); 85 return Builder.CreateBitCast(result.getScalarVal(), 86 ConvertType(E->getType())); 87 } 88 89 llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E, 90 const ObjCMethodDecl *MethodWithObjects) { 91 ASTContext &Context = CGM.getContext(); 92 const ObjCDictionaryLiteral *DLE = 0; 93 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E); 94 if (!ALE) 95 DLE = cast<ObjCDictionaryLiteral>(E); 96 97 // Compute the type of the array we're initializing. 98 uint64_t NumElements = 99 ALE ? ALE->getNumElements() : DLE->getNumElements(); 100 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()), 101 NumElements); 102 QualType ElementType = Context.getObjCIdType().withConst(); 103 QualType ElementArrayType 104 = Context.getConstantArrayType(ElementType, APNumElements, 105 ArrayType::Normal, /*IndexTypeQuals=*/0); 106 107 // Allocate the temporary array(s). 108 llvm::Value *Objects = CreateMemTemp(ElementArrayType, "objects"); 109 llvm::Value *Keys = 0; 110 if (DLE) 111 Keys = CreateMemTemp(ElementArrayType, "keys"); 112 113 // In ARC, we may need to do extra work to keep all the keys and 114 // values alive until after the call. 115 SmallVector<llvm::Value *, 16> NeededObjects; 116 bool TrackNeededObjects = 117 (getLangOpts().ObjCAutoRefCount && 118 CGM.getCodeGenOpts().OptimizationLevel != 0); 119 120 // Perform the actual initialialization of the array(s). 121 for (uint64_t i = 0; i < NumElements; i++) { 122 if (ALE) { 123 // Emit the element and store it to the appropriate array slot. 124 const Expr *Rhs = ALE->getElement(i); 125 LValue LV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i), 126 ElementType, 127 Context.getTypeAlignInChars(Rhs->getType()), 128 Context); 129 130 llvm::Value *value = EmitScalarExpr(Rhs); 131 EmitStoreThroughLValue(RValue::get(value), LV, true); 132 if (TrackNeededObjects) { 133 NeededObjects.push_back(value); 134 } 135 } else { 136 // Emit the key and store it to the appropriate array slot. 137 const Expr *Key = DLE->getKeyValueElement(i).Key; 138 LValue KeyLV = LValue::MakeAddr(Builder.CreateStructGEP(Keys, i), 139 ElementType, 140 Context.getTypeAlignInChars(Key->getType()), 141 Context); 142 llvm::Value *keyValue = EmitScalarExpr(Key); 143 EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true); 144 145 // Emit the value and store it to the appropriate array slot. 146 const Expr *Value = DLE->getKeyValueElement(i).Value; 147 LValue ValueLV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i), 148 ElementType, 149 Context.getTypeAlignInChars(Value->getType()), 150 Context); 151 llvm::Value *valueValue = EmitScalarExpr(Value); 152 EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true); 153 if (TrackNeededObjects) { 154 NeededObjects.push_back(keyValue); 155 NeededObjects.push_back(valueValue); 156 } 157 } 158 } 159 160 // Generate the argument list. 161 CallArgList Args; 162 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin(); 163 const ParmVarDecl *argDecl = *PI++; 164 QualType ArgQT = argDecl->getType().getUnqualifiedType(); 165 Args.add(RValue::get(Objects), ArgQT); 166 if (DLE) { 167 argDecl = *PI++; 168 ArgQT = argDecl->getType().getUnqualifiedType(); 169 Args.add(RValue::get(Keys), ArgQT); 170 } 171 argDecl = *PI; 172 ArgQT = argDecl->getType().getUnqualifiedType(); 173 llvm::Value *Count = 174 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements); 175 Args.add(RValue::get(Count), ArgQT); 176 177 // Generate a reference to the class pointer, which will be the receiver. 178 Selector Sel = MethodWithObjects->getSelector(); 179 QualType ResultType = E->getType(); 180 const ObjCObjectPointerType *InterfacePointerType 181 = ResultType->getAsObjCInterfacePointerType(); 182 ObjCInterfaceDecl *Class 183 = InterfacePointerType->getObjectType()->getInterface(); 184 CGObjCRuntime &Runtime = CGM.getObjCRuntime(); 185 llvm::Value *Receiver = Runtime.GetClass(*this, Class); 186 187 // Generate the message send. 188 RValue result 189 = Runtime.GenerateMessageSend(*this, ReturnValueSlot(), 190 MethodWithObjects->getResultType(), 191 Sel, 192 Receiver, Args, Class, 193 MethodWithObjects); 194 195 // The above message send needs these objects, but in ARC they are 196 // passed in a buffer that is essentially __unsafe_unretained. 197 // Therefore we must prevent the optimizer from releasing them until 198 // after the call. 199 if (TrackNeededObjects) { 200 EmitARCIntrinsicUse(NeededObjects); 201 } 202 203 return Builder.CreateBitCast(result.getScalarVal(), 204 ConvertType(E->getType())); 205 } 206 207 llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) { 208 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod()); 209 } 210 211 llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral( 212 const ObjCDictionaryLiteral *E) { 213 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod()); 214 } 215 216 /// Emit a selector. 217 llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) { 218 // Untyped selector. 219 // Note that this implementation allows for non-constant strings to be passed 220 // as arguments to @selector(). Currently, the only thing preventing this 221 // behaviour is the type checking in the front end. 222 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector()); 223 } 224 225 llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) { 226 // FIXME: This should pass the Decl not the name. 227 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol()); 228 } 229 230 /// \brief Adjust the type of the result of an Objective-C message send 231 /// expression when the method has a related result type. 232 static RValue AdjustRelatedResultType(CodeGenFunction &CGF, 233 QualType ExpT, 234 const ObjCMethodDecl *Method, 235 RValue Result) { 236 if (!Method) 237 return Result; 238 239 if (!Method->hasRelatedResultType() || 240 CGF.getContext().hasSameType(ExpT, Method->getResultType()) || 241 !Result.isScalar()) 242 return Result; 243 244 // We have applied a related result type. Cast the rvalue appropriately. 245 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(), 246 CGF.ConvertType(ExpT))); 247 } 248 249 /// Decide whether to extend the lifetime of the receiver of a 250 /// returns-inner-pointer message. 251 static bool 252 shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) { 253 switch (message->getReceiverKind()) { 254 255 // For a normal instance message, we should extend unless the 256 // receiver is loaded from a variable with precise lifetime. 257 case ObjCMessageExpr::Instance: { 258 const Expr *receiver = message->getInstanceReceiver(); 259 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver); 260 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true; 261 receiver = ice->getSubExpr()->IgnoreParens(); 262 263 // Only __strong variables. 264 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 265 return true; 266 267 // All ivars and fields have precise lifetime. 268 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver)) 269 return false; 270 271 // Otherwise, check for variables. 272 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr()); 273 if (!declRef) return true; 274 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl()); 275 if (!var) return true; 276 277 // All variables have precise lifetime except local variables with 278 // automatic storage duration that aren't specially marked. 279 return (var->hasLocalStorage() && 280 !var->hasAttr<ObjCPreciseLifetimeAttr>()); 281 } 282 283 case ObjCMessageExpr::Class: 284 case ObjCMessageExpr::SuperClass: 285 // It's never necessary for class objects. 286 return false; 287 288 case ObjCMessageExpr::SuperInstance: 289 // We generally assume that 'self' lives throughout a method call. 290 return false; 291 } 292 293 llvm_unreachable("invalid receiver kind"); 294 } 295 296 RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E, 297 ReturnValueSlot Return) { 298 // Only the lookup mechanism and first two arguments of the method 299 // implementation vary between runtimes. We can get the receiver and 300 // arguments in generic code. 301 302 bool isDelegateInit = E->isDelegateInitCall(); 303 304 const ObjCMethodDecl *method = E->getMethodDecl(); 305 306 // We don't retain the receiver in delegate init calls, and this is 307 // safe because the receiver value is always loaded from 'self', 308 // which we zero out. We don't want to Block_copy block receivers, 309 // though. 310 bool retainSelf = 311 (!isDelegateInit && 312 CGM.getLangOpts().ObjCAutoRefCount && 313 method && 314 method->hasAttr<NSConsumesSelfAttr>()); 315 316 CGObjCRuntime &Runtime = CGM.getObjCRuntime(); 317 bool isSuperMessage = false; 318 bool isClassMessage = false; 319 ObjCInterfaceDecl *OID = 0; 320 // Find the receiver 321 QualType ReceiverType; 322 llvm::Value *Receiver = 0; 323 switch (E->getReceiverKind()) { 324 case ObjCMessageExpr::Instance: 325 ReceiverType = E->getInstanceReceiver()->getType(); 326 if (retainSelf) { 327 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this, 328 E->getInstanceReceiver()); 329 Receiver = ter.getPointer(); 330 if (ter.getInt()) retainSelf = false; 331 } else 332 Receiver = EmitScalarExpr(E->getInstanceReceiver()); 333 break; 334 335 case ObjCMessageExpr::Class: { 336 ReceiverType = E->getClassReceiver(); 337 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>(); 338 assert(ObjTy && "Invalid Objective-C class message send"); 339 OID = ObjTy->getInterface(); 340 assert(OID && "Invalid Objective-C class message send"); 341 Receiver = Runtime.GetClass(*this, OID); 342 isClassMessage = true; 343 break; 344 } 345 346 case ObjCMessageExpr::SuperInstance: 347 ReceiverType = E->getSuperType(); 348 Receiver = LoadObjCSelf(); 349 isSuperMessage = true; 350 break; 351 352 case ObjCMessageExpr::SuperClass: 353 ReceiverType = E->getSuperType(); 354 Receiver = LoadObjCSelf(); 355 isSuperMessage = true; 356 isClassMessage = true; 357 break; 358 } 359 360 if (retainSelf) 361 Receiver = EmitARCRetainNonBlock(Receiver); 362 363 // In ARC, we sometimes want to "extend the lifetime" 364 // (i.e. retain+autorelease) of receivers of returns-inner-pointer 365 // messages. 366 if (getLangOpts().ObjCAutoRefCount && method && 367 method->hasAttr<ObjCReturnsInnerPointerAttr>() && 368 shouldExtendReceiverForInnerPointerMessage(E)) 369 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver); 370 371 QualType ResultType = 372 method ? method->getResultType() : E->getType(); 373 374 CallArgList Args; 375 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end()); 376 377 // For delegate init calls in ARC, do an unsafe store of null into 378 // self. This represents the call taking direct ownership of that 379 // value. We have to do this after emitting the other call 380 // arguments because they might also reference self, but we don't 381 // have to worry about any of them modifying self because that would 382 // be an undefined read and write of an object in unordered 383 // expressions. 384 if (isDelegateInit) { 385 assert(getLangOpts().ObjCAutoRefCount && 386 "delegate init calls should only be marked in ARC"); 387 388 // Do an unsafe store of null into self. 389 llvm::Value *selfAddr = 390 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()]; 391 assert(selfAddr && "no self entry for a delegate init call?"); 392 393 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr); 394 } 395 396 RValue result; 397 if (isSuperMessage) { 398 // super is only valid in an Objective-C method 399 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl); 400 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext()); 401 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType, 402 E->getSelector(), 403 OMD->getClassInterface(), 404 isCategoryImpl, 405 Receiver, 406 isClassMessage, 407 Args, 408 method); 409 } else { 410 result = Runtime.GenerateMessageSend(*this, Return, ResultType, 411 E->getSelector(), 412 Receiver, Args, OID, 413 method); 414 } 415 416 // For delegate init calls in ARC, implicitly store the result of 417 // the call back into self. This takes ownership of the value. 418 if (isDelegateInit) { 419 llvm::Value *selfAddr = 420 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()]; 421 llvm::Value *newSelf = result.getScalarVal(); 422 423 // The delegate return type isn't necessarily a matching type; in 424 // fact, it's quite likely to be 'id'. 425 llvm::Type *selfTy = 426 cast<llvm::PointerType>(selfAddr->getType())->getElementType(); 427 newSelf = Builder.CreateBitCast(newSelf, selfTy); 428 429 Builder.CreateStore(newSelf, selfAddr); 430 } 431 432 return AdjustRelatedResultType(*this, E->getType(), method, result); 433 } 434 435 namespace { 436 struct FinishARCDealloc : EHScopeStack::Cleanup { 437 void Emit(CodeGenFunction &CGF, Flags flags) { 438 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl); 439 440 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext()); 441 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 442 if (!iface->getSuperClass()) return; 443 444 bool isCategory = isa<ObjCCategoryImplDecl>(impl); 445 446 // Call [super dealloc] if we have a superclass. 447 llvm::Value *self = CGF.LoadObjCSelf(); 448 449 CallArgList args; 450 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(), 451 CGF.getContext().VoidTy, 452 method->getSelector(), 453 iface, 454 isCategory, 455 self, 456 /*is class msg*/ false, 457 args, 458 method); 459 } 460 }; 461 } 462 463 /// StartObjCMethod - Begin emission of an ObjCMethod. This generates 464 /// the LLVM function and sets the other context used by 465 /// CodeGenFunction. 466 void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD, 467 const ObjCContainerDecl *CD, 468 SourceLocation StartLoc) { 469 FunctionArgList args; 470 // Check if we should generate debug info for this method. 471 if (!OMD->hasAttr<NoDebugAttr>()) 472 maybeInitializeDebugInfo(); 473 474 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD); 475 476 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD); 477 CGM.SetInternalFunctionAttributes(OMD, Fn, FI); 478 479 args.push_back(OMD->getSelfDecl()); 480 args.push_back(OMD->getCmdDecl()); 481 482 for (ObjCMethodDecl::param_const_iterator PI = OMD->param_begin(), 483 E = OMD->param_end(); PI != E; ++PI) 484 args.push_back(*PI); 485 486 CurGD = OMD; 487 488 StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc); 489 490 // In ARC, certain methods get an extra cleanup. 491 if (CGM.getLangOpts().ObjCAutoRefCount && 492 OMD->isInstanceMethod() && 493 OMD->getSelector().isUnarySelector()) { 494 const IdentifierInfo *ident = 495 OMD->getSelector().getIdentifierInfoForSlot(0); 496 if (ident->isStr("dealloc")) 497 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind()); 498 } 499 } 500 501 static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF, 502 LValue lvalue, QualType type); 503 504 /// Generate an Objective-C method. An Objective-C method is a C function with 505 /// its pointer, name, and types registered in the class struture. 506 void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) { 507 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart()); 508 EmitStmt(OMD->getBody()); 509 FinishFunction(OMD->getBodyRBrace()); 510 } 511 512 /// emitStructGetterCall - Call the runtime function to load a property 513 /// into the return value slot. 514 static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar, 515 bool isAtomic, bool hasStrong) { 516 ASTContext &Context = CGF.getContext(); 517 518 llvm::Value *src = 519 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), 520 ivar, 0).getAddress(); 521 522 // objc_copyStruct (ReturnValue, &structIvar, 523 // sizeof (Type of Ivar), isAtomic, false); 524 CallArgList args; 525 526 llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy); 527 args.add(RValue::get(dest), Context.VoidPtrTy); 528 529 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy); 530 args.add(RValue::get(src), Context.VoidPtrTy); 531 532 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType()); 533 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType()); 534 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy); 535 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy); 536 537 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction(); 538 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(Context.VoidTy, args, 539 FunctionType::ExtInfo(), 540 RequiredArgs::All), 541 fn, ReturnValueSlot(), args); 542 } 543 544 /// Determine whether the given architecture supports unaligned atomic 545 /// accesses. They don't have to be fast, just faster than a function 546 /// call and a mutex. 547 static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) { 548 // FIXME: Allow unaligned atomic load/store on x86. (It is not 549 // currently supported by the backend.) 550 return 0; 551 } 552 553 /// Return the maximum size that permits atomic accesses for the given 554 /// architecture. 555 static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM, 556 llvm::Triple::ArchType arch) { 557 // ARM has 8-byte atomic accesses, but it's not clear whether we 558 // want to rely on them here. 559 560 // In the default case, just assume that any size up to a pointer is 561 // fine given adequate alignment. 562 return CharUnits::fromQuantity(CGM.PointerSizeInBytes); 563 } 564 565 namespace { 566 class PropertyImplStrategy { 567 public: 568 enum StrategyKind { 569 /// The 'native' strategy is to use the architecture's provided 570 /// reads and writes. 571 Native, 572 573 /// Use objc_setProperty and objc_getProperty. 574 GetSetProperty, 575 576 /// Use objc_setProperty for the setter, but use expression 577 /// evaluation for the getter. 578 SetPropertyAndExpressionGet, 579 580 /// Use objc_copyStruct. 581 CopyStruct, 582 583 /// The 'expression' strategy is to emit normal assignment or 584 /// lvalue-to-rvalue expressions. 585 Expression 586 }; 587 588 StrategyKind getKind() const { return StrategyKind(Kind); } 589 590 bool hasStrongMember() const { return HasStrong; } 591 bool isAtomic() const { return IsAtomic; } 592 bool isCopy() const { return IsCopy; } 593 594 CharUnits getIvarSize() const { return IvarSize; } 595 CharUnits getIvarAlignment() const { return IvarAlignment; } 596 597 PropertyImplStrategy(CodeGenModule &CGM, 598 const ObjCPropertyImplDecl *propImpl); 599 600 private: 601 unsigned Kind : 8; 602 unsigned IsAtomic : 1; 603 unsigned IsCopy : 1; 604 unsigned HasStrong : 1; 605 606 CharUnits IvarSize; 607 CharUnits IvarAlignment; 608 }; 609 } 610 611 /// Pick an implementation strategy for the given property synthesis. 612 PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM, 613 const ObjCPropertyImplDecl *propImpl) { 614 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl(); 615 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind(); 616 617 IsCopy = (setterKind == ObjCPropertyDecl::Copy); 618 IsAtomic = prop->isAtomic(); 619 HasStrong = false; // doesn't matter here. 620 621 // Evaluate the ivar's size and alignment. 622 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl(); 623 QualType ivarType = ivar->getType(); 624 llvm::tie(IvarSize, IvarAlignment) 625 = CGM.getContext().getTypeInfoInChars(ivarType); 626 627 // If we have a copy property, we always have to use getProperty/setProperty. 628 // TODO: we could actually use setProperty and an expression for non-atomics. 629 if (IsCopy) { 630 Kind = GetSetProperty; 631 return; 632 } 633 634 // Handle retain. 635 if (setterKind == ObjCPropertyDecl::Retain) { 636 // In GC-only, there's nothing special that needs to be done. 637 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) { 638 // fallthrough 639 640 // In ARC, if the property is non-atomic, use expression emission, 641 // which translates to objc_storeStrong. This isn't required, but 642 // it's slightly nicer. 643 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) { 644 // Using standard expression emission for the setter is only 645 // acceptable if the ivar is __strong, which won't be true if 646 // the property is annotated with __attribute__((NSObject)). 647 // TODO: falling all the way back to objc_setProperty here is 648 // just laziness, though; we could still use objc_storeStrong 649 // if we hacked it right. 650 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong) 651 Kind = Expression; 652 else 653 Kind = SetPropertyAndExpressionGet; 654 return; 655 656 // Otherwise, we need to at least use setProperty. However, if 657 // the property isn't atomic, we can use normal expression 658 // emission for the getter. 659 } else if (!IsAtomic) { 660 Kind = SetPropertyAndExpressionGet; 661 return; 662 663 // Otherwise, we have to use both setProperty and getProperty. 664 } else { 665 Kind = GetSetProperty; 666 return; 667 } 668 } 669 670 // If we're not atomic, just use expression accesses. 671 if (!IsAtomic) { 672 Kind = Expression; 673 return; 674 } 675 676 // Properties on bitfield ivars need to be emitted using expression 677 // accesses even if they're nominally atomic. 678 if (ivar->isBitField()) { 679 Kind = Expression; 680 return; 681 } 682 683 // GC-qualified or ARC-qualified ivars need to be emitted as 684 // expressions. This actually works out to being atomic anyway, 685 // except for ARC __strong, but that should trigger the above code. 686 if (ivarType.hasNonTrivialObjCLifetime() || 687 (CGM.getLangOpts().getGC() && 688 CGM.getContext().getObjCGCAttrKind(ivarType))) { 689 Kind = Expression; 690 return; 691 } 692 693 // Compute whether the ivar has strong members. 694 if (CGM.getLangOpts().getGC()) 695 if (const RecordType *recordType = ivarType->getAs<RecordType>()) 696 HasStrong = recordType->getDecl()->hasObjectMember(); 697 698 // We can never access structs with object members with a native 699 // access, because we need to use write barriers. This is what 700 // objc_copyStruct is for. 701 if (HasStrong) { 702 Kind = CopyStruct; 703 return; 704 } 705 706 // Otherwise, this is target-dependent and based on the size and 707 // alignment of the ivar. 708 709 // If the size of the ivar is not a power of two, give up. We don't 710 // want to get into the business of doing compare-and-swaps. 711 if (!IvarSize.isPowerOfTwo()) { 712 Kind = CopyStruct; 713 return; 714 } 715 716 llvm::Triple::ArchType arch = 717 CGM.getTarget().getTriple().getArch(); 718 719 // Most architectures require memory to fit within a single cache 720 // line, so the alignment has to be at least the size of the access. 721 // Otherwise we have to grab a lock. 722 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) { 723 Kind = CopyStruct; 724 return; 725 } 726 727 // If the ivar's size exceeds the architecture's maximum atomic 728 // access size, we have to use CopyStruct. 729 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) { 730 Kind = CopyStruct; 731 return; 732 } 733 734 // Otherwise, we can use native loads and stores. 735 Kind = Native; 736 } 737 738 /// \brief Generate an Objective-C property getter function. 739 /// 740 /// The given Decl must be an ObjCImplementationDecl. \@synthesize 741 /// is illegal within a category. 742 void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP, 743 const ObjCPropertyImplDecl *PID) { 744 llvm::Constant *AtomicHelperFn = 745 GenerateObjCAtomicGetterCopyHelperFunction(PID); 746 const ObjCPropertyDecl *PD = PID->getPropertyDecl(); 747 ObjCMethodDecl *OMD = PD->getGetterMethodDecl(); 748 assert(OMD && "Invalid call to generate getter (empty method)"); 749 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart()); 750 751 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn); 752 753 FinishFunction(); 754 } 755 756 static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) { 757 const Expr *getter = propImpl->getGetterCXXConstructor(); 758 if (!getter) return true; 759 760 // Sema only makes only of these when the ivar has a C++ class type, 761 // so the form is pretty constrained. 762 763 // If the property has a reference type, we might just be binding a 764 // reference, in which case the result will be a gl-value. We should 765 // treat this as a non-trivial operation. 766 if (getter->isGLValue()) 767 return false; 768 769 // If we selected a trivial copy-constructor, we're okay. 770 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter)) 771 return (construct->getConstructor()->isTrivial()); 772 773 // The constructor might require cleanups (in which case it's never 774 // trivial). 775 assert(isa<ExprWithCleanups>(getter)); 776 return false; 777 } 778 779 /// emitCPPObjectAtomicGetterCall - Call the runtime function to 780 /// copy the ivar into the resturn slot. 781 static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF, 782 llvm::Value *returnAddr, 783 ObjCIvarDecl *ivar, 784 llvm::Constant *AtomicHelperFn) { 785 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar, 786 // AtomicHelperFn); 787 CallArgList args; 788 789 // The 1st argument is the return Slot. 790 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy); 791 792 // The 2nd argument is the address of the ivar. 793 llvm::Value *ivarAddr = 794 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), 795 CGF.LoadObjCSelf(), ivar, 0).getAddress(); 796 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy); 797 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy); 798 799 // Third argument is the helper function. 800 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy); 801 802 llvm::Value *copyCppAtomicObjectFn = 803 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction(); 804 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy, 805 args, 806 FunctionType::ExtInfo(), 807 RequiredArgs::All), 808 copyCppAtomicObjectFn, ReturnValueSlot(), args); 809 } 810 811 void 812 CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl, 813 const ObjCPropertyImplDecl *propImpl, 814 const ObjCMethodDecl *GetterMethodDecl, 815 llvm::Constant *AtomicHelperFn) { 816 // If there's a non-trivial 'get' expression, we just have to emit that. 817 if (!hasTrivialGetExpr(propImpl)) { 818 if (!AtomicHelperFn) { 819 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(), 820 /*nrvo*/ 0); 821 EmitReturnStmt(ret); 822 } 823 else { 824 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl(); 825 emitCPPObjectAtomicGetterCall(*this, ReturnValue, 826 ivar, AtomicHelperFn); 827 } 828 return; 829 } 830 831 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl(); 832 QualType propType = prop->getType(); 833 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl(); 834 835 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl(); 836 837 // Pick an implementation strategy. 838 PropertyImplStrategy strategy(CGM, propImpl); 839 switch (strategy.getKind()) { 840 case PropertyImplStrategy::Native: { 841 // We don't need to do anything for a zero-size struct. 842 if (strategy.getIvarSize().isZero()) 843 return; 844 845 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0); 846 847 // Currently, all atomic accesses have to be through integer 848 // types, so there's no point in trying to pick a prettier type. 849 llvm::Type *bitcastType = 850 llvm::Type::getIntNTy(getLLVMContext(), 851 getContext().toBits(strategy.getIvarSize())); 852 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay 853 854 // Perform an atomic load. This does not impose ordering constraints. 855 llvm::Value *ivarAddr = LV.getAddress(); 856 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType); 857 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load"); 858 load->setAlignment(strategy.getIvarAlignment().getQuantity()); 859 load->setAtomic(llvm::Unordered); 860 861 // Store that value into the return address. Doing this with a 862 // bitcast is likely to produce some pretty ugly IR, but it's not 863 // the *most* terrible thing in the world. 864 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType)); 865 866 // Make sure we don't do an autorelease. 867 AutoreleaseResult = false; 868 return; 869 } 870 871 case PropertyImplStrategy::GetSetProperty: { 872 llvm::Value *getPropertyFn = 873 CGM.getObjCRuntime().GetPropertyGetFunction(); 874 if (!getPropertyFn) { 875 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy"); 876 return; 877 } 878 879 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true). 880 // FIXME: Can't this be simpler? This might even be worse than the 881 // corresponding gcc code. 882 llvm::Value *cmd = 883 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd"); 884 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy); 885 llvm::Value *ivarOffset = 886 EmitIvarOffset(classImpl->getClassInterface(), ivar); 887 888 CallArgList args; 889 args.add(RValue::get(self), getContext().getObjCIdType()); 890 args.add(RValue::get(cmd), getContext().getObjCSelType()); 891 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType()); 892 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())), 893 getContext().BoolTy); 894 895 // FIXME: We shouldn't need to get the function info here, the 896 // runtime already should have computed it to build the function. 897 RValue RV = EmitCall(getTypes().arrangeFreeFunctionCall(propType, args, 898 FunctionType::ExtInfo(), 899 RequiredArgs::All), 900 getPropertyFn, ReturnValueSlot(), args); 901 902 // We need to fix the type here. Ivars with copy & retain are 903 // always objects so we don't need to worry about complex or 904 // aggregates. 905 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(), 906 getTypes().ConvertType(getterMethod->getResultType()))); 907 908 EmitReturnOfRValue(RV, propType); 909 910 // objc_getProperty does an autorelease, so we should suppress ours. 911 AutoreleaseResult = false; 912 913 return; 914 } 915 916 case PropertyImplStrategy::CopyStruct: 917 emitStructGetterCall(*this, ivar, strategy.isAtomic(), 918 strategy.hasStrongMember()); 919 return; 920 921 case PropertyImplStrategy::Expression: 922 case PropertyImplStrategy::SetPropertyAndExpressionGet: { 923 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0); 924 925 QualType ivarType = ivar->getType(); 926 switch (getEvaluationKind(ivarType)) { 927 case TEK_Complex: { 928 ComplexPairTy pair = EmitLoadOfComplex(LV); 929 EmitStoreOfComplex(pair, 930 MakeNaturalAlignAddrLValue(ReturnValue, ivarType), 931 /*init*/ true); 932 return; 933 } 934 case TEK_Aggregate: 935 // The return value slot is guaranteed to not be aliased, but 936 // that's not necessarily the same as "on the stack", so 937 // we still potentially need objc_memmove_collectable. 938 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType); 939 return; 940 case TEK_Scalar: { 941 llvm::Value *value; 942 if (propType->isReferenceType()) { 943 value = LV.getAddress(); 944 } else { 945 // We want to load and autoreleaseReturnValue ARC __weak ivars. 946 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) { 947 value = emitARCRetainLoadOfScalar(*this, LV, ivarType); 948 949 // Otherwise we want to do a simple load, suppressing the 950 // final autorelease. 951 } else { 952 value = EmitLoadOfLValue(LV).getScalarVal(); 953 AutoreleaseResult = false; 954 } 955 956 value = Builder.CreateBitCast(value, ConvertType(propType)); 957 value = Builder.CreateBitCast(value, 958 ConvertType(GetterMethodDecl->getResultType())); 959 } 960 961 EmitReturnOfRValue(RValue::get(value), propType); 962 return; 963 } 964 } 965 llvm_unreachable("bad evaluation kind"); 966 } 967 968 } 969 llvm_unreachable("bad @property implementation strategy!"); 970 } 971 972 /// emitStructSetterCall - Call the runtime function to store the value 973 /// from the first formal parameter into the given ivar. 974 static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD, 975 ObjCIvarDecl *ivar) { 976 // objc_copyStruct (&structIvar, &Arg, 977 // sizeof (struct something), true, false); 978 CallArgList args; 979 980 // The first argument is the address of the ivar. 981 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), 982 CGF.LoadObjCSelf(), ivar, 0) 983 .getAddress(); 984 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy); 985 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy); 986 987 // The second argument is the address of the parameter variable. 988 ParmVarDecl *argVar = *OMD->param_begin(); 989 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(), 990 VK_LValue, SourceLocation()); 991 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress(); 992 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy); 993 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy); 994 995 // The third argument is the sizeof the type. 996 llvm::Value *size = 997 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType())); 998 args.add(RValue::get(size), CGF.getContext().getSizeType()); 999 1000 // The fourth argument is the 'isAtomic' flag. 1001 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy); 1002 1003 // The fifth argument is the 'hasStrong' flag. 1004 // FIXME: should this really always be false? 1005 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy); 1006 1007 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction(); 1008 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy, 1009 args, 1010 FunctionType::ExtInfo(), 1011 RequiredArgs::All), 1012 copyStructFn, ReturnValueSlot(), args); 1013 } 1014 1015 /// emitCPPObjectAtomicSetterCall - Call the runtime function to store 1016 /// the value from the first formal parameter into the given ivar, using 1017 /// the Cpp API for atomic Cpp objects with non-trivial copy assignment. 1018 static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF, 1019 ObjCMethodDecl *OMD, 1020 ObjCIvarDecl *ivar, 1021 llvm::Constant *AtomicHelperFn) { 1022 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg, 1023 // AtomicHelperFn); 1024 CallArgList args; 1025 1026 // The first argument is the address of the ivar. 1027 llvm::Value *ivarAddr = 1028 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), 1029 CGF.LoadObjCSelf(), ivar, 0).getAddress(); 1030 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy); 1031 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy); 1032 1033 // The second argument is the address of the parameter variable. 1034 ParmVarDecl *argVar = *OMD->param_begin(); 1035 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(), 1036 VK_LValue, SourceLocation()); 1037 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress(); 1038 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy); 1039 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy); 1040 1041 // Third argument is the helper function. 1042 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy); 1043 1044 llvm::Value *copyCppAtomicObjectFn = 1045 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction(); 1046 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy, 1047 args, 1048 FunctionType::ExtInfo(), 1049 RequiredArgs::All), 1050 copyCppAtomicObjectFn, ReturnValueSlot(), args); 1051 1052 1053 } 1054 1055 1056 static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) { 1057 Expr *setter = PID->getSetterCXXAssignment(); 1058 if (!setter) return true; 1059 1060 // Sema only makes only of these when the ivar has a C++ class type, 1061 // so the form is pretty constrained. 1062 1063 // An operator call is trivial if the function it calls is trivial. 1064 // This also implies that there's nothing non-trivial going on with 1065 // the arguments, because operator= can only be trivial if it's a 1066 // synthesized assignment operator and therefore both parameters are 1067 // references. 1068 if (CallExpr *call = dyn_cast<CallExpr>(setter)) { 1069 if (const FunctionDecl *callee 1070 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl())) 1071 if (callee->isTrivial()) 1072 return true; 1073 return false; 1074 } 1075 1076 assert(isa<ExprWithCleanups>(setter)); 1077 return false; 1078 } 1079 1080 static bool UseOptimizedSetter(CodeGenModule &CGM) { 1081 if (CGM.getLangOpts().getGC() != LangOptions::NonGC) 1082 return false; 1083 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter(); 1084 } 1085 1086 void 1087 CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl, 1088 const ObjCPropertyImplDecl *propImpl, 1089 llvm::Constant *AtomicHelperFn) { 1090 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl(); 1091 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl(); 1092 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl(); 1093 1094 // Just use the setter expression if Sema gave us one and it's 1095 // non-trivial. 1096 if (!hasTrivialSetExpr(propImpl)) { 1097 if (!AtomicHelperFn) 1098 // If non-atomic, assignment is called directly. 1099 EmitStmt(propImpl->getSetterCXXAssignment()); 1100 else 1101 // If atomic, assignment is called via a locking api. 1102 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar, 1103 AtomicHelperFn); 1104 return; 1105 } 1106 1107 PropertyImplStrategy strategy(CGM, propImpl); 1108 switch (strategy.getKind()) { 1109 case PropertyImplStrategy::Native: { 1110 // We don't need to do anything for a zero-size struct. 1111 if (strategy.getIvarSize().isZero()) 1112 return; 1113 1114 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()]; 1115 1116 LValue ivarLValue = 1117 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0); 1118 llvm::Value *ivarAddr = ivarLValue.getAddress(); 1119 1120 // Currently, all atomic accesses have to be through integer 1121 // types, so there's no point in trying to pick a prettier type. 1122 llvm::Type *bitcastType = 1123 llvm::Type::getIntNTy(getLLVMContext(), 1124 getContext().toBits(strategy.getIvarSize())); 1125 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay 1126 1127 // Cast both arguments to the chosen operation type. 1128 argAddr = Builder.CreateBitCast(argAddr, bitcastType); 1129 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType); 1130 1131 // This bitcast load is likely to cause some nasty IR. 1132 llvm::Value *load = Builder.CreateLoad(argAddr); 1133 1134 // Perform an atomic store. There are no memory ordering requirements. 1135 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr); 1136 store->setAlignment(strategy.getIvarAlignment().getQuantity()); 1137 store->setAtomic(llvm::Unordered); 1138 return; 1139 } 1140 1141 case PropertyImplStrategy::GetSetProperty: 1142 case PropertyImplStrategy::SetPropertyAndExpressionGet: { 1143 1144 llvm::Value *setOptimizedPropertyFn = 0; 1145 llvm::Value *setPropertyFn = 0; 1146 if (UseOptimizedSetter(CGM)) { 1147 // 10.8 and iOS 6.0 code and GC is off 1148 setOptimizedPropertyFn = 1149 CGM.getObjCRuntime() 1150 .GetOptimizedPropertySetFunction(strategy.isAtomic(), 1151 strategy.isCopy()); 1152 if (!setOptimizedPropertyFn) { 1153 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI"); 1154 return; 1155 } 1156 } 1157 else { 1158 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction(); 1159 if (!setPropertyFn) { 1160 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy"); 1161 return; 1162 } 1163 } 1164 1165 // Emit objc_setProperty((id) self, _cmd, offset, arg, 1166 // <is-atomic>, <is-copy>). 1167 llvm::Value *cmd = 1168 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]); 1169 llvm::Value *self = 1170 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy); 1171 llvm::Value *ivarOffset = 1172 EmitIvarOffset(classImpl->getClassInterface(), ivar); 1173 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()]; 1174 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy); 1175 1176 CallArgList args; 1177 args.add(RValue::get(self), getContext().getObjCIdType()); 1178 args.add(RValue::get(cmd), getContext().getObjCSelType()); 1179 if (setOptimizedPropertyFn) { 1180 args.add(RValue::get(arg), getContext().getObjCIdType()); 1181 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType()); 1182 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args, 1183 FunctionType::ExtInfo(), 1184 RequiredArgs::All), 1185 setOptimizedPropertyFn, ReturnValueSlot(), args); 1186 } else { 1187 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType()); 1188 args.add(RValue::get(arg), getContext().getObjCIdType()); 1189 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())), 1190 getContext().BoolTy); 1191 args.add(RValue::get(Builder.getInt1(strategy.isCopy())), 1192 getContext().BoolTy); 1193 // FIXME: We shouldn't need to get the function info here, the runtime 1194 // already should have computed it to build the function. 1195 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args, 1196 FunctionType::ExtInfo(), 1197 RequiredArgs::All), 1198 setPropertyFn, ReturnValueSlot(), args); 1199 } 1200 1201 return; 1202 } 1203 1204 case PropertyImplStrategy::CopyStruct: 1205 emitStructSetterCall(*this, setterMethod, ivar); 1206 return; 1207 1208 case PropertyImplStrategy::Expression: 1209 break; 1210 } 1211 1212 // Otherwise, fake up some ASTs and emit a normal assignment. 1213 ValueDecl *selfDecl = setterMethod->getSelfDecl(); 1214 DeclRefExpr self(selfDecl, false, selfDecl->getType(), 1215 VK_LValue, SourceLocation()); 1216 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack, 1217 selfDecl->getType(), CK_LValueToRValue, &self, 1218 VK_RValue); 1219 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(), 1220 SourceLocation(), SourceLocation(), 1221 &selfLoad, true, true); 1222 1223 ParmVarDecl *argDecl = *setterMethod->param_begin(); 1224 QualType argType = argDecl->getType().getNonReferenceType(); 1225 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation()); 1226 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack, 1227 argType.getUnqualifiedType(), CK_LValueToRValue, 1228 &arg, VK_RValue); 1229 1230 // The property type can differ from the ivar type in some situations with 1231 // Objective-C pointer types, we can always bit cast the RHS in these cases. 1232 // The following absurdity is just to ensure well-formed IR. 1233 CastKind argCK = CK_NoOp; 1234 if (ivarRef.getType()->isObjCObjectPointerType()) { 1235 if (argLoad.getType()->isObjCObjectPointerType()) 1236 argCK = CK_BitCast; 1237 else if (argLoad.getType()->isBlockPointerType()) 1238 argCK = CK_BlockPointerToObjCPointerCast; 1239 else 1240 argCK = CK_CPointerToObjCPointerCast; 1241 } else if (ivarRef.getType()->isBlockPointerType()) { 1242 if (argLoad.getType()->isBlockPointerType()) 1243 argCK = CK_BitCast; 1244 else 1245 argCK = CK_AnyPointerToBlockPointerCast; 1246 } else if (ivarRef.getType()->isPointerType()) { 1247 argCK = CK_BitCast; 1248 } 1249 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack, 1250 ivarRef.getType(), argCK, &argLoad, 1251 VK_RValue); 1252 Expr *finalArg = &argLoad; 1253 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(), 1254 argLoad.getType())) 1255 finalArg = &argCast; 1256 1257 1258 BinaryOperator assign(&ivarRef, finalArg, BO_Assign, 1259 ivarRef.getType(), VK_RValue, OK_Ordinary, 1260 SourceLocation(), false); 1261 EmitStmt(&assign); 1262 } 1263 1264 /// \brief Generate an Objective-C property setter function. 1265 /// 1266 /// The given Decl must be an ObjCImplementationDecl. \@synthesize 1267 /// is illegal within a category. 1268 void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP, 1269 const ObjCPropertyImplDecl *PID) { 1270 llvm::Constant *AtomicHelperFn = 1271 GenerateObjCAtomicSetterCopyHelperFunction(PID); 1272 const ObjCPropertyDecl *PD = PID->getPropertyDecl(); 1273 ObjCMethodDecl *OMD = PD->getSetterMethodDecl(); 1274 assert(OMD && "Invalid call to generate setter (empty method)"); 1275 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart()); 1276 1277 generateObjCSetterBody(IMP, PID, AtomicHelperFn); 1278 1279 FinishFunction(); 1280 } 1281 1282 namespace { 1283 struct DestroyIvar : EHScopeStack::Cleanup { 1284 private: 1285 llvm::Value *addr; 1286 const ObjCIvarDecl *ivar; 1287 CodeGenFunction::Destroyer *destroyer; 1288 bool useEHCleanupForArray; 1289 public: 1290 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar, 1291 CodeGenFunction::Destroyer *destroyer, 1292 bool useEHCleanupForArray) 1293 : addr(addr), ivar(ivar), destroyer(destroyer), 1294 useEHCleanupForArray(useEHCleanupForArray) {} 1295 1296 void Emit(CodeGenFunction &CGF, Flags flags) { 1297 LValue lvalue 1298 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0); 1299 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer, 1300 flags.isForNormalCleanup() && useEHCleanupForArray); 1301 } 1302 }; 1303 } 1304 1305 /// Like CodeGenFunction::destroyARCStrong, but do it with a call. 1306 static void destroyARCStrongWithStore(CodeGenFunction &CGF, 1307 llvm::Value *addr, 1308 QualType type) { 1309 llvm::Value *null = getNullForVariable(addr); 1310 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true); 1311 } 1312 1313 static void emitCXXDestructMethod(CodeGenFunction &CGF, 1314 ObjCImplementationDecl *impl) { 1315 CodeGenFunction::RunCleanupsScope scope(CGF); 1316 1317 llvm::Value *self = CGF.LoadObjCSelf(); 1318 1319 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 1320 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 1321 ivar; ivar = ivar->getNextIvar()) { 1322 QualType type = ivar->getType(); 1323 1324 // Check whether the ivar is a destructible type. 1325 QualType::DestructionKind dtorKind = type.isDestructedType(); 1326 if (!dtorKind) continue; 1327 1328 CodeGenFunction::Destroyer *destroyer = 0; 1329 1330 // Use a call to objc_storeStrong to destroy strong ivars, for the 1331 // general benefit of the tools. 1332 if (dtorKind == QualType::DK_objc_strong_lifetime) { 1333 destroyer = destroyARCStrongWithStore; 1334 1335 // Otherwise use the default for the destruction kind. 1336 } else { 1337 destroyer = CGF.getDestroyer(dtorKind); 1338 } 1339 1340 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind); 1341 1342 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer, 1343 cleanupKind & EHCleanup); 1344 } 1345 1346 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?"); 1347 } 1348 1349 void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, 1350 ObjCMethodDecl *MD, 1351 bool ctor) { 1352 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface()); 1353 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart()); 1354 1355 // Emit .cxx_construct. 1356 if (ctor) { 1357 // Suppress the final autorelease in ARC. 1358 AutoreleaseResult = false; 1359 1360 SmallVector<CXXCtorInitializer *, 8> IvarInitializers; 1361 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(), 1362 E = IMP->init_end(); B != E; ++B) { 1363 CXXCtorInitializer *IvarInit = (*B); 1364 FieldDecl *Field = IvarInit->getAnyMember(); 1365 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field); 1366 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), 1367 LoadObjCSelf(), Ivar, 0); 1368 EmitAggExpr(IvarInit->getInit(), 1369 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed, 1370 AggValueSlot::DoesNotNeedGCBarriers, 1371 AggValueSlot::IsNotAliased)); 1372 } 1373 // constructor returns 'self'. 1374 CodeGenTypes &Types = CGM.getTypes(); 1375 QualType IdTy(CGM.getContext().getObjCIdType()); 1376 llvm::Value *SelfAsId = 1377 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy)); 1378 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy); 1379 1380 // Emit .cxx_destruct. 1381 } else { 1382 emitCXXDestructMethod(*this, IMP); 1383 } 1384 FinishFunction(); 1385 } 1386 1387 bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) { 1388 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(); 1389 it++; it++; 1390 const ABIArgInfo &AI = it->info; 1391 // FIXME. Is this sufficient check? 1392 return (AI.getKind() == ABIArgInfo::Indirect); 1393 } 1394 1395 bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) { 1396 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) 1397 return false; 1398 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>()) 1399 return FDTTy->getDecl()->hasObjectMember(); 1400 return false; 1401 } 1402 1403 llvm::Value *CodeGenFunction::LoadObjCSelf() { 1404 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl); 1405 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self"); 1406 } 1407 1408 QualType CodeGenFunction::TypeOfSelfObject() { 1409 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl); 1410 ImplicitParamDecl *selfDecl = OMD->getSelfDecl(); 1411 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>( 1412 getContext().getCanonicalType(selfDecl->getType())); 1413 return PTy->getPointeeType(); 1414 } 1415 1416 void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){ 1417 llvm::Constant *EnumerationMutationFn = 1418 CGM.getObjCRuntime().EnumerationMutationFunction(); 1419 1420 if (!EnumerationMutationFn) { 1421 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime"); 1422 return; 1423 } 1424 1425 CGDebugInfo *DI = getDebugInfo(); 1426 if (DI) 1427 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin()); 1428 1429 // The local variable comes into scope immediately. 1430 AutoVarEmission variable = AutoVarEmission::invalid(); 1431 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) 1432 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl())); 1433 1434 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end"); 1435 1436 // Fast enumeration state. 1437 QualType StateTy = CGM.getObjCFastEnumerationStateType(); 1438 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr"); 1439 EmitNullInitialization(StatePtr, StateTy); 1440 1441 // Number of elements in the items array. 1442 static const unsigned NumItems = 16; 1443 1444 // Fetch the countByEnumeratingWithState:objects:count: selector. 1445 IdentifierInfo *II[] = { 1446 &CGM.getContext().Idents.get("countByEnumeratingWithState"), 1447 &CGM.getContext().Idents.get("objects"), 1448 &CGM.getContext().Idents.get("count") 1449 }; 1450 Selector FastEnumSel = 1451 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]); 1452 1453 QualType ItemsTy = 1454 getContext().getConstantArrayType(getContext().getObjCIdType(), 1455 llvm::APInt(32, NumItems), 1456 ArrayType::Normal, 0); 1457 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr"); 1458 1459 // Emit the collection pointer. In ARC, we do a retain. 1460 llvm::Value *Collection; 1461 if (getLangOpts().ObjCAutoRefCount) { 1462 Collection = EmitARCRetainScalarExpr(S.getCollection()); 1463 1464 // Enter a cleanup to do the release. 1465 EmitObjCConsumeObject(S.getCollection()->getType(), Collection); 1466 } else { 1467 Collection = EmitScalarExpr(S.getCollection()); 1468 } 1469 1470 // The 'continue' label needs to appear within the cleanup for the 1471 // collection object. 1472 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next"); 1473 1474 // Send it our message: 1475 CallArgList Args; 1476 1477 // The first argument is a temporary of the enumeration-state type. 1478 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy)); 1479 1480 // The second argument is a temporary array with space for NumItems 1481 // pointers. We'll actually be loading elements from the array 1482 // pointer written into the control state; this buffer is so that 1483 // collections that *aren't* backed by arrays can still queue up 1484 // batches of elements. 1485 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy)); 1486 1487 // The third argument is the capacity of that temporary array. 1488 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy); 1489 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems); 1490 Args.add(RValue::get(Count), getContext().UnsignedLongTy); 1491 1492 // Start the enumeration. 1493 RValue CountRV = 1494 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(), 1495 getContext().UnsignedLongTy, 1496 FastEnumSel, 1497 Collection, Args); 1498 1499 // The initial number of objects that were returned in the buffer. 1500 llvm::Value *initialBufferLimit = CountRV.getScalarVal(); 1501 1502 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty"); 1503 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit"); 1504 1505 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy); 1506 1507 // If the limit pointer was zero to begin with, the collection is 1508 // empty; skip all this. 1509 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), 1510 EmptyBB, LoopInitBB); 1511 1512 // Otherwise, initialize the loop. 1513 EmitBlock(LoopInitBB); 1514 1515 // Save the initial mutations value. This is the value at an 1516 // address that was written into the state object by 1517 // countByEnumeratingWithState:objects:count:. 1518 llvm::Value *StateMutationsPtrPtr = 1519 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr"); 1520 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, 1521 "mutationsptr"); 1522 1523 llvm::Value *initialMutations = 1524 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations"); 1525 1526 // Start looping. This is the point we return to whenever we have a 1527 // fresh, non-empty batch of objects. 1528 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody"); 1529 EmitBlock(LoopBodyBB); 1530 1531 // The current index into the buffer. 1532 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index"); 1533 index->addIncoming(zero, LoopInitBB); 1534 1535 // The current buffer size. 1536 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count"); 1537 count->addIncoming(initialBufferLimit, LoopInitBB); 1538 1539 // Check whether the mutations value has changed from where it was 1540 // at start. StateMutationsPtr should actually be invariant between 1541 // refreshes. 1542 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr"); 1543 llvm::Value *currentMutations 1544 = Builder.CreateLoad(StateMutationsPtr, "statemutations"); 1545 1546 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated"); 1547 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated"); 1548 1549 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations), 1550 WasNotMutatedBB, WasMutatedBB); 1551 1552 // If so, call the enumeration-mutation function. 1553 EmitBlock(WasMutatedBB); 1554 llvm::Value *V = 1555 Builder.CreateBitCast(Collection, 1556 ConvertType(getContext().getObjCIdType())); 1557 CallArgList Args2; 1558 Args2.add(RValue::get(V), getContext().getObjCIdType()); 1559 // FIXME: We shouldn't need to get the function info here, the runtime already 1560 // should have computed it to build the function. 1561 EmitCall(CGM.getTypes().arrangeFreeFunctionCall(getContext().VoidTy, Args2, 1562 FunctionType::ExtInfo(), 1563 RequiredArgs::All), 1564 EnumerationMutationFn, ReturnValueSlot(), Args2); 1565 1566 // Otherwise, or if the mutation function returns, just continue. 1567 EmitBlock(WasNotMutatedBB); 1568 1569 // Initialize the element variable. 1570 RunCleanupsScope elementVariableScope(*this); 1571 bool elementIsVariable; 1572 LValue elementLValue; 1573 QualType elementType; 1574 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) { 1575 // Initialize the variable, in case it's a __block variable or something. 1576 EmitAutoVarInit(variable); 1577 1578 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl()); 1579 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(), 1580 VK_LValue, SourceLocation()); 1581 elementLValue = EmitLValue(&tempDRE); 1582 elementType = D->getType(); 1583 elementIsVariable = true; 1584 1585 if (D->isARCPseudoStrong()) 1586 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone); 1587 } else { 1588 elementLValue = LValue(); // suppress warning 1589 elementType = cast<Expr>(S.getElement())->getType(); 1590 elementIsVariable = false; 1591 } 1592 llvm::Type *convertedElementType = ConvertType(elementType); 1593 1594 // Fetch the buffer out of the enumeration state. 1595 // TODO: this pointer should actually be invariant between 1596 // refreshes, which would help us do certain loop optimizations. 1597 llvm::Value *StateItemsPtr = 1598 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr"); 1599 llvm::Value *EnumStateItems = 1600 Builder.CreateLoad(StateItemsPtr, "stateitems"); 1601 1602 // Fetch the value at the current index from the buffer. 1603 llvm::Value *CurrentItemPtr = 1604 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr"); 1605 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr); 1606 1607 // Cast that value to the right type. 1608 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType, 1609 "currentitem"); 1610 1611 // Make sure we have an l-value. Yes, this gets evaluated every 1612 // time through the loop. 1613 if (!elementIsVariable) { 1614 elementLValue = EmitLValue(cast<Expr>(S.getElement())); 1615 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue); 1616 } else { 1617 EmitScalarInit(CurrentItem, elementLValue); 1618 } 1619 1620 // If we do have an element variable, this assignment is the end of 1621 // its initialization. 1622 if (elementIsVariable) 1623 EmitAutoVarCleanups(variable); 1624 1625 // Perform the loop body, setting up break and continue labels. 1626 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody)); 1627 { 1628 RunCleanupsScope Scope(*this); 1629 EmitStmt(S.getBody()); 1630 } 1631 BreakContinueStack.pop_back(); 1632 1633 // Destroy the element variable now. 1634 elementVariableScope.ForceCleanup(); 1635 1636 // Check whether there are more elements. 1637 EmitBlock(AfterBody.getBlock()); 1638 1639 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch"); 1640 1641 // First we check in the local buffer. 1642 llvm::Value *indexPlusOne 1643 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1)); 1644 1645 // If we haven't overrun the buffer yet, we can continue. 1646 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count), 1647 LoopBodyBB, FetchMoreBB); 1648 1649 index->addIncoming(indexPlusOne, AfterBody.getBlock()); 1650 count->addIncoming(count, AfterBody.getBlock()); 1651 1652 // Otherwise, we have to fetch more elements. 1653 EmitBlock(FetchMoreBB); 1654 1655 CountRV = 1656 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(), 1657 getContext().UnsignedLongTy, 1658 FastEnumSel, 1659 Collection, Args); 1660 1661 // If we got a zero count, we're done. 1662 llvm::Value *refetchCount = CountRV.getScalarVal(); 1663 1664 // (note that the message send might split FetchMoreBB) 1665 index->addIncoming(zero, Builder.GetInsertBlock()); 1666 count->addIncoming(refetchCount, Builder.GetInsertBlock()); 1667 1668 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero), 1669 EmptyBB, LoopBodyBB); 1670 1671 // No more elements. 1672 EmitBlock(EmptyBB); 1673 1674 if (!elementIsVariable) { 1675 // If the element was not a declaration, set it to be null. 1676 1677 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType); 1678 elementLValue = EmitLValue(cast<Expr>(S.getElement())); 1679 EmitStoreThroughLValue(RValue::get(null), elementLValue); 1680 } 1681 1682 if (DI) 1683 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd()); 1684 1685 // Leave the cleanup we entered in ARC. 1686 if (getLangOpts().ObjCAutoRefCount) 1687 PopCleanupBlock(); 1688 1689 EmitBlock(LoopEnd.getBlock()); 1690 } 1691 1692 void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) { 1693 CGM.getObjCRuntime().EmitTryStmt(*this, S); 1694 } 1695 1696 void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) { 1697 CGM.getObjCRuntime().EmitThrowStmt(*this, S); 1698 } 1699 1700 void CodeGenFunction::EmitObjCAtSynchronizedStmt( 1701 const ObjCAtSynchronizedStmt &S) { 1702 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S); 1703 } 1704 1705 /// Produce the code for a CK_ARCProduceObject. Just does a 1706 /// primitive retain. 1707 llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type, 1708 llvm::Value *value) { 1709 return EmitARCRetain(type, value); 1710 } 1711 1712 namespace { 1713 struct CallObjCRelease : EHScopeStack::Cleanup { 1714 CallObjCRelease(llvm::Value *object) : object(object) {} 1715 llvm::Value *object; 1716 1717 void Emit(CodeGenFunction &CGF, Flags flags) { 1718 // Releases at the end of the full-expression are imprecise. 1719 CGF.EmitARCRelease(object, ARCImpreciseLifetime); 1720 } 1721 }; 1722 } 1723 1724 /// Produce the code for a CK_ARCConsumeObject. Does a primitive 1725 /// release at the end of the full-expression. 1726 llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type, 1727 llvm::Value *object) { 1728 // If we're in a conditional branch, we need to make the cleanup 1729 // conditional. 1730 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object); 1731 return object; 1732 } 1733 1734 llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type, 1735 llvm::Value *value) { 1736 return EmitARCRetainAutorelease(type, value); 1737 } 1738 1739 /// Given a number of pointers, inform the optimizer that they're 1740 /// being intrinsically used up until this point in the program. 1741 void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) { 1742 llvm::Constant *&fn = CGM.getARCEntrypoints().clang_arc_use; 1743 if (!fn) { 1744 llvm::FunctionType *fnType = 1745 llvm::FunctionType::get(CGM.VoidTy, ArrayRef<llvm::Type*>(), true); 1746 fn = CGM.CreateRuntimeFunction(fnType, "clang.arc.use"); 1747 } 1748 1749 // This isn't really a "runtime" function, but as an intrinsic it 1750 // doesn't really matter as long as we align things up. 1751 EmitNounwindRuntimeCall(fn, values); 1752 } 1753 1754 1755 static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM, 1756 llvm::FunctionType *type, 1757 StringRef fnName) { 1758 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName); 1759 1760 if (llvm::Function *f = dyn_cast<llvm::Function>(fn)) { 1761 // If the target runtime doesn't naturally support ARC, emit weak 1762 // references to the runtime support library. We don't really 1763 // permit this to fail, but we need a particular relocation style. 1764 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC()) { 1765 f->setLinkage(llvm::Function::ExternalWeakLinkage); 1766 } else if (fnName == "objc_retain" || fnName == "objc_release") { 1767 // If we have Native ARC, set nonlazybind attribute for these APIs for 1768 // performance. 1769 f->addFnAttr(llvm::Attribute::NonLazyBind); 1770 } 1771 } 1772 1773 return fn; 1774 } 1775 1776 /// Perform an operation having the signature 1777 /// i8* (i8*) 1778 /// where a null input causes a no-op and returns null. 1779 static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF, 1780 llvm::Value *value, 1781 llvm::Constant *&fn, 1782 StringRef fnName, 1783 bool isTailCall = false) { 1784 if (isa<llvm::ConstantPointerNull>(value)) return value; 1785 1786 if (!fn) { 1787 llvm::FunctionType *fnType = 1788 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false); 1789 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName); 1790 } 1791 1792 // Cast the argument to 'id'. 1793 llvm::Type *origType = value->getType(); 1794 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy); 1795 1796 // Call the function. 1797 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value); 1798 if (isTailCall) 1799 call->setTailCall(); 1800 1801 // Cast the result back to the original type. 1802 return CGF.Builder.CreateBitCast(call, origType); 1803 } 1804 1805 /// Perform an operation having the following signature: 1806 /// i8* (i8**) 1807 static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF, 1808 llvm::Value *addr, 1809 llvm::Constant *&fn, 1810 StringRef fnName) { 1811 if (!fn) { 1812 llvm::FunctionType *fnType = 1813 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrPtrTy, false); 1814 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName); 1815 } 1816 1817 // Cast the argument to 'id*'. 1818 llvm::Type *origType = addr->getType(); 1819 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy); 1820 1821 // Call the function. 1822 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr); 1823 1824 // Cast the result back to a dereference of the original type. 1825 if (origType != CGF.Int8PtrPtrTy) 1826 result = CGF.Builder.CreateBitCast(result, 1827 cast<llvm::PointerType>(origType)->getElementType()); 1828 1829 return result; 1830 } 1831 1832 /// Perform an operation having the following signature: 1833 /// i8* (i8**, i8*) 1834 static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF, 1835 llvm::Value *addr, 1836 llvm::Value *value, 1837 llvm::Constant *&fn, 1838 StringRef fnName, 1839 bool ignored) { 1840 assert(cast<llvm::PointerType>(addr->getType())->getElementType() 1841 == value->getType()); 1842 1843 if (!fn) { 1844 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy }; 1845 1846 llvm::FunctionType *fnType 1847 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false); 1848 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName); 1849 } 1850 1851 llvm::Type *origType = value->getType(); 1852 1853 llvm::Value *args[] = { 1854 CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy), 1855 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy) 1856 }; 1857 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args); 1858 1859 if (ignored) return 0; 1860 1861 return CGF.Builder.CreateBitCast(result, origType); 1862 } 1863 1864 /// Perform an operation having the following signature: 1865 /// void (i8**, i8**) 1866 static void emitARCCopyOperation(CodeGenFunction &CGF, 1867 llvm::Value *dst, 1868 llvm::Value *src, 1869 llvm::Constant *&fn, 1870 StringRef fnName) { 1871 assert(dst->getType() == src->getType()); 1872 1873 if (!fn) { 1874 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrPtrTy }; 1875 1876 llvm::FunctionType *fnType 1877 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false); 1878 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName); 1879 } 1880 1881 llvm::Value *args[] = { 1882 CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy), 1883 CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy) 1884 }; 1885 CGF.EmitNounwindRuntimeCall(fn, args); 1886 } 1887 1888 /// Produce the code to do a retain. Based on the type, calls one of: 1889 /// call i8* \@objc_retain(i8* %value) 1890 /// call i8* \@objc_retainBlock(i8* %value) 1891 llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) { 1892 if (type->isBlockPointerType()) 1893 return EmitARCRetainBlock(value, /*mandatory*/ false); 1894 else 1895 return EmitARCRetainNonBlock(value); 1896 } 1897 1898 /// Retain the given object, with normal retain semantics. 1899 /// call i8* \@objc_retain(i8* %value) 1900 llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) { 1901 return emitARCValueOperation(*this, value, 1902 CGM.getARCEntrypoints().objc_retain, 1903 "objc_retain"); 1904 } 1905 1906 /// Retain the given block, with _Block_copy semantics. 1907 /// call i8* \@objc_retainBlock(i8* %value) 1908 /// 1909 /// \param mandatory - If false, emit the call with metadata 1910 /// indicating that it's okay for the optimizer to eliminate this call 1911 /// if it can prove that the block never escapes except down the stack. 1912 llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value, 1913 bool mandatory) { 1914 llvm::Value *result 1915 = emitARCValueOperation(*this, value, 1916 CGM.getARCEntrypoints().objc_retainBlock, 1917 "objc_retainBlock"); 1918 1919 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to 1920 // tell the optimizer that it doesn't need to do this copy if the 1921 // block doesn't escape, where being passed as an argument doesn't 1922 // count as escaping. 1923 if (!mandatory && isa<llvm::Instruction>(result)) { 1924 llvm::CallInst *call 1925 = cast<llvm::CallInst>(result->stripPointerCasts()); 1926 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock); 1927 1928 SmallVector<llvm::Value*,1> args; 1929 call->setMetadata("clang.arc.copy_on_escape", 1930 llvm::MDNode::get(Builder.getContext(), args)); 1931 } 1932 1933 return result; 1934 } 1935 1936 /// Retain the given object which is the result of a function call. 1937 /// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value) 1938 /// 1939 /// Yes, this function name is one character away from a different 1940 /// call with completely different semantics. 1941 llvm::Value * 1942 CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) { 1943 // Fetch the void(void) inline asm which marks that we're going to 1944 // retain the autoreleased return value. 1945 llvm::InlineAsm *&marker 1946 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker; 1947 if (!marker) { 1948 StringRef assembly 1949 = CGM.getTargetCodeGenInfo() 1950 .getARCRetainAutoreleasedReturnValueMarker(); 1951 1952 // If we have an empty assembly string, there's nothing to do. 1953 if (assembly.empty()) { 1954 1955 // Otherwise, at -O0, build an inline asm that we're going to call 1956 // in a moment. 1957 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) { 1958 llvm::FunctionType *type = 1959 llvm::FunctionType::get(VoidTy, /*variadic*/false); 1960 1961 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true); 1962 1963 // If we're at -O1 and above, we don't want to litter the code 1964 // with this marker yet, so leave a breadcrumb for the ARC 1965 // optimizer to pick up. 1966 } else { 1967 llvm::NamedMDNode *metadata = 1968 CGM.getModule().getOrInsertNamedMetadata( 1969 "clang.arc.retainAutoreleasedReturnValueMarker"); 1970 assert(metadata->getNumOperands() <= 1); 1971 if (metadata->getNumOperands() == 0) { 1972 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly); 1973 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string)); 1974 } 1975 } 1976 } 1977 1978 // Call the marker asm if we made one, which we do only at -O0. 1979 if (marker) Builder.CreateCall(marker); 1980 1981 return emitARCValueOperation(*this, value, 1982 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue, 1983 "objc_retainAutoreleasedReturnValue"); 1984 } 1985 1986 /// Release the given object. 1987 /// call void \@objc_release(i8* %value) 1988 void CodeGenFunction::EmitARCRelease(llvm::Value *value, 1989 ARCPreciseLifetime_t precise) { 1990 if (isa<llvm::ConstantPointerNull>(value)) return; 1991 1992 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release; 1993 if (!fn) { 1994 llvm::FunctionType *fnType = 1995 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false); 1996 fn = createARCRuntimeFunction(CGM, fnType, "objc_release"); 1997 } 1998 1999 // Cast the argument to 'id'. 2000 value = Builder.CreateBitCast(value, Int8PtrTy); 2001 2002 // Call objc_release. 2003 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value); 2004 2005 if (precise == ARCImpreciseLifetime) { 2006 SmallVector<llvm::Value*,1> args; 2007 call->setMetadata("clang.imprecise_release", 2008 llvm::MDNode::get(Builder.getContext(), args)); 2009 } 2010 } 2011 2012 /// Destroy a __strong variable. 2013 /// 2014 /// At -O0, emit a call to store 'null' into the address; 2015 /// instrumenting tools prefer this because the address is exposed, 2016 /// but it's relatively cumbersome to optimize. 2017 /// 2018 /// At -O1 and above, just load and call objc_release. 2019 /// 2020 /// call void \@objc_storeStrong(i8** %addr, i8* null) 2021 void CodeGenFunction::EmitARCDestroyStrong(llvm::Value *addr, 2022 ARCPreciseLifetime_t precise) { 2023 if (CGM.getCodeGenOpts().OptimizationLevel == 0) { 2024 llvm::PointerType *addrTy = cast<llvm::PointerType>(addr->getType()); 2025 llvm::Value *null = llvm::ConstantPointerNull::get( 2026 cast<llvm::PointerType>(addrTy->getElementType())); 2027 EmitARCStoreStrongCall(addr, null, /*ignored*/ true); 2028 return; 2029 } 2030 2031 llvm::Value *value = Builder.CreateLoad(addr); 2032 EmitARCRelease(value, precise); 2033 } 2034 2035 /// Store into a strong object. Always calls this: 2036 /// call void \@objc_storeStrong(i8** %addr, i8* %value) 2037 llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr, 2038 llvm::Value *value, 2039 bool ignored) { 2040 assert(cast<llvm::PointerType>(addr->getType())->getElementType() 2041 == value->getType()); 2042 2043 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong; 2044 if (!fn) { 2045 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy }; 2046 llvm::FunctionType *fnType 2047 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false); 2048 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong"); 2049 } 2050 2051 llvm::Value *args[] = { 2052 Builder.CreateBitCast(addr, Int8PtrPtrTy), 2053 Builder.CreateBitCast(value, Int8PtrTy) 2054 }; 2055 EmitNounwindRuntimeCall(fn, args); 2056 2057 if (ignored) return 0; 2058 return value; 2059 } 2060 2061 /// Store into a strong object. Sometimes calls this: 2062 /// call void \@objc_storeStrong(i8** %addr, i8* %value) 2063 /// Other times, breaks it down into components. 2064 llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst, 2065 llvm::Value *newValue, 2066 bool ignored) { 2067 QualType type = dst.getType(); 2068 bool isBlock = type->isBlockPointerType(); 2069 2070 // Use a store barrier at -O0 unless this is a block type or the 2071 // lvalue is inadequately aligned. 2072 if (shouldUseFusedARCCalls() && 2073 !isBlock && 2074 (dst.getAlignment().isZero() || 2075 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) { 2076 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored); 2077 } 2078 2079 // Otherwise, split it out. 2080 2081 // Retain the new value. 2082 newValue = EmitARCRetain(type, newValue); 2083 2084 // Read the old value. 2085 llvm::Value *oldValue = EmitLoadOfScalar(dst); 2086 2087 // Store. We do this before the release so that any deallocs won't 2088 // see the old value. 2089 EmitStoreOfScalar(newValue, dst); 2090 2091 // Finally, release the old value. 2092 EmitARCRelease(oldValue, dst.isARCPreciseLifetime()); 2093 2094 return newValue; 2095 } 2096 2097 /// Autorelease the given object. 2098 /// call i8* \@objc_autorelease(i8* %value) 2099 llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) { 2100 return emitARCValueOperation(*this, value, 2101 CGM.getARCEntrypoints().objc_autorelease, 2102 "objc_autorelease"); 2103 } 2104 2105 /// Autorelease the given object. 2106 /// call i8* \@objc_autoreleaseReturnValue(i8* %value) 2107 llvm::Value * 2108 CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) { 2109 return emitARCValueOperation(*this, value, 2110 CGM.getARCEntrypoints().objc_autoreleaseReturnValue, 2111 "objc_autoreleaseReturnValue", 2112 /*isTailCall*/ true); 2113 } 2114 2115 /// Do a fused retain/autorelease of the given object. 2116 /// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value) 2117 llvm::Value * 2118 CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) { 2119 return emitARCValueOperation(*this, value, 2120 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue, 2121 "objc_retainAutoreleaseReturnValue", 2122 /*isTailCall*/ true); 2123 } 2124 2125 /// Do a fused retain/autorelease of the given object. 2126 /// call i8* \@objc_retainAutorelease(i8* %value) 2127 /// or 2128 /// %retain = call i8* \@objc_retainBlock(i8* %value) 2129 /// call i8* \@objc_autorelease(i8* %retain) 2130 llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type, 2131 llvm::Value *value) { 2132 if (!type->isBlockPointerType()) 2133 return EmitARCRetainAutoreleaseNonBlock(value); 2134 2135 if (isa<llvm::ConstantPointerNull>(value)) return value; 2136 2137 llvm::Type *origType = value->getType(); 2138 value = Builder.CreateBitCast(value, Int8PtrTy); 2139 value = EmitARCRetainBlock(value, /*mandatory*/ true); 2140 value = EmitARCAutorelease(value); 2141 return Builder.CreateBitCast(value, origType); 2142 } 2143 2144 /// Do a fused retain/autorelease of the given object. 2145 /// call i8* \@objc_retainAutorelease(i8* %value) 2146 llvm::Value * 2147 CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) { 2148 return emitARCValueOperation(*this, value, 2149 CGM.getARCEntrypoints().objc_retainAutorelease, 2150 "objc_retainAutorelease"); 2151 } 2152 2153 /// i8* \@objc_loadWeak(i8** %addr) 2154 /// Essentially objc_autorelease(objc_loadWeakRetained(addr)). 2155 llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) { 2156 return emitARCLoadOperation(*this, addr, 2157 CGM.getARCEntrypoints().objc_loadWeak, 2158 "objc_loadWeak"); 2159 } 2160 2161 /// i8* \@objc_loadWeakRetained(i8** %addr) 2162 llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) { 2163 return emitARCLoadOperation(*this, addr, 2164 CGM.getARCEntrypoints().objc_loadWeakRetained, 2165 "objc_loadWeakRetained"); 2166 } 2167 2168 /// i8* \@objc_storeWeak(i8** %addr, i8* %value) 2169 /// Returns %value. 2170 llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr, 2171 llvm::Value *value, 2172 bool ignored) { 2173 return emitARCStoreOperation(*this, addr, value, 2174 CGM.getARCEntrypoints().objc_storeWeak, 2175 "objc_storeWeak", ignored); 2176 } 2177 2178 /// i8* \@objc_initWeak(i8** %addr, i8* %value) 2179 /// Returns %value. %addr is known to not have a current weak entry. 2180 /// Essentially equivalent to: 2181 /// *addr = nil; objc_storeWeak(addr, value); 2182 void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) { 2183 // If we're initializing to null, just write null to memory; no need 2184 // to get the runtime involved. But don't do this if optimization 2185 // is enabled, because accounting for this would make the optimizer 2186 // much more complicated. 2187 if (isa<llvm::ConstantPointerNull>(value) && 2188 CGM.getCodeGenOpts().OptimizationLevel == 0) { 2189 Builder.CreateStore(value, addr); 2190 return; 2191 } 2192 2193 emitARCStoreOperation(*this, addr, value, 2194 CGM.getARCEntrypoints().objc_initWeak, 2195 "objc_initWeak", /*ignored*/ true); 2196 } 2197 2198 /// void \@objc_destroyWeak(i8** %addr) 2199 /// Essentially objc_storeWeak(addr, nil). 2200 void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) { 2201 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak; 2202 if (!fn) { 2203 llvm::FunctionType *fnType = 2204 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrPtrTy, false); 2205 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak"); 2206 } 2207 2208 // Cast the argument to 'id*'. 2209 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy); 2210 2211 EmitNounwindRuntimeCall(fn, addr); 2212 } 2213 2214 /// void \@objc_moveWeak(i8** %dest, i8** %src) 2215 /// Disregards the current value in %dest. Leaves %src pointing to nothing. 2216 /// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)). 2217 void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) { 2218 emitARCCopyOperation(*this, dst, src, 2219 CGM.getARCEntrypoints().objc_moveWeak, 2220 "objc_moveWeak"); 2221 } 2222 2223 /// void \@objc_copyWeak(i8** %dest, i8** %src) 2224 /// Disregards the current value in %dest. Essentially 2225 /// objc_release(objc_initWeak(dest, objc_readWeakRetained(src))) 2226 void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) { 2227 emitARCCopyOperation(*this, dst, src, 2228 CGM.getARCEntrypoints().objc_copyWeak, 2229 "objc_copyWeak"); 2230 } 2231 2232 /// Produce the code to do a objc_autoreleasepool_push. 2233 /// call i8* \@objc_autoreleasePoolPush(void) 2234 llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() { 2235 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush; 2236 if (!fn) { 2237 llvm::FunctionType *fnType = 2238 llvm::FunctionType::get(Int8PtrTy, false); 2239 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush"); 2240 } 2241 2242 return EmitNounwindRuntimeCall(fn); 2243 } 2244 2245 /// Produce the code to do a primitive release. 2246 /// call void \@objc_autoreleasePoolPop(i8* %ptr) 2247 void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) { 2248 assert(value->getType() == Int8PtrTy); 2249 2250 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop; 2251 if (!fn) { 2252 llvm::FunctionType *fnType = 2253 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false); 2254 2255 // We don't want to use a weak import here; instead we should not 2256 // fall into this path. 2257 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop"); 2258 } 2259 2260 // objc_autoreleasePoolPop can throw. 2261 EmitRuntimeCallOrInvoke(fn, value); 2262 } 2263 2264 /// Produce the code to do an MRR version objc_autoreleasepool_push. 2265 /// Which is: [[NSAutoreleasePool alloc] init]; 2266 /// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class. 2267 /// init is declared as: - (id) init; in its NSObject super class. 2268 /// 2269 llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() { 2270 CGObjCRuntime &Runtime = CGM.getObjCRuntime(); 2271 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this); 2272 // [NSAutoreleasePool alloc] 2273 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc"); 2274 Selector AllocSel = getContext().Selectors.getSelector(0, &II); 2275 CallArgList Args; 2276 RValue AllocRV = 2277 Runtime.GenerateMessageSend(*this, ReturnValueSlot(), 2278 getContext().getObjCIdType(), 2279 AllocSel, Receiver, Args); 2280 2281 // [Receiver init] 2282 Receiver = AllocRV.getScalarVal(); 2283 II = &CGM.getContext().Idents.get("init"); 2284 Selector InitSel = getContext().Selectors.getSelector(0, &II); 2285 RValue InitRV = 2286 Runtime.GenerateMessageSend(*this, ReturnValueSlot(), 2287 getContext().getObjCIdType(), 2288 InitSel, Receiver, Args); 2289 return InitRV.getScalarVal(); 2290 } 2291 2292 /// Produce the code to do a primitive release. 2293 /// [tmp drain]; 2294 void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) { 2295 IdentifierInfo *II = &CGM.getContext().Idents.get("drain"); 2296 Selector DrainSel = getContext().Selectors.getSelector(0, &II); 2297 CallArgList Args; 2298 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(), 2299 getContext().VoidTy, DrainSel, Arg, Args); 2300 } 2301 2302 void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF, 2303 llvm::Value *addr, 2304 QualType type) { 2305 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime); 2306 } 2307 2308 void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF, 2309 llvm::Value *addr, 2310 QualType type) { 2311 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime); 2312 } 2313 2314 void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF, 2315 llvm::Value *addr, 2316 QualType type) { 2317 CGF.EmitARCDestroyWeak(addr); 2318 } 2319 2320 namespace { 2321 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup { 2322 llvm::Value *Token; 2323 2324 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {} 2325 2326 void Emit(CodeGenFunction &CGF, Flags flags) { 2327 CGF.EmitObjCAutoreleasePoolPop(Token); 2328 } 2329 }; 2330 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup { 2331 llvm::Value *Token; 2332 2333 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {} 2334 2335 void Emit(CodeGenFunction &CGF, Flags flags) { 2336 CGF.EmitObjCMRRAutoreleasePoolPop(Token); 2337 } 2338 }; 2339 } 2340 2341 void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) { 2342 if (CGM.getLangOpts().ObjCAutoRefCount) 2343 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr); 2344 else 2345 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr); 2346 } 2347 2348 static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF, 2349 LValue lvalue, 2350 QualType type) { 2351 switch (type.getObjCLifetime()) { 2352 case Qualifiers::OCL_None: 2353 case Qualifiers::OCL_ExplicitNone: 2354 case Qualifiers::OCL_Strong: 2355 case Qualifiers::OCL_Autoreleasing: 2356 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(), 2357 false); 2358 2359 case Qualifiers::OCL_Weak: 2360 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()), 2361 true); 2362 } 2363 2364 llvm_unreachable("impossible lifetime!"); 2365 } 2366 2367 static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF, 2368 const Expr *e) { 2369 e = e->IgnoreParens(); 2370 QualType type = e->getType(); 2371 2372 // If we're loading retained from a __strong xvalue, we can avoid 2373 // an extra retain/release pair by zeroing out the source of this 2374 // "move" operation. 2375 if (e->isXValue() && 2376 !type.isConstQualified() && 2377 type.getObjCLifetime() == Qualifiers::OCL_Strong) { 2378 // Emit the lvalue. 2379 LValue lv = CGF.EmitLValue(e); 2380 2381 // Load the object pointer. 2382 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal(); 2383 2384 // Set the source pointer to NULL. 2385 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv); 2386 2387 return TryEmitResult(result, true); 2388 } 2389 2390 // As a very special optimization, in ARC++, if the l-value is the 2391 // result of a non-volatile assignment, do a simple retain of the 2392 // result of the call to objc_storeWeak instead of reloading. 2393 if (CGF.getLangOpts().CPlusPlus && 2394 !type.isVolatileQualified() && 2395 type.getObjCLifetime() == Qualifiers::OCL_Weak && 2396 isa<BinaryOperator>(e) && 2397 cast<BinaryOperator>(e)->getOpcode() == BO_Assign) 2398 return TryEmitResult(CGF.EmitScalarExpr(e), false); 2399 2400 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type); 2401 } 2402 2403 static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF, 2404 llvm::Value *value); 2405 2406 /// Given that the given expression is some sort of call (which does 2407 /// not return retained), emit a retain following it. 2408 static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) { 2409 llvm::Value *value = CGF.EmitScalarExpr(e); 2410 return emitARCRetainAfterCall(CGF, value); 2411 } 2412 2413 static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF, 2414 llvm::Value *value) { 2415 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) { 2416 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP(); 2417 2418 // Place the retain immediately following the call. 2419 CGF.Builder.SetInsertPoint(call->getParent(), 2420 ++llvm::BasicBlock::iterator(call)); 2421 value = CGF.EmitARCRetainAutoreleasedReturnValue(value); 2422 2423 CGF.Builder.restoreIP(ip); 2424 return value; 2425 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) { 2426 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP(); 2427 2428 // Place the retain at the beginning of the normal destination block. 2429 llvm::BasicBlock *BB = invoke->getNormalDest(); 2430 CGF.Builder.SetInsertPoint(BB, BB->begin()); 2431 value = CGF.EmitARCRetainAutoreleasedReturnValue(value); 2432 2433 CGF.Builder.restoreIP(ip); 2434 return value; 2435 2436 // Bitcasts can arise because of related-result returns. Rewrite 2437 // the operand. 2438 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) { 2439 llvm::Value *operand = bitcast->getOperand(0); 2440 operand = emitARCRetainAfterCall(CGF, operand); 2441 bitcast->setOperand(0, operand); 2442 return bitcast; 2443 2444 // Generic fall-back case. 2445 } else { 2446 // Retain using the non-block variant: we never need to do a copy 2447 // of a block that's been returned to us. 2448 return CGF.EmitARCRetainNonBlock(value); 2449 } 2450 } 2451 2452 /// Determine whether it might be important to emit a separate 2453 /// objc_retain_block on the result of the given expression, or 2454 /// whether it's okay to just emit it in a +1 context. 2455 static bool shouldEmitSeparateBlockRetain(const Expr *e) { 2456 assert(e->getType()->isBlockPointerType()); 2457 e = e->IgnoreParens(); 2458 2459 // For future goodness, emit block expressions directly in +1 2460 // contexts if we can. 2461 if (isa<BlockExpr>(e)) 2462 return false; 2463 2464 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) { 2465 switch (cast->getCastKind()) { 2466 // Emitting these operations in +1 contexts is goodness. 2467 case CK_LValueToRValue: 2468 case CK_ARCReclaimReturnedObject: 2469 case CK_ARCConsumeObject: 2470 case CK_ARCProduceObject: 2471 return false; 2472 2473 // These operations preserve a block type. 2474 case CK_NoOp: 2475 case CK_BitCast: 2476 return shouldEmitSeparateBlockRetain(cast->getSubExpr()); 2477 2478 // These operations are known to be bad (or haven't been considered). 2479 case CK_AnyPointerToBlockPointerCast: 2480 default: 2481 return true; 2482 } 2483 } 2484 2485 return true; 2486 } 2487 2488 /// Try to emit a PseudoObjectExpr at +1. 2489 /// 2490 /// This massively duplicates emitPseudoObjectRValue. 2491 static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF, 2492 const PseudoObjectExpr *E) { 2493 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques; 2494 2495 // Find the result expression. 2496 const Expr *resultExpr = E->getResultExpr(); 2497 assert(resultExpr); 2498 TryEmitResult result; 2499 2500 for (PseudoObjectExpr::const_semantics_iterator 2501 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) { 2502 const Expr *semantic = *i; 2503 2504 // If this semantic expression is an opaque value, bind it 2505 // to the result of its source expression. 2506 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) { 2507 typedef CodeGenFunction::OpaqueValueMappingData OVMA; 2508 OVMA opaqueData; 2509 2510 // If this semantic is the result of the pseudo-object 2511 // expression, try to evaluate the source as +1. 2512 if (ov == resultExpr) { 2513 assert(!OVMA::shouldBindAsLValue(ov)); 2514 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr()); 2515 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer())); 2516 2517 // Otherwise, just bind it. 2518 } else { 2519 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr()); 2520 } 2521 opaques.push_back(opaqueData); 2522 2523 // Otherwise, if the expression is the result, evaluate it 2524 // and remember the result. 2525 } else if (semantic == resultExpr) { 2526 result = tryEmitARCRetainScalarExpr(CGF, semantic); 2527 2528 // Otherwise, evaluate the expression in an ignored context. 2529 } else { 2530 CGF.EmitIgnoredExpr(semantic); 2531 } 2532 } 2533 2534 // Unbind all the opaques now. 2535 for (unsigned i = 0, e = opaques.size(); i != e; ++i) 2536 opaques[i].unbind(CGF); 2537 2538 return result; 2539 } 2540 2541 static TryEmitResult 2542 tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) { 2543 // We should *never* see a nested full-expression here, because if 2544 // we fail to emit at +1, our caller must not retain after we close 2545 // out the full-expression. 2546 assert(!isa<ExprWithCleanups>(e)); 2547 2548 // The desired result type, if it differs from the type of the 2549 // ultimate opaque expression. 2550 llvm::Type *resultType = 0; 2551 2552 while (true) { 2553 e = e->IgnoreParens(); 2554 2555 // There's a break at the end of this if-chain; anything 2556 // that wants to keep looping has to explicitly continue. 2557 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) { 2558 switch (ce->getCastKind()) { 2559 // No-op casts don't change the type, so we just ignore them. 2560 case CK_NoOp: 2561 e = ce->getSubExpr(); 2562 continue; 2563 2564 case CK_LValueToRValue: { 2565 TryEmitResult loadResult 2566 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr()); 2567 if (resultType) { 2568 llvm::Value *value = loadResult.getPointer(); 2569 value = CGF.Builder.CreateBitCast(value, resultType); 2570 loadResult.setPointer(value); 2571 } 2572 return loadResult; 2573 } 2574 2575 // These casts can change the type, so remember that and 2576 // soldier on. We only need to remember the outermost such 2577 // cast, though. 2578 case CK_CPointerToObjCPointerCast: 2579 case CK_BlockPointerToObjCPointerCast: 2580 case CK_AnyPointerToBlockPointerCast: 2581 case CK_BitCast: 2582 if (!resultType) 2583 resultType = CGF.ConvertType(ce->getType()); 2584 e = ce->getSubExpr(); 2585 assert(e->getType()->hasPointerRepresentation()); 2586 continue; 2587 2588 // For consumptions, just emit the subexpression and thus elide 2589 // the retain/release pair. 2590 case CK_ARCConsumeObject: { 2591 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr()); 2592 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType); 2593 return TryEmitResult(result, true); 2594 } 2595 2596 // Block extends are net +0. Naively, we could just recurse on 2597 // the subexpression, but actually we need to ensure that the 2598 // value is copied as a block, so there's a little filter here. 2599 case CK_ARCExtendBlockObject: { 2600 llvm::Value *result; // will be a +0 value 2601 2602 // If we can't safely assume the sub-expression will produce a 2603 // block-copied value, emit the sub-expression at +0. 2604 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) { 2605 result = CGF.EmitScalarExpr(ce->getSubExpr()); 2606 2607 // Otherwise, try to emit the sub-expression at +1 recursively. 2608 } else { 2609 TryEmitResult subresult 2610 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr()); 2611 result = subresult.getPointer(); 2612 2613 // If that produced a retained value, just use that, 2614 // possibly casting down. 2615 if (subresult.getInt()) { 2616 if (resultType) 2617 result = CGF.Builder.CreateBitCast(result, resultType); 2618 return TryEmitResult(result, true); 2619 } 2620 2621 // Otherwise it's +0. 2622 } 2623 2624 // Retain the object as a block, then cast down. 2625 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true); 2626 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType); 2627 return TryEmitResult(result, true); 2628 } 2629 2630 // For reclaims, emit the subexpression as a retained call and 2631 // skip the consumption. 2632 case CK_ARCReclaimReturnedObject: { 2633 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr()); 2634 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType); 2635 return TryEmitResult(result, true); 2636 } 2637 2638 default: 2639 break; 2640 } 2641 2642 // Skip __extension__. 2643 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) { 2644 if (op->getOpcode() == UO_Extension) { 2645 e = op->getSubExpr(); 2646 continue; 2647 } 2648 2649 // For calls and message sends, use the retained-call logic. 2650 // Delegate inits are a special case in that they're the only 2651 // returns-retained expression that *isn't* surrounded by 2652 // a consume. 2653 } else if (isa<CallExpr>(e) || 2654 (isa<ObjCMessageExpr>(e) && 2655 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) { 2656 llvm::Value *result = emitARCRetainCall(CGF, e); 2657 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType); 2658 return TryEmitResult(result, true); 2659 2660 // Look through pseudo-object expressions. 2661 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 2662 TryEmitResult result 2663 = tryEmitARCRetainPseudoObject(CGF, pseudo); 2664 if (resultType) { 2665 llvm::Value *value = result.getPointer(); 2666 value = CGF.Builder.CreateBitCast(value, resultType); 2667 result.setPointer(value); 2668 } 2669 return result; 2670 } 2671 2672 // Conservatively halt the search at any other expression kind. 2673 break; 2674 } 2675 2676 // We didn't find an obvious production, so emit what we've got and 2677 // tell the caller that we didn't manage to retain. 2678 llvm::Value *result = CGF.EmitScalarExpr(e); 2679 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType); 2680 return TryEmitResult(result, false); 2681 } 2682 2683 static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF, 2684 LValue lvalue, 2685 QualType type) { 2686 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type); 2687 llvm::Value *value = result.getPointer(); 2688 if (!result.getInt()) 2689 value = CGF.EmitARCRetain(type, value); 2690 return value; 2691 } 2692 2693 /// EmitARCRetainScalarExpr - Semantically equivalent to 2694 /// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a 2695 /// best-effort attempt to peephole expressions that naturally produce 2696 /// retained objects. 2697 llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) { 2698 // The retain needs to happen within the full-expression. 2699 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) { 2700 enterFullExpression(cleanups); 2701 RunCleanupsScope scope(*this); 2702 return EmitARCRetainScalarExpr(cleanups->getSubExpr()); 2703 } 2704 2705 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e); 2706 llvm::Value *value = result.getPointer(); 2707 if (!result.getInt()) 2708 value = EmitARCRetain(e->getType(), value); 2709 return value; 2710 } 2711 2712 llvm::Value * 2713 CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) { 2714 // The retain needs to happen within the full-expression. 2715 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) { 2716 enterFullExpression(cleanups); 2717 RunCleanupsScope scope(*this); 2718 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr()); 2719 } 2720 2721 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e); 2722 llvm::Value *value = result.getPointer(); 2723 if (result.getInt()) 2724 value = EmitARCAutorelease(value); 2725 else 2726 value = EmitARCRetainAutorelease(e->getType(), value); 2727 return value; 2728 } 2729 2730 llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) { 2731 llvm::Value *result; 2732 bool doRetain; 2733 2734 if (shouldEmitSeparateBlockRetain(e)) { 2735 result = EmitScalarExpr(e); 2736 doRetain = true; 2737 } else { 2738 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e); 2739 result = subresult.getPointer(); 2740 doRetain = !subresult.getInt(); 2741 } 2742 2743 if (doRetain) 2744 result = EmitARCRetainBlock(result, /*mandatory*/ true); 2745 return EmitObjCConsumeObject(e->getType(), result); 2746 } 2747 2748 llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) { 2749 // In ARC, retain and autorelease the expression. 2750 if (getLangOpts().ObjCAutoRefCount) { 2751 // Do so before running any cleanups for the full-expression. 2752 // EmitARCRetainAutoreleaseScalarExpr does this for us. 2753 return EmitARCRetainAutoreleaseScalarExpr(expr); 2754 } 2755 2756 // Otherwise, use the normal scalar-expression emission. The 2757 // exception machinery doesn't do anything special with the 2758 // exception like retaining it, so there's no safety associated with 2759 // only running cleanups after the throw has started, and when it 2760 // matters it tends to be substantially inferior code. 2761 return EmitScalarExpr(expr); 2762 } 2763 2764 std::pair<LValue,llvm::Value*> 2765 CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e, 2766 bool ignored) { 2767 // Evaluate the RHS first. 2768 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS()); 2769 llvm::Value *value = result.getPointer(); 2770 2771 bool hasImmediateRetain = result.getInt(); 2772 2773 // If we didn't emit a retained object, and the l-value is of block 2774 // type, then we need to emit the block-retain immediately in case 2775 // it invalidates the l-value. 2776 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) { 2777 value = EmitARCRetainBlock(value, /*mandatory*/ false); 2778 hasImmediateRetain = true; 2779 } 2780 2781 LValue lvalue = EmitLValue(e->getLHS()); 2782 2783 // If the RHS was emitted retained, expand this. 2784 if (hasImmediateRetain) { 2785 llvm::Value *oldValue = 2786 EmitLoadOfScalar(lvalue); 2787 EmitStoreOfScalar(value, lvalue); 2788 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime()); 2789 } else { 2790 value = EmitARCStoreStrong(lvalue, value, ignored); 2791 } 2792 2793 return std::pair<LValue,llvm::Value*>(lvalue, value); 2794 } 2795 2796 std::pair<LValue,llvm::Value*> 2797 CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) { 2798 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS()); 2799 LValue lvalue = EmitLValue(e->getLHS()); 2800 2801 EmitStoreOfScalar(value, lvalue); 2802 2803 return std::pair<LValue,llvm::Value*>(lvalue, value); 2804 } 2805 2806 void CodeGenFunction::EmitObjCAutoreleasePoolStmt( 2807 const ObjCAutoreleasePoolStmt &ARPS) { 2808 const Stmt *subStmt = ARPS.getSubStmt(); 2809 const CompoundStmt &S = cast<CompoundStmt>(*subStmt); 2810 2811 CGDebugInfo *DI = getDebugInfo(); 2812 if (DI) 2813 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc()); 2814 2815 // Keep track of the current cleanup stack depth. 2816 RunCleanupsScope Scope(*this); 2817 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) { 2818 llvm::Value *token = EmitObjCAutoreleasePoolPush(); 2819 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token); 2820 } else { 2821 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush(); 2822 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token); 2823 } 2824 2825 for (CompoundStmt::const_body_iterator I = S.body_begin(), 2826 E = S.body_end(); I != E; ++I) 2827 EmitStmt(*I); 2828 2829 if (DI) 2830 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc()); 2831 } 2832 2833 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object, 2834 /// make sure it survives garbage collection until this point. 2835 void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) { 2836 // We just use an inline assembly. 2837 llvm::FunctionType *extenderType 2838 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All); 2839 llvm::Value *extender 2840 = llvm::InlineAsm::get(extenderType, 2841 /* assembly */ "", 2842 /* constraints */ "r", 2843 /* side effects */ true); 2844 2845 object = Builder.CreateBitCast(object, VoidPtrTy); 2846 EmitNounwindRuntimeCall(extender, object); 2847 } 2848 2849 /// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with 2850 /// non-trivial copy assignment function, produce following helper function. 2851 /// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; } 2852 /// 2853 llvm::Constant * 2854 CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction( 2855 const ObjCPropertyImplDecl *PID) { 2856 if (!getLangOpts().CPlusPlus || 2857 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper()) 2858 return 0; 2859 QualType Ty = PID->getPropertyIvarDecl()->getType(); 2860 if (!Ty->isRecordType()) 2861 return 0; 2862 const ObjCPropertyDecl *PD = PID->getPropertyDecl(); 2863 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic))) 2864 return 0; 2865 llvm::Constant * HelperFn = 0; 2866 if (hasTrivialSetExpr(PID)) 2867 return 0; 2868 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null"); 2869 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty))) 2870 return HelperFn; 2871 2872 ASTContext &C = getContext(); 2873 IdentifierInfo *II 2874 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_"); 2875 FunctionDecl *FD = FunctionDecl::Create(C, 2876 C.getTranslationUnitDecl(), 2877 SourceLocation(), 2878 SourceLocation(), II, C.VoidTy, 0, 2879 SC_Static, 2880 false, 2881 false); 2882 2883 QualType DestTy = C.getPointerType(Ty); 2884 QualType SrcTy = Ty; 2885 SrcTy.addConst(); 2886 SrcTy = C.getPointerType(SrcTy); 2887 2888 FunctionArgList args; 2889 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy); 2890 args.push_back(&dstDecl); 2891 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy); 2892 args.push_back(&srcDecl); 2893 2894 const CGFunctionInfo &FI = 2895 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args, 2896 FunctionType::ExtInfo(), 2897 RequiredArgs::All); 2898 2899 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI); 2900 2901 llvm::Function *Fn = 2902 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, 2903 "__assign_helper_atomic_property_", 2904 &CGM.getModule()); 2905 2906 // Initialize debug info if needed. 2907 maybeInitializeDebugInfo(); 2908 2909 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation()); 2910 2911 DeclRefExpr DstExpr(&dstDecl, false, DestTy, 2912 VK_RValue, SourceLocation()); 2913 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(), 2914 VK_LValue, OK_Ordinary, SourceLocation()); 2915 2916 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy, 2917 VK_RValue, SourceLocation()); 2918 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(), 2919 VK_LValue, OK_Ordinary, SourceLocation()); 2920 2921 Expr *Args[2] = { &DST, &SRC }; 2922 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment()); 2923 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(), 2924 Args, DestTy->getPointeeType(), 2925 VK_LValue, SourceLocation(), false); 2926 2927 EmitStmt(&TheCall); 2928 2929 FinishFunction(); 2930 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy); 2931 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn); 2932 return HelperFn; 2933 } 2934 2935 llvm::Constant * 2936 CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction( 2937 const ObjCPropertyImplDecl *PID) { 2938 if (!getLangOpts().CPlusPlus || 2939 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper()) 2940 return 0; 2941 const ObjCPropertyDecl *PD = PID->getPropertyDecl(); 2942 QualType Ty = PD->getType(); 2943 if (!Ty->isRecordType()) 2944 return 0; 2945 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic))) 2946 return 0; 2947 llvm::Constant * HelperFn = 0; 2948 2949 if (hasTrivialGetExpr(PID)) 2950 return 0; 2951 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null"); 2952 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty))) 2953 return HelperFn; 2954 2955 2956 ASTContext &C = getContext(); 2957 IdentifierInfo *II 2958 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_"); 2959 FunctionDecl *FD = FunctionDecl::Create(C, 2960 C.getTranslationUnitDecl(), 2961 SourceLocation(), 2962 SourceLocation(), II, C.VoidTy, 0, 2963 SC_Static, 2964 false, 2965 false); 2966 2967 QualType DestTy = C.getPointerType(Ty); 2968 QualType SrcTy = Ty; 2969 SrcTy.addConst(); 2970 SrcTy = C.getPointerType(SrcTy); 2971 2972 FunctionArgList args; 2973 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy); 2974 args.push_back(&dstDecl); 2975 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy); 2976 args.push_back(&srcDecl); 2977 2978 const CGFunctionInfo &FI = 2979 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args, 2980 FunctionType::ExtInfo(), 2981 RequiredArgs::All); 2982 2983 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI); 2984 2985 llvm::Function *Fn = 2986 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, 2987 "__copy_helper_atomic_property_", &CGM.getModule()); 2988 2989 // Initialize debug info if needed. 2990 maybeInitializeDebugInfo(); 2991 2992 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation()); 2993 2994 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy, 2995 VK_RValue, SourceLocation()); 2996 2997 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(), 2998 VK_LValue, OK_Ordinary, SourceLocation()); 2999 3000 CXXConstructExpr *CXXConstExpr = 3001 cast<CXXConstructExpr>(PID->getGetterCXXConstructor()); 3002 3003 SmallVector<Expr*, 4> ConstructorArgs; 3004 ConstructorArgs.push_back(&SRC); 3005 CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin(); 3006 ++A; 3007 3008 for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end(); 3009 A != AEnd; ++A) 3010 ConstructorArgs.push_back(*A); 3011 3012 CXXConstructExpr *TheCXXConstructExpr = 3013 CXXConstructExpr::Create(C, Ty, SourceLocation(), 3014 CXXConstExpr->getConstructor(), 3015 CXXConstExpr->isElidable(), 3016 ConstructorArgs, 3017 CXXConstExpr->hadMultipleCandidates(), 3018 CXXConstExpr->isListInitialization(), 3019 CXXConstExpr->requiresZeroInitialization(), 3020 CXXConstExpr->getConstructionKind(), 3021 SourceRange()); 3022 3023 DeclRefExpr DstExpr(&dstDecl, false, DestTy, 3024 VK_RValue, SourceLocation()); 3025 3026 RValue DV = EmitAnyExpr(&DstExpr); 3027 CharUnits Alignment 3028 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType()); 3029 EmitAggExpr(TheCXXConstructExpr, 3030 AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(), 3031 AggValueSlot::IsDestructed, 3032 AggValueSlot::DoesNotNeedGCBarriers, 3033 AggValueSlot::IsNotAliased)); 3034 3035 FinishFunction(); 3036 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy); 3037 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn); 3038 return HelperFn; 3039 } 3040 3041 llvm::Value * 3042 CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) { 3043 // Get selectors for retain/autorelease. 3044 IdentifierInfo *CopyID = &getContext().Idents.get("copy"); 3045 Selector CopySelector = 3046 getContext().Selectors.getNullarySelector(CopyID); 3047 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease"); 3048 Selector AutoreleaseSelector = 3049 getContext().Selectors.getNullarySelector(AutoreleaseID); 3050 3051 // Emit calls to retain/autorelease. 3052 CGObjCRuntime &Runtime = CGM.getObjCRuntime(); 3053 llvm::Value *Val = Block; 3054 RValue Result; 3055 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(), 3056 Ty, CopySelector, 3057 Val, CallArgList(), 0, 0); 3058 Val = Result.getScalarVal(); 3059 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(), 3060 Ty, AutoreleaseSelector, 3061 Val, CallArgList(), 0, 0); 3062 Val = Result.getScalarVal(); 3063 return Val; 3064 } 3065 3066 3067 CGObjCRuntime::~CGObjCRuntime() {} 3068