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