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