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