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