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