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