clang API Documentation
00001 //===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This contains code to emit Objective-C code as LLVM code. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "CGDebugInfo.h" 00015 #include "CGObjCRuntime.h" 00016 #include "CodeGenFunction.h" 00017 #include "CodeGenModule.h" 00018 #include "TargetInfo.h" 00019 #include "clang/AST/ASTContext.h" 00020 #include "clang/AST/DeclObjC.h" 00021 #include "clang/AST/StmtObjC.h" 00022 #include "clang/Basic/Diagnostic.h" 00023 #include "llvm/ADT/STLExtras.h" 00024 #include "llvm/Target/TargetData.h" 00025 #include "llvm/InlineAsm.h" 00026 using namespace clang; 00027 using namespace CodeGen; 00028 00029 typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult; 00030 static TryEmitResult 00031 tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e); 00032 static RValue AdjustRelatedResultType(CodeGenFunction &CGF, 00033 const Expr *E, 00034 const ObjCMethodDecl *Method, 00035 RValue Result); 00036 00037 /// Given the address of a variable of pointer type, find the correct 00038 /// null to store into it. 00039 static llvm::Constant *getNullForVariable(llvm::Value *addr) { 00040 llvm::Type *type = 00041 cast<llvm::PointerType>(addr->getType())->getElementType(); 00042 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type)); 00043 } 00044 00045 /// Emits an instance of NSConstantString representing the object. 00046 llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E) 00047 { 00048 llvm::Constant *C = 00049 CGM.getObjCRuntime().GenerateConstantString(E->getString()); 00050 // FIXME: This bitcast should just be made an invariant on the Runtime. 00051 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType())); 00052 } 00053 00054 /// EmitObjCBoxedExpr - This routine generates code to call 00055 /// the appropriate expression boxing method. This will either be 00056 /// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:]. 00057 /// 00058 llvm::Value * 00059 CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) { 00060 // Generate the correct selector for this literal's concrete type. 00061 const Expr *SubExpr = E->getSubExpr(); 00062 // Get the method. 00063 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod(); 00064 assert(BoxingMethod && "BoxingMethod is null"); 00065 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method"); 00066 Selector Sel = BoxingMethod->getSelector(); 00067 00068 // Generate a reference to the class pointer, which will be the receiver. 00069 // Assumes that the method was introduced in the class that should be 00070 // messaged (avoids pulling it out of the result type). 00071 CGObjCRuntime &Runtime = CGM.getObjCRuntime(); 00072 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface(); 00073 llvm::Value *Receiver = Runtime.GetClass(Builder, ClassDecl); 00074 00075 const ParmVarDecl *argDecl = *BoxingMethod->param_begin(); 00076 QualType ArgQT = argDecl->getType().getUnqualifiedType(); 00077 RValue RV = EmitAnyExpr(SubExpr); 00078 CallArgList Args; 00079 Args.add(RV, ArgQT); 00080 00081 RValue result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(), 00082 BoxingMethod->getResultType(), Sel, Receiver, Args, 00083 ClassDecl, BoxingMethod); 00084 return Builder.CreateBitCast(result.getScalarVal(), 00085 ConvertType(E->getType())); 00086 } 00087 00088 llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E, 00089 const ObjCMethodDecl *MethodWithObjects) { 00090 ASTContext &Context = CGM.getContext(); 00091 const ObjCDictionaryLiteral *DLE = 0; 00092 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E); 00093 if (!ALE) 00094 DLE = cast<ObjCDictionaryLiteral>(E); 00095 00096 // Compute the type of the array we're initializing. 00097 uint64_t NumElements = 00098 ALE ? ALE->getNumElements() : DLE->getNumElements(); 00099 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()), 00100 NumElements); 00101 QualType ElementType = Context.getObjCIdType().withConst(); 00102 QualType ElementArrayType 00103 = Context.getConstantArrayType(ElementType, APNumElements, 00104 ArrayType::Normal, /*IndexTypeQuals=*/0); 00105 00106 // Allocate the temporary array(s). 00107 llvm::Value *Objects = CreateMemTemp(ElementArrayType, "objects"); 00108 llvm::Value *Keys = 0; 00109 if (DLE) 00110 Keys = CreateMemTemp(ElementArrayType, "keys"); 00111 00112 // Perform the actual initialialization of the array(s). 00113 for (uint64_t i = 0; i < NumElements; i++) { 00114 if (ALE) { 00115 // Emit the initializer. 00116 const Expr *Rhs = ALE->getElement(i); 00117 LValue LV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i), 00118 ElementType, 00119 Context.getTypeAlignInChars(Rhs->getType()), 00120 Context); 00121 EmitScalarInit(Rhs, /*D=*/0, LV, /*capturedByInit=*/false); 00122 } else { 00123 // Emit the key initializer. 00124 const Expr *Key = DLE->getKeyValueElement(i).Key; 00125 LValue KeyLV = LValue::MakeAddr(Builder.CreateStructGEP(Keys, i), 00126 ElementType, 00127 Context.getTypeAlignInChars(Key->getType()), 00128 Context); 00129 EmitScalarInit(Key, /*D=*/0, KeyLV, /*capturedByInit=*/false); 00130 00131 // Emit the value initializer. 00132 const Expr *Value = DLE->getKeyValueElement(i).Value; 00133 LValue ValueLV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i), 00134 ElementType, 00135 Context.getTypeAlignInChars(Value->getType()), 00136 Context); 00137 EmitScalarInit(Value, /*D=*/0, ValueLV, /*capturedByInit=*/false); 00138 } 00139 } 00140 00141 // Generate the argument list. 00142 CallArgList Args; 00143 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin(); 00144 const ParmVarDecl *argDecl = *PI++; 00145 QualType ArgQT = argDecl->getType().getUnqualifiedType(); 00146 Args.add(RValue::get(Objects), ArgQT); 00147 if (DLE) { 00148 argDecl = *PI++; 00149 ArgQT = argDecl->getType().getUnqualifiedType(); 00150 Args.add(RValue::get(Keys), ArgQT); 00151 } 00152 argDecl = *PI; 00153 ArgQT = argDecl->getType().getUnqualifiedType(); 00154 llvm::Value *Count = 00155 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements); 00156 Args.add(RValue::get(Count), ArgQT); 00157 00158 // Generate a reference to the class pointer, which will be the receiver. 00159 Selector Sel = MethodWithObjects->getSelector(); 00160 QualType ResultType = E->getType(); 00161 const ObjCObjectPointerType *InterfacePointerType 00162 = ResultType->getAsObjCInterfacePointerType(); 00163 ObjCInterfaceDecl *Class 00164 = InterfacePointerType->getObjectType()->getInterface(); 00165 CGObjCRuntime &Runtime = CGM.getObjCRuntime(); 00166 llvm::Value *Receiver = Runtime.GetClass(Builder, Class); 00167 00168 // Generate the message send. 00169 RValue result 00170 = Runtime.GenerateMessageSend(*this, ReturnValueSlot(), 00171 MethodWithObjects->getResultType(), 00172 Sel, 00173 Receiver, Args, Class, 00174 MethodWithObjects); 00175 return Builder.CreateBitCast(result.getScalarVal(), 00176 ConvertType(E->getType())); 00177 } 00178 00179 llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) { 00180 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod()); 00181 } 00182 00183 llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral( 00184 const ObjCDictionaryLiteral *E) { 00185 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod()); 00186 } 00187 00188 /// Emit a selector. 00189 llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) { 00190 // Untyped selector. 00191 // Note that this implementation allows for non-constant strings to be passed 00192 // as arguments to @selector(). Currently, the only thing preventing this 00193 // behaviour is the type checking in the front end. 00194 return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector()); 00195 } 00196 00197 llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) { 00198 // FIXME: This should pass the Decl not the name. 00199 return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol()); 00200 } 00201 00202 /// \brief Adjust the type of the result of an Objective-C message send 00203 /// expression when the method has a related result type. 00204 static RValue AdjustRelatedResultType(CodeGenFunction &CGF, 00205 const Expr *E, 00206 const ObjCMethodDecl *Method, 00207 RValue Result) { 00208 if (!Method) 00209 return Result; 00210 00211 if (!Method->hasRelatedResultType() || 00212 CGF.getContext().hasSameType(E->getType(), Method->getResultType()) || 00213 !Result.isScalar()) 00214 return Result; 00215 00216 // We have applied a related result type. Cast the rvalue appropriately. 00217 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(), 00218 CGF.ConvertType(E->getType()))); 00219 } 00220 00221 /// Decide whether to extend the lifetime of the receiver of a 00222 /// returns-inner-pointer message. 00223 static bool 00224 shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) { 00225 switch (message->getReceiverKind()) { 00226 00227 // For a normal instance message, we should extend unless the 00228 // receiver is loaded from a variable with precise lifetime. 00229 case ObjCMessageExpr::Instance: { 00230 const Expr *receiver = message->getInstanceReceiver(); 00231 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver); 00232 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true; 00233 receiver = ice->getSubExpr()->IgnoreParens(); 00234 00235 // Only __strong variables. 00236 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 00237 return true; 00238 00239 // All ivars and fields have precise lifetime. 00240 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver)) 00241 return false; 00242 00243 // Otherwise, check for variables. 00244 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr()); 00245 if (!declRef) return true; 00246 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl()); 00247 if (!var) return true; 00248 00249 // All variables have precise lifetime except local variables with 00250 // automatic storage duration that aren't specially marked. 00251 return (var->hasLocalStorage() && 00252 !var->hasAttr<ObjCPreciseLifetimeAttr>()); 00253 } 00254 00255 case ObjCMessageExpr::Class: 00256 case ObjCMessageExpr::SuperClass: 00257 // It's never necessary for class objects. 00258 return false; 00259 00260 case ObjCMessageExpr::SuperInstance: 00261 // We generally assume that 'self' lives throughout a method call. 00262 return false; 00263 } 00264 00265 llvm_unreachable("invalid receiver kind"); 00266 } 00267 00268 RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E, 00269 ReturnValueSlot Return) { 00270 // Only the lookup mechanism and first two arguments of the method 00271 // implementation vary between runtimes. We can get the receiver and 00272 // arguments in generic code. 00273 00274 bool isDelegateInit = E->isDelegateInitCall(); 00275 00276 const ObjCMethodDecl *method = E->getMethodDecl(); 00277 00278 // We don't retain the receiver in delegate init calls, and this is 00279 // safe because the receiver value is always loaded from 'self', 00280 // which we zero out. We don't want to Block_copy block receivers, 00281 // though. 00282 bool retainSelf = 00283 (!isDelegateInit && 00284 CGM.getLangOpts().ObjCAutoRefCount && 00285 method && 00286 method->hasAttr<NSConsumesSelfAttr>()); 00287 00288 CGObjCRuntime &Runtime = CGM.getObjCRuntime(); 00289 bool isSuperMessage = false; 00290 bool isClassMessage = false; 00291 ObjCInterfaceDecl *OID = 0; 00292 // Find the receiver 00293 QualType ReceiverType; 00294 llvm::Value *Receiver = 0; 00295 switch (E->getReceiverKind()) { 00296 case ObjCMessageExpr::Instance: 00297 ReceiverType = E->getInstanceReceiver()->getType(); 00298 if (retainSelf) { 00299 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this, 00300 E->getInstanceReceiver()); 00301 Receiver = ter.getPointer(); 00302 if (ter.getInt()) retainSelf = false; 00303 } else 00304 Receiver = EmitScalarExpr(E->getInstanceReceiver()); 00305 break; 00306 00307 case ObjCMessageExpr::Class: { 00308 ReceiverType = E->getClassReceiver(); 00309 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>(); 00310 assert(ObjTy && "Invalid Objective-C class message send"); 00311 OID = ObjTy->getInterface(); 00312 assert(OID && "Invalid Objective-C class message send"); 00313 Receiver = Runtime.GetClass(Builder, OID); 00314 isClassMessage = true; 00315 break; 00316 } 00317 00318 case ObjCMessageExpr::SuperInstance: 00319 ReceiverType = E->getSuperType(); 00320 Receiver = LoadObjCSelf(); 00321 isSuperMessage = true; 00322 break; 00323 00324 case ObjCMessageExpr::SuperClass: 00325 ReceiverType = E->getSuperType(); 00326 Receiver = LoadObjCSelf(); 00327 isSuperMessage = true; 00328 isClassMessage = true; 00329 break; 00330 } 00331 00332 if (retainSelf) 00333 Receiver = EmitARCRetainNonBlock(Receiver); 00334 00335 // In ARC, we sometimes want to "extend the lifetime" 00336 // (i.e. retain+autorelease) of receivers of returns-inner-pointer 00337 // messages. 00338 if (getLangOpts().ObjCAutoRefCount && method && 00339 method->hasAttr<ObjCReturnsInnerPointerAttr>() && 00340 shouldExtendReceiverForInnerPointerMessage(E)) 00341 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver); 00342 00343 QualType ResultType = 00344 method ? method->getResultType() : E->getType(); 00345 00346 CallArgList Args; 00347 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end()); 00348 00349 // For delegate init calls in ARC, do an unsafe store of null into 00350 // self. This represents the call taking direct ownership of that 00351 // value. We have to do this after emitting the other call 00352 // arguments because they might also reference self, but we don't 00353 // have to worry about any of them modifying self because that would 00354 // be an undefined read and write of an object in unordered 00355 // expressions. 00356 if (isDelegateInit) { 00357 assert(getLangOpts().ObjCAutoRefCount && 00358 "delegate init calls should only be marked in ARC"); 00359 00360 // Do an unsafe store of null into self. 00361 llvm::Value *selfAddr = 00362 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()]; 00363 assert(selfAddr && "no self entry for a delegate init call?"); 00364 00365 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr); 00366 } 00367 00368 RValue result; 00369 if (isSuperMessage) { 00370 // super is only valid in an Objective-C method 00371 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl); 00372 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext()); 00373 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType, 00374 E->getSelector(), 00375 OMD->getClassInterface(), 00376 isCategoryImpl, 00377 Receiver, 00378 isClassMessage, 00379 Args, 00380 method); 00381 } else { 00382 result = Runtime.GenerateMessageSend(*this, Return, ResultType, 00383 E->getSelector(), 00384 Receiver, Args, OID, 00385 method); 00386 } 00387 00388 // For delegate init calls in ARC, implicitly store the result of 00389 // the call back into self. This takes ownership of the value. 00390 if (isDelegateInit) { 00391 llvm::Value *selfAddr = 00392 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()]; 00393 llvm::Value *newSelf = result.getScalarVal(); 00394 00395 // The delegate return type isn't necessarily a matching type; in 00396 // fact, it's quite likely to be 'id'. 00397 llvm::Type *selfTy = 00398 cast<llvm::PointerType>(selfAddr->getType())->getElementType(); 00399 newSelf = Builder.CreateBitCast(newSelf, selfTy); 00400 00401 Builder.CreateStore(newSelf, selfAddr); 00402 } 00403 00404 return AdjustRelatedResultType(*this, E, method, result); 00405 } 00406 00407 namespace { 00408 struct FinishARCDealloc : EHScopeStack::Cleanup { 00409 void Emit(CodeGenFunction &CGF, Flags flags) { 00410 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl); 00411 00412 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext()); 00413 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 00414 if (!iface->getSuperClass()) return; 00415 00416 bool isCategory = isa<ObjCCategoryImplDecl>(impl); 00417 00418 // Call [super dealloc] if we have a superclass. 00419 llvm::Value *self = CGF.LoadObjCSelf(); 00420 00421 CallArgList args; 00422 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(), 00423 CGF.getContext().VoidTy, 00424 method->getSelector(), 00425 iface, 00426 isCategory, 00427 self, 00428 /*is class msg*/ false, 00429 args, 00430 method); 00431 } 00432 }; 00433 } 00434 00435 /// StartObjCMethod - Begin emission of an ObjCMethod. This generates 00436 /// the LLVM function and sets the other context used by 00437 /// CodeGenFunction. 00438 void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD, 00439 const ObjCContainerDecl *CD, 00440 SourceLocation StartLoc) { 00441 FunctionArgList args; 00442 // Check if we should generate debug info for this method. 00443 if (CGM.getModuleDebugInfo() && !OMD->hasAttr<NoDebugAttr>()) 00444 DebugInfo = CGM.getModuleDebugInfo(); 00445 00446 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD); 00447 00448 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD); 00449 CGM.SetInternalFunctionAttributes(OMD, Fn, FI); 00450 00451 args.push_back(OMD->getSelfDecl()); 00452 args.push_back(OMD->getCmdDecl()); 00453 00454 for (ObjCMethodDecl::param_const_iterator PI = OMD->param_begin(), 00455 E = OMD->param_end(); PI != E; ++PI) 00456 args.push_back(*PI); 00457 00458 CurGD = OMD; 00459 00460 StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc); 00461 00462 // In ARC, certain methods get an extra cleanup. 00463 if (CGM.getLangOpts().ObjCAutoRefCount && 00464 OMD->isInstanceMethod() && 00465 OMD->getSelector().isUnarySelector()) { 00466 const IdentifierInfo *ident = 00467 OMD->getSelector().getIdentifierInfoForSlot(0); 00468 if (ident->isStr("dealloc")) 00469 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind()); 00470 } 00471 } 00472 00473 static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF, 00474 LValue lvalue, QualType type); 00475 00476 /// Generate an Objective-C method. An Objective-C method is a C function with 00477 /// its pointer, name, and types registered in the class struture. 00478 void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) { 00479 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart()); 00480 EmitStmt(OMD->getBody()); 00481 FinishFunction(OMD->getBodyRBrace()); 00482 } 00483 00484 /// emitStructGetterCall - Call the runtime function to load a property 00485 /// into the return value slot. 00486 static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar, 00487 bool isAtomic, bool hasStrong) { 00488 ASTContext &Context = CGF.getContext(); 00489 00490 llvm::Value *src = 00491 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), 00492 ivar, 0).getAddress(); 00493 00494 // objc_copyStruct (ReturnValue, &structIvar, 00495 // sizeof (Type of Ivar), isAtomic, false); 00496 CallArgList args; 00497 00498 llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy); 00499 args.add(RValue::get(dest), Context.VoidPtrTy); 00500 00501 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy); 00502 args.add(RValue::get(src), Context.VoidPtrTy); 00503 00504 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType()); 00505 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType()); 00506 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy); 00507 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy); 00508 00509 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction(); 00510 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(Context.VoidTy, args, 00511 FunctionType::ExtInfo(), 00512 RequiredArgs::All), 00513 fn, ReturnValueSlot(), args); 00514 } 00515 00516 /// Determine whether the given architecture supports unaligned atomic 00517 /// accesses. They don't have to be fast, just faster than a function 00518 /// call and a mutex. 00519 static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) { 00520 // FIXME: Allow unaligned atomic load/store on x86. (It is not 00521 // currently supported by the backend.) 00522 return 0; 00523 } 00524 00525 /// Return the maximum size that permits atomic accesses for the given 00526 /// architecture. 00527 static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM, 00528 llvm::Triple::ArchType arch) { 00529 // ARM has 8-byte atomic accesses, but it's not clear whether we 00530 // want to rely on them here. 00531 00532 // In the default case, just assume that any size up to a pointer is 00533 // fine given adequate alignment. 00534 return CharUnits::fromQuantity(CGM.PointerSizeInBytes); 00535 } 00536 00537 namespace { 00538 class PropertyImplStrategy { 00539 public: 00540 enum StrategyKind { 00541 /// The 'native' strategy is to use the architecture's provided 00542 /// reads and writes. 00543 Native, 00544 00545 /// Use objc_setProperty and objc_getProperty. 00546 GetSetProperty, 00547 00548 /// Use objc_setProperty for the setter, but use expression 00549 /// evaluation for the getter. 00550 SetPropertyAndExpressionGet, 00551 00552 /// Use objc_copyStruct. 00553 CopyStruct, 00554 00555 /// The 'expression' strategy is to emit normal assignment or 00556 /// lvalue-to-rvalue expressions. 00557 Expression 00558 }; 00559 00560 StrategyKind getKind() const { return StrategyKind(Kind); } 00561 00562 bool hasStrongMember() const { return HasStrong; } 00563 bool isAtomic() const { return IsAtomic; } 00564 bool isCopy() const { return IsCopy; } 00565 00566 CharUnits getIvarSize() const { return IvarSize; } 00567 CharUnits getIvarAlignment() const { return IvarAlignment; } 00568 00569 PropertyImplStrategy(CodeGenModule &CGM, 00570 const ObjCPropertyImplDecl *propImpl); 00571 00572 private: 00573 unsigned Kind : 8; 00574 unsigned IsAtomic : 1; 00575 unsigned IsCopy : 1; 00576 unsigned HasStrong : 1; 00577 00578 CharUnits IvarSize; 00579 CharUnits IvarAlignment; 00580 }; 00581 } 00582 00583 /// Pick an implementation strategy for the the given property synthesis. 00584 PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM, 00585 const ObjCPropertyImplDecl *propImpl) { 00586 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl(); 00587 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind(); 00588 00589 IsCopy = (setterKind == ObjCPropertyDecl::Copy); 00590 IsAtomic = prop->isAtomic(); 00591 HasStrong = false; // doesn't matter here. 00592 00593 // Evaluate the ivar's size and alignment. 00594 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl(); 00595 QualType ivarType = ivar->getType(); 00596 llvm::tie(IvarSize, IvarAlignment) 00597 = CGM.getContext().getTypeInfoInChars(ivarType); 00598 00599 // If we have a copy property, we always have to use getProperty/setProperty. 00600 // TODO: we could actually use setProperty and an expression for non-atomics. 00601 if (IsCopy) { 00602 Kind = GetSetProperty; 00603 return; 00604 } 00605 00606 // Handle retain. 00607 if (setterKind == ObjCPropertyDecl::Retain) { 00608 // In GC-only, there's nothing special that needs to be done. 00609 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) { 00610 // fallthrough 00611 00612 // In ARC, if the property is non-atomic, use expression emission, 00613 // which translates to objc_storeStrong. This isn't required, but 00614 // it's slightly nicer. 00615 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) { 00616 Kind = Expression; 00617 return; 00618 00619 // Otherwise, we need to at least use setProperty. However, if 00620 // the property isn't atomic, we can use normal expression 00621 // emission for the getter. 00622 } else if (!IsAtomic) { 00623 Kind = SetPropertyAndExpressionGet; 00624 return; 00625 00626 // Otherwise, we have to use both setProperty and getProperty. 00627 } else { 00628 Kind = GetSetProperty; 00629 return; 00630 } 00631 } 00632 00633 // If we're not atomic, just use expression accesses. 00634 if (!IsAtomic) { 00635 Kind = Expression; 00636 return; 00637 } 00638 00639 // Properties on bitfield ivars need to be emitted using expression 00640 // accesses even if they're nominally atomic. 00641 if (ivar->isBitField()) { 00642 Kind = Expression; 00643 return; 00644 } 00645 00646 // GC-qualified or ARC-qualified ivars need to be emitted as 00647 // expressions. This actually works out to being atomic anyway, 00648 // except for ARC __strong, but that should trigger the above code. 00649 if (ivarType.hasNonTrivialObjCLifetime() || 00650 (CGM.getLangOpts().getGC() && 00651 CGM.getContext().getObjCGCAttrKind(ivarType))) { 00652 Kind = Expression; 00653 return; 00654 } 00655 00656 // Compute whether the ivar has strong members. 00657 if (CGM.getLangOpts().getGC()) 00658 if (const RecordType *recordType = ivarType->getAs<RecordType>()) 00659 HasStrong = recordType->getDecl()->hasObjectMember(); 00660 00661 // We can never access structs with object members with a native 00662 // access, because we need to use write barriers. This is what 00663 // objc_copyStruct is for. 00664 if (HasStrong) { 00665 Kind = CopyStruct; 00666 return; 00667 } 00668 00669 // Otherwise, this is target-dependent and based on the size and 00670 // alignment of the ivar. 00671 00672 // If the size of the ivar is not a power of two, give up. We don't 00673 // want to get into the business of doing compare-and-swaps. 00674 if (!IvarSize.isPowerOfTwo()) { 00675 Kind = CopyStruct; 00676 return; 00677 } 00678 00679 llvm::Triple::ArchType arch = 00680 CGM.getContext().getTargetInfo().getTriple().getArch(); 00681 00682 // Most architectures require memory to fit within a single cache 00683 // line, so the alignment has to be at least the size of the access. 00684 // Otherwise we have to grab a lock. 00685 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) { 00686 Kind = CopyStruct; 00687 return; 00688 } 00689 00690 // If the ivar's size exceeds the architecture's maximum atomic 00691 // access size, we have to use CopyStruct. 00692 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) { 00693 Kind = CopyStruct; 00694 return; 00695 } 00696 00697 // Otherwise, we can use native loads and stores. 00698 Kind = Native; 00699 } 00700 00701 /// GenerateObjCGetter - Generate an Objective-C property getter 00702 /// function. The given Decl must be an ObjCImplementationDecl. @synthesize 00703 /// is illegal within a category. 00704 void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP, 00705 const ObjCPropertyImplDecl *PID) { 00706 llvm::Constant *AtomicHelperFn = 00707 GenerateObjCAtomicGetterCopyHelperFunction(PID); 00708 const ObjCPropertyDecl *PD = PID->getPropertyDecl(); 00709 ObjCMethodDecl *OMD = PD->getGetterMethodDecl(); 00710 assert(OMD && "Invalid call to generate getter (empty method)"); 00711 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart()); 00712 00713 generateObjCGetterBody(IMP, PID, AtomicHelperFn); 00714 00715 FinishFunction(); 00716 } 00717 00718 static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) { 00719 const Expr *getter = propImpl->getGetterCXXConstructor(); 00720 if (!getter) return true; 00721 00722 // Sema only makes only of these when the ivar has a C++ class type, 00723 // so the form is pretty constrained. 00724 00725 // If the property has a reference type, we might just be binding a 00726 // reference, in which case the result will be a gl-value. We should 00727 // treat this as a non-trivial operation. 00728 if (getter->isGLValue()) 00729 return false; 00730 00731 // If we selected a trivial copy-constructor, we're okay. 00732 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter)) 00733 return (construct->getConstructor()->isTrivial()); 00734 00735 // The constructor might require cleanups (in which case it's never 00736 // trivial). 00737 assert(isa<ExprWithCleanups>(getter)); 00738 return false; 00739 } 00740 00741 /// emitCPPObjectAtomicGetterCall - Call the runtime function to 00742 /// copy the ivar into the resturn slot. 00743 static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF, 00744 llvm::Value *returnAddr, 00745 ObjCIvarDecl *ivar, 00746 llvm::Constant *AtomicHelperFn) { 00747 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar, 00748 // AtomicHelperFn); 00749 CallArgList args; 00750 00751 // The 1st argument is the return Slot. 00752 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy); 00753 00754 // The 2nd argument is the address of the ivar. 00755 llvm::Value *ivarAddr = 00756 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), 00757 CGF.LoadObjCSelf(), ivar, 0).getAddress(); 00758 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy); 00759 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy); 00760 00761 // Third argument is the helper function. 00762 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy); 00763 00764 llvm::Value *copyCppAtomicObjectFn = 00765 CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction(); 00766 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args, 00767 FunctionType::ExtInfo(), 00768 RequiredArgs::All), 00769 copyCppAtomicObjectFn, ReturnValueSlot(), args); 00770 } 00771 00772 void 00773 CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl, 00774 const ObjCPropertyImplDecl *propImpl, 00775 llvm::Constant *AtomicHelperFn) { 00776 // If there's a non-trivial 'get' expression, we just have to emit that. 00777 if (!hasTrivialGetExpr(propImpl)) { 00778 if (!AtomicHelperFn) { 00779 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(), 00780 /*nrvo*/ 0); 00781 EmitReturnStmt(ret); 00782 } 00783 else { 00784 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl(); 00785 emitCPPObjectAtomicGetterCall(*this, ReturnValue, 00786 ivar, AtomicHelperFn); 00787 } 00788 return; 00789 } 00790 00791 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl(); 00792 QualType propType = prop->getType(); 00793 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl(); 00794 00795 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl(); 00796 00797 // Pick an implementation strategy. 00798 PropertyImplStrategy strategy(CGM, propImpl); 00799 switch (strategy.getKind()) { 00800 case PropertyImplStrategy::Native: { 00801 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0); 00802 00803 // Currently, all atomic accesses have to be through integer 00804 // types, so there's no point in trying to pick a prettier type. 00805 llvm::Type *bitcastType = 00806 llvm::Type::getIntNTy(getLLVMContext(), 00807 getContext().toBits(strategy.getIvarSize())); 00808 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay 00809 00810 // Perform an atomic load. This does not impose ordering constraints. 00811 llvm::Value *ivarAddr = LV.getAddress(); 00812 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType); 00813 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load"); 00814 load->setAlignment(strategy.getIvarAlignment().getQuantity()); 00815 load->setAtomic(llvm::Unordered); 00816 00817 // Store that value into the return address. Doing this with a 00818 // bitcast is likely to produce some pretty ugly IR, but it's not 00819 // the *most* terrible thing in the world. 00820 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType)); 00821 00822 // Make sure we don't do an autorelease. 00823 AutoreleaseResult = false; 00824 return; 00825 } 00826 00827 case PropertyImplStrategy::GetSetProperty: { 00828 llvm::Value *getPropertyFn = 00829 CGM.getObjCRuntime().GetPropertyGetFunction(); 00830 if (!getPropertyFn) { 00831 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy"); 00832 return; 00833 } 00834 00835 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true). 00836 // FIXME: Can't this be simpler? This might even be worse than the 00837 // corresponding gcc code. 00838 llvm::Value *cmd = 00839 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd"); 00840 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy); 00841 llvm::Value *ivarOffset = 00842 EmitIvarOffset(classImpl->getClassInterface(), ivar); 00843 00844 CallArgList args; 00845 args.add(RValue::get(self), getContext().getObjCIdType()); 00846 args.add(RValue::get(cmd), getContext().getObjCSelType()); 00847 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType()); 00848 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())), 00849 getContext().BoolTy); 00850 00851 // FIXME: We shouldn't need to get the function info here, the 00852 // runtime already should have computed it to build the function. 00853 RValue RV = EmitCall(getTypes().arrangeFunctionCall(propType, args, 00854 FunctionType::ExtInfo(), 00855 RequiredArgs::All), 00856 getPropertyFn, ReturnValueSlot(), args); 00857 00858 // We need to fix the type here. Ivars with copy & retain are 00859 // always objects so we don't need to worry about complex or 00860 // aggregates. 00861 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(), 00862 getTypes().ConvertType(getterMethod->getResultType()))); 00863 00864 EmitReturnOfRValue(RV, propType); 00865 00866 // objc_getProperty does an autorelease, so we should suppress ours. 00867 AutoreleaseResult = false; 00868 00869 return; 00870 } 00871 00872 case PropertyImplStrategy::CopyStruct: 00873 emitStructGetterCall(*this, ivar, strategy.isAtomic(), 00874 strategy.hasStrongMember()); 00875 return; 00876 00877 case PropertyImplStrategy::Expression: 00878 case PropertyImplStrategy::SetPropertyAndExpressionGet: { 00879 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0); 00880 00881 QualType ivarType = ivar->getType(); 00882 if (ivarType->isAnyComplexType()) { 00883 ComplexPairTy pair = LoadComplexFromAddr(LV.getAddress(), 00884 LV.isVolatileQualified()); 00885 StoreComplexToAddr(pair, ReturnValue, LV.isVolatileQualified()); 00886 } else if (hasAggregateLLVMType(ivarType)) { 00887 // The return value slot is guaranteed to not be aliased, but 00888 // that's not necessarily the same as "on the stack", so 00889 // we still potentially need objc_memmove_collectable. 00890 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType); 00891 } else { 00892 llvm::Value *value; 00893 if (propType->isReferenceType()) { 00894 value = LV.getAddress(); 00895 } else { 00896 // We want to load and autoreleaseReturnValue ARC __weak ivars. 00897 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) { 00898 value = emitARCRetainLoadOfScalar(*this, LV, ivarType); 00899 00900 // Otherwise we want to do a simple load, suppressing the 00901 // final autorelease. 00902 } else { 00903 value = EmitLoadOfLValue(LV).getScalarVal(); 00904 AutoreleaseResult = false; 00905 } 00906 00907 value = Builder.CreateBitCast(value, ConvertType(propType)); 00908 } 00909 00910 EmitReturnOfRValue(RValue::get(value), propType); 00911 } 00912 return; 00913 } 00914 00915 } 00916 llvm_unreachable("bad @property implementation strategy!"); 00917 } 00918 00919 /// emitStructSetterCall - Call the runtime function to store the value 00920 /// from the first formal parameter into the given ivar. 00921 static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD, 00922 ObjCIvarDecl *ivar) { 00923 // objc_copyStruct (&structIvar, &Arg, 00924 // sizeof (struct something), true, false); 00925 CallArgList args; 00926 00927 // The first argument is the address of the ivar. 00928 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), 00929 CGF.LoadObjCSelf(), ivar, 0) 00930 .getAddress(); 00931 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy); 00932 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy); 00933 00934 // The second argument is the address of the parameter variable. 00935 ParmVarDecl *argVar = *OMD->param_begin(); 00936 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(), 00937 VK_LValue, SourceLocation()); 00938 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress(); 00939 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy); 00940 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy); 00941 00942 // The third argument is the sizeof the type. 00943 llvm::Value *size = 00944 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType())); 00945 args.add(RValue::get(size), CGF.getContext().getSizeType()); 00946 00947 // The fourth argument is the 'isAtomic' flag. 00948 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy); 00949 00950 // The fifth argument is the 'hasStrong' flag. 00951 // FIXME: should this really always be false? 00952 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy); 00953 00954 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction(); 00955 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args, 00956 FunctionType::ExtInfo(), 00957 RequiredArgs::All), 00958 copyStructFn, ReturnValueSlot(), args); 00959 } 00960 00961 /// emitCPPObjectAtomicSetterCall - Call the runtime function to store 00962 /// the value from the first formal parameter into the given ivar, using 00963 /// the Cpp API for atomic Cpp objects with non-trivial copy assignment. 00964 static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF, 00965 ObjCMethodDecl *OMD, 00966 ObjCIvarDecl *ivar, 00967 llvm::Constant *AtomicHelperFn) { 00968 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg, 00969 // AtomicHelperFn); 00970 CallArgList args; 00971 00972 // The first argument is the address of the ivar. 00973 llvm::Value *ivarAddr = 00974 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), 00975 CGF.LoadObjCSelf(), ivar, 0).getAddress(); 00976 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy); 00977 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy); 00978 00979 // The second argument is the address of the parameter variable. 00980 ParmVarDecl *argVar = *OMD->param_begin(); 00981 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(), 00982 VK_LValue, SourceLocation()); 00983 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress(); 00984 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy); 00985 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy); 00986 00987 // Third argument is the helper function. 00988 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy); 00989 00990 llvm::Value *copyCppAtomicObjectFn = 00991 CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction(); 00992 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args, 00993 FunctionType::ExtInfo(), 00994 RequiredArgs::All), 00995 copyCppAtomicObjectFn, ReturnValueSlot(), args); 00996 00997 00998 } 00999 01000 01001 static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) { 01002 Expr *setter = PID->getSetterCXXAssignment(); 01003 if (!setter) return true; 01004 01005 // Sema only makes only of these when the ivar has a C++ class type, 01006 // so the form is pretty constrained. 01007 01008 // An operator call is trivial if the function it calls is trivial. 01009 // This also implies that there's nothing non-trivial going on with 01010 // the arguments, because operator= can only be trivial if it's a 01011 // synthesized assignment operator and therefore both parameters are 01012 // references. 01013 if (CallExpr *call = dyn_cast<CallExpr>(setter)) { 01014 if (const FunctionDecl *callee 01015 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl())) 01016 if (callee->isTrivial()) 01017 return true; 01018 return false; 01019 } 01020 01021 assert(isa<ExprWithCleanups>(setter)); 01022 return false; 01023 } 01024 01025 static bool UseOptimizedSetter(CodeGenModule &CGM) { 01026 if (CGM.getLangOpts().getGC() != LangOptions::NonGC) 01027 return false; 01028 const TargetInfo &Target = CGM.getContext().getTargetInfo(); 01029 01030 if (Target.getPlatformName() != "macosx") 01031 return false; 01032 01033 return Target.getPlatformMinVersion() >= VersionTuple(10, 8); 01034 } 01035 01036 void 01037 CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl, 01038 const ObjCPropertyImplDecl *propImpl, 01039 llvm::Constant *AtomicHelperFn) { 01040 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl(); 01041 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl(); 01042 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl(); 01043 01044 // Just use the setter expression if Sema gave us one and it's 01045 // non-trivial. 01046 if (!hasTrivialSetExpr(propImpl)) { 01047 if (!AtomicHelperFn) 01048 // If non-atomic, assignment is called directly. 01049 EmitStmt(propImpl->getSetterCXXAssignment()); 01050 else 01051 // If atomic, assignment is called via a locking api. 01052 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar, 01053 AtomicHelperFn); 01054 return; 01055 } 01056 01057 PropertyImplStrategy strategy(CGM, propImpl); 01058 switch (strategy.getKind()) { 01059 case PropertyImplStrategy::Native: { 01060 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()]; 01061 01062 LValue ivarLValue = 01063 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0); 01064 llvm::Value *ivarAddr = ivarLValue.getAddress(); 01065 01066 // Currently, all atomic accesses have to be through integer 01067 // types, so there's no point in trying to pick a prettier type. 01068 llvm::Type *bitcastType = 01069 llvm::Type::getIntNTy(getLLVMContext(), 01070 getContext().toBits(strategy.getIvarSize())); 01071 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay 01072 01073 // Cast both arguments to the chosen operation type. 01074 argAddr = Builder.CreateBitCast(argAddr, bitcastType); 01075 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType); 01076 01077 // This bitcast load is likely to cause some nasty IR. 01078 llvm::Value *load = Builder.CreateLoad(argAddr); 01079 01080 // Perform an atomic store. There are no memory ordering requirements. 01081 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr); 01082 store->setAlignment(strategy.getIvarAlignment().getQuantity()); 01083 store->setAtomic(llvm::Unordered); 01084 return; 01085 } 01086 01087 case PropertyImplStrategy::GetSetProperty: 01088 case PropertyImplStrategy::SetPropertyAndExpressionGet: { 01089 01090 llvm::Value *setOptimizedPropertyFn = 0; 01091 llvm::Value *setPropertyFn = 0; 01092 if (UseOptimizedSetter(CGM)) { 01093 // 10.8 code and GC is off 01094 setOptimizedPropertyFn = 01095 CGM.getObjCRuntime() 01096 .GetOptimizedPropertySetFunction(strategy.isAtomic(), 01097 strategy.isCopy()); 01098 if (!setOptimizedPropertyFn) { 01099 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI"); 01100 return; 01101 } 01102 } 01103 else { 01104 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction(); 01105 if (!setPropertyFn) { 01106 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy"); 01107 return; 01108 } 01109 } 01110 01111 // Emit objc_setProperty((id) self, _cmd, offset, arg, 01112 // <is-atomic>, <is-copy>). 01113 llvm::Value *cmd = 01114 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]); 01115 llvm::Value *self = 01116 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy); 01117 llvm::Value *ivarOffset = 01118 EmitIvarOffset(classImpl->getClassInterface(), ivar); 01119 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()]; 01120 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy); 01121 01122 CallArgList args; 01123 args.add(RValue::get(self), getContext().getObjCIdType()); 01124 args.add(RValue::get(cmd), getContext().getObjCSelType()); 01125 if (setOptimizedPropertyFn) { 01126 args.add(RValue::get(arg), getContext().getObjCIdType()); 01127 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType()); 01128 EmitCall(getTypes().arrangeFunctionCall(getContext().VoidTy, args, 01129 FunctionType::ExtInfo(), 01130 RequiredArgs::All), 01131 setOptimizedPropertyFn, ReturnValueSlot(), args); 01132 } else { 01133 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType()); 01134 args.add(RValue::get(arg), getContext().getObjCIdType()); 01135 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())), 01136 getContext().BoolTy); 01137 args.add(RValue::get(Builder.getInt1(strategy.isCopy())), 01138 getContext().BoolTy); 01139 // FIXME: We shouldn't need to get the function info here, the runtime 01140 // already should have computed it to build the function. 01141 EmitCall(getTypes().arrangeFunctionCall(getContext().VoidTy, args, 01142 FunctionType::ExtInfo(), 01143 RequiredArgs::All), 01144 setPropertyFn, ReturnValueSlot(), args); 01145 } 01146 01147 return; 01148 } 01149 01150 case PropertyImplStrategy::CopyStruct: 01151 emitStructSetterCall(*this, setterMethod, ivar); 01152 return; 01153 01154 case PropertyImplStrategy::Expression: 01155 break; 01156 } 01157 01158 // Otherwise, fake up some ASTs and emit a normal assignment. 01159 ValueDecl *selfDecl = setterMethod->getSelfDecl(); 01160 DeclRefExpr self(selfDecl, false, selfDecl->getType(), 01161 VK_LValue, SourceLocation()); 01162 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack, 01163 selfDecl->getType(), CK_LValueToRValue, &self, 01164 VK_RValue); 01165 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(), 01166 SourceLocation(), &selfLoad, true, true); 01167 01168 ParmVarDecl *argDecl = *setterMethod->param_begin(); 01169 QualType argType = argDecl->getType().getNonReferenceType(); 01170 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation()); 01171 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack, 01172 argType.getUnqualifiedType(), CK_LValueToRValue, 01173 &arg, VK_RValue); 01174 01175 // The property type can differ from the ivar type in some situations with 01176 // Objective-C pointer types, we can always bit cast the RHS in these cases. 01177 // The following absurdity is just to ensure well-formed IR. 01178 CastKind argCK = CK_NoOp; 01179 if (ivarRef.getType()->isObjCObjectPointerType()) { 01180 if (argLoad.getType()->isObjCObjectPointerType()) 01181 argCK = CK_BitCast; 01182 else if (argLoad.getType()->isBlockPointerType()) 01183 argCK = CK_BlockPointerToObjCPointerCast; 01184 else 01185 argCK = CK_CPointerToObjCPointerCast; 01186 } else if (ivarRef.getType()->isBlockPointerType()) { 01187 if (argLoad.getType()->isBlockPointerType()) 01188 argCK = CK_BitCast; 01189 else 01190 argCK = CK_AnyPointerToBlockPointerCast; 01191 } else if (ivarRef.getType()->isPointerType()) { 01192 argCK = CK_BitCast; 01193 } 01194 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack, 01195 ivarRef.getType(), argCK, &argLoad, 01196 VK_RValue); 01197 Expr *finalArg = &argLoad; 01198 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(), 01199 argLoad.getType())) 01200 finalArg = &argCast; 01201 01202 01203 BinaryOperator assign(&ivarRef, finalArg, BO_Assign, 01204 ivarRef.getType(), VK_RValue, OK_Ordinary, 01205 SourceLocation()); 01206 EmitStmt(&assign); 01207 } 01208 01209 /// GenerateObjCSetter - Generate an Objective-C property setter 01210 /// function. The given Decl must be an ObjCImplementationDecl. @synthesize 01211 /// is illegal within a category. 01212 void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP, 01213 const ObjCPropertyImplDecl *PID) { 01214 llvm::Constant *AtomicHelperFn = 01215 GenerateObjCAtomicSetterCopyHelperFunction(PID); 01216 const ObjCPropertyDecl *PD = PID->getPropertyDecl(); 01217 ObjCMethodDecl *OMD = PD->getSetterMethodDecl(); 01218 assert(OMD && "Invalid call to generate setter (empty method)"); 01219 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart()); 01220 01221 generateObjCSetterBody(IMP, PID, AtomicHelperFn); 01222 01223 FinishFunction(); 01224 } 01225 01226 namespace { 01227 struct DestroyIvar : EHScopeStack::Cleanup { 01228 private: 01229 llvm::Value *addr; 01230 const ObjCIvarDecl *ivar; 01231 CodeGenFunction::Destroyer *destroyer; 01232 bool useEHCleanupForArray; 01233 public: 01234 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar, 01235 CodeGenFunction::Destroyer *destroyer, 01236 bool useEHCleanupForArray) 01237 : addr(addr), ivar(ivar), destroyer(destroyer), 01238 useEHCleanupForArray(useEHCleanupForArray) {} 01239 01240 void Emit(CodeGenFunction &CGF, Flags flags) { 01241 LValue lvalue 01242 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0); 01243 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer, 01244 flags.isForNormalCleanup() && useEHCleanupForArray); 01245 } 01246 }; 01247 } 01248 01249 /// Like CodeGenFunction::destroyARCStrong, but do it with a call. 01250 static void destroyARCStrongWithStore(CodeGenFunction &CGF, 01251 llvm::Value *addr, 01252 QualType type) { 01253 llvm::Value *null = getNullForVariable(addr); 01254 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true); 01255 } 01256 01257 static void emitCXXDestructMethod(CodeGenFunction &CGF, 01258 ObjCImplementationDecl *impl) { 01259 CodeGenFunction::RunCleanupsScope scope(CGF); 01260 01261 llvm::Value *self = CGF.LoadObjCSelf(); 01262 01263 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 01264 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 01265 ivar; ivar = ivar->getNextIvar()) { 01266 QualType type = ivar->getType(); 01267 01268 // Check whether the ivar is a destructible type. 01269 QualType::DestructionKind dtorKind = type.isDestructedType(); 01270 if (!dtorKind) continue; 01271 01272 CodeGenFunction::Destroyer *destroyer = 0; 01273 01274 // Use a call to objc_storeStrong to destroy strong ivars, for the 01275 // general benefit of the tools. 01276 if (dtorKind == QualType::DK_objc_strong_lifetime) { 01277 destroyer = destroyARCStrongWithStore; 01278 01279 // Otherwise use the default for the destruction kind. 01280 } else { 01281 destroyer = CGF.getDestroyer(dtorKind); 01282 } 01283 01284 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind); 01285 01286 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer, 01287 cleanupKind & EHCleanup); 01288 } 01289 01290 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?"); 01291 } 01292 01293 void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, 01294 ObjCMethodDecl *MD, 01295 bool ctor) { 01296 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface()); 01297 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart()); 01298 01299 // Emit .cxx_construct. 01300 if (ctor) { 01301 // Suppress the final autorelease in ARC. 01302 AutoreleaseResult = false; 01303 01304 SmallVector<CXXCtorInitializer *, 8> IvarInitializers; 01305 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(), 01306 E = IMP->init_end(); B != E; ++B) { 01307 CXXCtorInitializer *IvarInit = (*B); 01308 FieldDecl *Field = IvarInit->getAnyMember(); 01309 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field); 01310 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), 01311 LoadObjCSelf(), Ivar, 0); 01312 EmitAggExpr(IvarInit->getInit(), 01313 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed, 01314 AggValueSlot::DoesNotNeedGCBarriers, 01315 AggValueSlot::IsNotAliased)); 01316 } 01317 // constructor returns 'self'. 01318 CodeGenTypes &Types = CGM.getTypes(); 01319 QualType IdTy(CGM.getContext().getObjCIdType()); 01320 llvm::Value *SelfAsId = 01321 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy)); 01322 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy); 01323 01324 // Emit .cxx_destruct. 01325 } else { 01326 emitCXXDestructMethod(*this, IMP); 01327 } 01328 FinishFunction(); 01329 } 01330 01331 bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) { 01332 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(); 01333 it++; it++; 01334 const ABIArgInfo &AI = it->info; 01335 // FIXME. Is this sufficient check? 01336 return (AI.getKind() == ABIArgInfo::Indirect); 01337 } 01338 01339 bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) { 01340 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) 01341 return false; 01342 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>()) 01343 return FDTTy->getDecl()->hasObjectMember(); 01344 return false; 01345 } 01346 01347 llvm::Value *CodeGenFunction::LoadObjCSelf() { 01348 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl); 01349 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self"); 01350 } 01351 01352 QualType CodeGenFunction::TypeOfSelfObject() { 01353 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl); 01354 ImplicitParamDecl *selfDecl = OMD->getSelfDecl(); 01355 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>( 01356 getContext().getCanonicalType(selfDecl->getType())); 01357 return PTy->getPointeeType(); 01358 } 01359 01360 void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){ 01361 llvm::Constant *EnumerationMutationFn = 01362 CGM.getObjCRuntime().EnumerationMutationFunction(); 01363 01364 if (!EnumerationMutationFn) { 01365 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime"); 01366 return; 01367 } 01368 01369 CGDebugInfo *DI = getDebugInfo(); 01370 if (DI) 01371 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin()); 01372 01373 // The local variable comes into scope immediately. 01374 AutoVarEmission variable = AutoVarEmission::invalid(); 01375 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) 01376 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl())); 01377 01378 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end"); 01379 01380 // Fast enumeration state. 01381 QualType StateTy = CGM.getObjCFastEnumerationStateType(); 01382 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr"); 01383 EmitNullInitialization(StatePtr, StateTy); 01384 01385 // Number of elements in the items array. 01386 static const unsigned NumItems = 16; 01387 01388 // Fetch the countByEnumeratingWithState:objects:count: selector. 01389 IdentifierInfo *II[] = { 01390 &CGM.getContext().Idents.get("countByEnumeratingWithState"), 01391 &CGM.getContext().Idents.get("objects"), 01392 &CGM.getContext().Idents.get("count") 01393 }; 01394 Selector FastEnumSel = 01395 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]); 01396 01397 QualType ItemsTy = 01398 getContext().getConstantArrayType(getContext().getObjCIdType(), 01399 llvm::APInt(32, NumItems), 01400 ArrayType::Normal, 0); 01401 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr"); 01402 01403 // Emit the collection pointer. In ARC, we do a retain. 01404 llvm::Value *Collection; 01405 if (getLangOpts().ObjCAutoRefCount) { 01406 Collection = EmitARCRetainScalarExpr(S.getCollection()); 01407 01408 // Enter a cleanup to do the release. 01409 EmitObjCConsumeObject(S.getCollection()->getType(), Collection); 01410 } else { 01411 Collection = EmitScalarExpr(S.getCollection()); 01412 } 01413 01414 // The 'continue' label needs to appear within the cleanup for the 01415 // collection object. 01416 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next"); 01417 01418 // Send it our message: 01419 CallArgList Args; 01420 01421 // The first argument is a temporary of the enumeration-state type. 01422 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy)); 01423 01424 // The second argument is a temporary array with space for NumItems 01425 // pointers. We'll actually be loading elements from the array 01426 // pointer written into the control state; this buffer is so that 01427 // collections that *aren't* backed by arrays can still queue up 01428 // batches of elements. 01429 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy)); 01430 01431 // The third argument is the capacity of that temporary array. 01432 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy); 01433 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems); 01434 Args.add(RValue::get(Count), getContext().UnsignedLongTy); 01435 01436 // Start the enumeration. 01437 RValue CountRV = 01438 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(), 01439 getContext().UnsignedLongTy, 01440 FastEnumSel, 01441 Collection, Args); 01442 01443 // The initial number of objects that were returned in the buffer. 01444 llvm::Value *initialBufferLimit = CountRV.getScalarVal(); 01445 01446 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty"); 01447 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit"); 01448 01449 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy); 01450 01451 // If the limit pointer was zero to begin with, the collection is 01452 // empty; skip all this. 01453 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), 01454 EmptyBB, LoopInitBB); 01455 01456 // Otherwise, initialize the loop. 01457 EmitBlock(LoopInitBB); 01458 01459 // Save the initial mutations value. This is the value at an 01460 // address that was written into the state object by 01461 // countByEnumeratingWithState:objects:count:. 01462 llvm::Value *StateMutationsPtrPtr = 01463 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr"); 01464 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, 01465 "mutationsptr"); 01466 01467 llvm::Value *initialMutations = 01468 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations"); 01469 01470 // Start looping. This is the point we return to whenever we have a 01471 // fresh, non-empty batch of objects. 01472 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody"); 01473 EmitBlock(LoopBodyBB); 01474 01475 // The current index into the buffer. 01476 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index"); 01477 index->addIncoming(zero, LoopInitBB); 01478 01479 // The current buffer size. 01480 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count"); 01481 count->addIncoming(initialBufferLimit, LoopInitBB); 01482 01483 // Check whether the mutations value has changed from where it was 01484 // at start. StateMutationsPtr should actually be invariant between 01485 // refreshes. 01486 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr"); 01487 llvm::Value *currentMutations 01488 = Builder.CreateLoad(StateMutationsPtr, "statemutations"); 01489 01490 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated"); 01491 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated"); 01492 01493 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations), 01494 WasNotMutatedBB, WasMutatedBB); 01495 01496 // If so, call the enumeration-mutation function. 01497 EmitBlock(WasMutatedBB); 01498 llvm::Value *V = 01499 Builder.CreateBitCast(Collection, 01500 ConvertType(getContext().getObjCIdType())); 01501 CallArgList Args2; 01502 Args2.add(RValue::get(V), getContext().getObjCIdType()); 01503 // FIXME: We shouldn't need to get the function info here, the runtime already 01504 // should have computed it to build the function. 01505 EmitCall(CGM.getTypes().arrangeFunctionCall(getContext().VoidTy, Args2, 01506 FunctionType::ExtInfo(), 01507 RequiredArgs::All), 01508 EnumerationMutationFn, ReturnValueSlot(), Args2); 01509 01510 // Otherwise, or if the mutation function returns, just continue. 01511 EmitBlock(WasNotMutatedBB); 01512 01513 // Initialize the element variable. 01514 RunCleanupsScope elementVariableScope(*this); 01515 bool elementIsVariable; 01516 LValue elementLValue; 01517 QualType elementType; 01518 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) { 01519 // Initialize the variable, in case it's a __block variable or something. 01520 EmitAutoVarInit(variable); 01521 01522 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl()); 01523 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(), 01524 VK_LValue, SourceLocation()); 01525 elementLValue = EmitLValue(&tempDRE); 01526 elementType = D->getType(); 01527 elementIsVariable = true; 01528 01529 if (D->isARCPseudoStrong()) 01530 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone); 01531 } else { 01532 elementLValue = LValue(); // suppress warning 01533 elementType = cast<Expr>(S.getElement())->getType(); 01534 elementIsVariable = false; 01535 } 01536 llvm::Type *convertedElementType = ConvertType(elementType); 01537 01538 // Fetch the buffer out of the enumeration state. 01539 // TODO: this pointer should actually be invariant between 01540 // refreshes, which would help us do certain loop optimizations. 01541 llvm::Value *StateItemsPtr = 01542 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr"); 01543 llvm::Value *EnumStateItems = 01544 Builder.CreateLoad(StateItemsPtr, "stateitems"); 01545 01546 // Fetch the value at the current index from the buffer. 01547 llvm::Value *CurrentItemPtr = 01548 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr"); 01549 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr); 01550 01551 // Cast that value to the right type. 01552 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType, 01553 "currentitem"); 01554 01555 // Make sure we have an l-value. Yes, this gets evaluated every 01556 // time through the loop. 01557 if (!elementIsVariable) { 01558 elementLValue = EmitLValue(cast<Expr>(S.getElement())); 01559 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue); 01560 } else { 01561 EmitScalarInit(CurrentItem, elementLValue); 01562 } 01563 01564 // If we do have an element variable, this assignment is the end of 01565 // its initialization. 01566 if (elementIsVariable) 01567 EmitAutoVarCleanups(variable); 01568 01569 // Perform the loop body, setting up break and continue labels. 01570 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody)); 01571 { 01572 RunCleanupsScope Scope(*this); 01573 EmitStmt(S.getBody()); 01574 } 01575 BreakContinueStack.pop_back(); 01576 01577 // Destroy the element variable now. 01578 elementVariableScope.ForceCleanup(); 01579 01580 // Check whether there are more elements. 01581 EmitBlock(AfterBody.getBlock()); 01582 01583 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch"); 01584 01585 // First we check in the local buffer. 01586 llvm::Value *indexPlusOne 01587 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1)); 01588 01589 // If we haven't overrun the buffer yet, we can continue. 01590 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count), 01591 LoopBodyBB, FetchMoreBB); 01592 01593 index->addIncoming(indexPlusOne, AfterBody.getBlock()); 01594 count->addIncoming(count, AfterBody.getBlock()); 01595 01596 // Otherwise, we have to fetch more elements. 01597 EmitBlock(FetchMoreBB); 01598 01599 CountRV = 01600 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(), 01601 getContext().UnsignedLongTy, 01602 FastEnumSel, 01603 Collection, Args); 01604 01605 // If we got a zero count, we're done. 01606 llvm::Value *refetchCount = CountRV.getScalarVal(); 01607 01608 // (note that the message send might split FetchMoreBB) 01609 index->addIncoming(zero, Builder.GetInsertBlock()); 01610 count->addIncoming(refetchCount, Builder.GetInsertBlock()); 01611 01612 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero), 01613 EmptyBB, LoopBodyBB); 01614 01615 // No more elements. 01616 EmitBlock(EmptyBB); 01617 01618 if (!elementIsVariable) { 01619 // If the element was not a declaration, set it to be null. 01620 01621 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType); 01622 elementLValue = EmitLValue(cast<Expr>(S.getElement())); 01623 EmitStoreThroughLValue(RValue::get(null), elementLValue); 01624 } 01625 01626 if (DI) 01627 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd()); 01628 01629 // Leave the cleanup we entered in ARC. 01630 if (getLangOpts().ObjCAutoRefCount) 01631 PopCleanupBlock(); 01632 01633 EmitBlock(LoopEnd.getBlock()); 01634 } 01635 01636 void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) { 01637 CGM.getObjCRuntime().EmitTryStmt(*this, S); 01638 } 01639 01640 void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) { 01641 CGM.getObjCRuntime().EmitThrowStmt(*this, S); 01642 } 01643 01644 void CodeGenFunction::EmitObjCAtSynchronizedStmt( 01645 const ObjCAtSynchronizedStmt &S) { 01646 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S); 01647 } 01648 01649 /// Produce the code for a CK_ARCProduceObject. Just does a 01650 /// primitive retain. 01651 llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type, 01652 llvm::Value *value) { 01653 return EmitARCRetain(type, value); 01654 } 01655 01656 namespace { 01657 struct CallObjCRelease : EHScopeStack::Cleanup { 01658 CallObjCRelease(llvm::Value *object) : object(object) {} 01659 llvm::Value *object; 01660 01661 void Emit(CodeGenFunction &CGF, Flags flags) { 01662 CGF.EmitARCRelease(object, /*precise*/ true); 01663 } 01664 }; 01665 } 01666 01667 /// Produce the code for a CK_ARCConsumeObject. Does a primitive 01668 /// release at the end of the full-expression. 01669 llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type, 01670 llvm::Value *object) { 01671 // If we're in a conditional branch, we need to make the cleanup 01672 // conditional. 01673 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object); 01674 return object; 01675 } 01676 01677 llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type, 01678 llvm::Value *value) { 01679 return EmitARCRetainAutorelease(type, value); 01680 } 01681 01682 01683 static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM, 01684 llvm::FunctionType *type, 01685 StringRef fnName) { 01686 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName); 01687 01688 // In -fobjc-no-arc-runtime, emit weak references to the runtime 01689 // support library. 01690 if (!CGM.getCodeGenOpts().ObjCRuntimeHasARC) 01691 if (llvm::Function *f = dyn_cast<llvm::Function>(fn)) 01692 f->setLinkage(llvm::Function::ExternalWeakLinkage); 01693 01694 return fn; 01695 } 01696 01697 /// Perform an operation having the signature 01698 /// i8* (i8*) 01699 /// where a null input causes a no-op and returns null. 01700 static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF, 01701 llvm::Value *value, 01702 llvm::Constant *&fn, 01703 StringRef fnName) { 01704 if (isa<llvm::ConstantPointerNull>(value)) return value; 01705 01706 if (!fn) { 01707 std::vector<llvm::Type*> args(1, CGF.Int8PtrTy); 01708 llvm::FunctionType *fnType = 01709 llvm::FunctionType::get(CGF.Int8PtrTy, args, false); 01710 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName); 01711 } 01712 01713 // Cast the argument to 'id'. 01714 llvm::Type *origType = value->getType(); 01715 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy); 01716 01717 // Call the function. 01718 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value); 01719 call->setDoesNotThrow(); 01720 01721 // Cast the result back to the original type. 01722 return CGF.Builder.CreateBitCast(call, origType); 01723 } 01724 01725 /// Perform an operation having the following signature: 01726 /// i8* (i8**) 01727 static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF, 01728 llvm::Value *addr, 01729 llvm::Constant *&fn, 01730 StringRef fnName) { 01731 if (!fn) { 01732 std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy); 01733 llvm::FunctionType *fnType = 01734 llvm::FunctionType::get(CGF.Int8PtrTy, args, false); 01735 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName); 01736 } 01737 01738 // Cast the argument to 'id*'. 01739 llvm::Type *origType = addr->getType(); 01740 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy); 01741 01742 // Call the function. 01743 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr); 01744 call->setDoesNotThrow(); 01745 01746 // Cast the result back to a dereference of the original type. 01747 llvm::Value *result = call; 01748 if (origType != CGF.Int8PtrPtrTy) 01749 result = CGF.Builder.CreateBitCast(result, 01750 cast<llvm::PointerType>(origType)->getElementType()); 01751 01752 return result; 01753 } 01754 01755 /// Perform an operation having the following signature: 01756 /// i8* (i8**, i8*) 01757 static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF, 01758 llvm::Value *addr, 01759 llvm::Value *value, 01760 llvm::Constant *&fn, 01761 StringRef fnName, 01762 bool ignored) { 01763 assert(cast<llvm::PointerType>(addr->getType())->getElementType() 01764 == value->getType()); 01765 01766 if (!fn) { 01767 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy }; 01768 01769 llvm::FunctionType *fnType 01770 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false); 01771 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName); 01772 } 01773 01774 llvm::Type *origType = value->getType(); 01775 01776 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy); 01777 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy); 01778 01779 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value); 01780 result->setDoesNotThrow(); 01781 01782 if (ignored) return 0; 01783 01784 return CGF.Builder.CreateBitCast(result, origType); 01785 } 01786 01787 /// Perform an operation having the following signature: 01788 /// void (i8**, i8**) 01789 static void emitARCCopyOperation(CodeGenFunction &CGF, 01790 llvm::Value *dst, 01791 llvm::Value *src, 01792 llvm::Constant *&fn, 01793 StringRef fnName) { 01794 assert(dst->getType() == src->getType()); 01795 01796 if (!fn) { 01797 std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy); 01798 llvm::FunctionType *fnType 01799 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false); 01800 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName); 01801 } 01802 01803 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy); 01804 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy); 01805 01806 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src); 01807 result->setDoesNotThrow(); 01808 } 01809 01810 /// Produce the code to do a retain. Based on the type, calls one of: 01811 /// call i8* @objc_retain(i8* %value) 01812 /// call i8* @objc_retainBlock(i8* %value) 01813 llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) { 01814 if (type->isBlockPointerType()) 01815 return EmitARCRetainBlock(value, /*mandatory*/ false); 01816 else 01817 return EmitARCRetainNonBlock(value); 01818 } 01819 01820 /// Retain the given object, with normal retain semantics. 01821 /// call i8* @objc_retain(i8* %value) 01822 llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) { 01823 return emitARCValueOperation(*this, value, 01824 CGM.getARCEntrypoints().objc_retain, 01825 "objc_retain"); 01826 } 01827 01828 /// Retain the given block, with _Block_copy semantics. 01829 /// call i8* @objc_retainBlock(i8* %value) 01830 /// 01831 /// \param mandatory - If false, emit the call with metadata 01832 /// indicating that it's okay for the optimizer to eliminate this call 01833 /// if it can prove that the block never escapes except down the stack. 01834 llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value, 01835 bool mandatory) { 01836 llvm::Value *result 01837 = emitARCValueOperation(*this, value, 01838 CGM.getARCEntrypoints().objc_retainBlock, 01839 "objc_retainBlock"); 01840 01841 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to 01842 // tell the optimizer that it doesn't need to do this copy if the 01843 // block doesn't escape, where being passed as an argument doesn't 01844 // count as escaping. 01845 if (!mandatory && isa<llvm::Instruction>(result)) { 01846 llvm::CallInst *call 01847 = cast<llvm::CallInst>(result->stripPointerCasts()); 01848 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock); 01849 01850 SmallVector<llvm::Value*,1> args; 01851 call->setMetadata("clang.arc.copy_on_escape", 01852 llvm::MDNode::get(Builder.getContext(), args)); 01853 } 01854 01855 return result; 01856 } 01857 01858 /// Retain the given object which is the result of a function call. 01859 /// call i8* @objc_retainAutoreleasedReturnValue(i8* %value) 01860 /// 01861 /// Yes, this function name is one character away from a different 01862 /// call with completely different semantics. 01863 llvm::Value * 01864 CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) { 01865 // Fetch the void(void) inline asm which marks that we're going to 01866 // retain the autoreleased return value. 01867 llvm::InlineAsm *&marker 01868 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker; 01869 if (!marker) { 01870 StringRef assembly 01871 = CGM.getTargetCodeGenInfo() 01872 .getARCRetainAutoreleasedReturnValueMarker(); 01873 01874 // If we have an empty assembly string, there's nothing to do. 01875 if (assembly.empty()) { 01876 01877 // Otherwise, at -O0, build an inline asm that we're going to call 01878 // in a moment. 01879 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) { 01880 llvm::FunctionType *type = 01881 llvm::FunctionType::get(VoidTy, /*variadic*/false); 01882 01883 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true); 01884 01885 // If we're at -O1 and above, we don't want to litter the code 01886 // with this marker yet, so leave a breadcrumb for the ARC 01887 // optimizer to pick up. 01888 } else { 01889 llvm::NamedMDNode *metadata = 01890 CGM.getModule().getOrInsertNamedMetadata( 01891 "clang.arc.retainAutoreleasedReturnValueMarker"); 01892 assert(metadata->getNumOperands() <= 1); 01893 if (metadata->getNumOperands() == 0) { 01894 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly); 01895 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string)); 01896 } 01897 } 01898 } 01899 01900 // Call the marker asm if we made one, which we do only at -O0. 01901 if (marker) Builder.CreateCall(marker); 01902 01903 return emitARCValueOperation(*this, value, 01904 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue, 01905 "objc_retainAutoreleasedReturnValue"); 01906 } 01907 01908 /// Release the given object. 01909 /// call void @objc_release(i8* %value) 01910 void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) { 01911 if (isa<llvm::ConstantPointerNull>(value)) return; 01912 01913 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release; 01914 if (!fn) { 01915 std::vector<llvm::Type*> args(1, Int8PtrTy); 01916 llvm::FunctionType *fnType = 01917 llvm::FunctionType::get(Builder.getVoidTy(), args, false); 01918 fn = createARCRuntimeFunction(CGM, fnType, "objc_release"); 01919 } 01920 01921 // Cast the argument to 'id'. 01922 value = Builder.CreateBitCast(value, Int8PtrTy); 01923 01924 // Call objc_release. 01925 llvm::CallInst *call = Builder.CreateCall(fn, value); 01926 call->setDoesNotThrow(); 01927 01928 if (!precise) { 01929 SmallVector<llvm::Value*,1> args; 01930 call->setMetadata("clang.imprecise_release", 01931 llvm::MDNode::get(Builder.getContext(), args)); 01932 } 01933 } 01934 01935 /// Store into a strong object. Always calls this: 01936 /// call void @objc_storeStrong(i8** %addr, i8* %value) 01937 llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr, 01938 llvm::Value *value, 01939 bool ignored) { 01940 assert(cast<llvm::PointerType>(addr->getType())->getElementType() 01941 == value->getType()); 01942 01943 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong; 01944 if (!fn) { 01945 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy }; 01946 llvm::FunctionType *fnType 01947 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false); 01948 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong"); 01949 } 01950 01951 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy); 01952 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy); 01953 01954 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow(); 01955 01956 if (ignored) return 0; 01957 return value; 01958 } 01959 01960 /// Store into a strong object. Sometimes calls this: 01961 /// call void @objc_storeStrong(i8** %addr, i8* %value) 01962 /// Other times, breaks it down into components. 01963 llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst, 01964 llvm::Value *newValue, 01965 bool ignored) { 01966 QualType type = dst.getType(); 01967 bool isBlock = type->isBlockPointerType(); 01968 01969 // Use a store barrier at -O0 unless this is a block type or the 01970 // lvalue is inadequately aligned. 01971 if (shouldUseFusedARCCalls() && 01972 !isBlock && 01973 (dst.getAlignment().isZero() || 01974 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) { 01975 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored); 01976 } 01977 01978 // Otherwise, split it out. 01979 01980 // Retain the new value. 01981 newValue = EmitARCRetain(type, newValue); 01982 01983 // Read the old value. 01984 llvm::Value *oldValue = EmitLoadOfScalar(dst); 01985 01986 // Store. We do this before the release so that any deallocs won't 01987 // see the old value. 01988 EmitStoreOfScalar(newValue, dst); 01989 01990 // Finally, release the old value. 01991 EmitARCRelease(oldValue, /*precise*/ false); 01992 01993 return newValue; 01994 } 01995 01996 /// Autorelease the given object. 01997 /// call i8* @objc_autorelease(i8* %value) 01998 llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) { 01999 return emitARCValueOperation(*this, value, 02000 CGM.getARCEntrypoints().objc_autorelease, 02001 "objc_autorelease"); 02002 } 02003 02004 /// Autorelease the given object. 02005 /// call i8* @objc_autoreleaseReturnValue(i8* %value) 02006 llvm::Value * 02007 CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) { 02008 return emitARCValueOperation(*this, value, 02009 CGM.getARCEntrypoints().objc_autoreleaseReturnValue, 02010 "objc_autoreleaseReturnValue"); 02011 } 02012 02013 /// Do a fused retain/autorelease of the given object. 02014 /// call i8* @objc_retainAutoreleaseReturnValue(i8* %value) 02015 llvm::Value * 02016 CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) { 02017 return emitARCValueOperation(*this, value, 02018 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue, 02019 "objc_retainAutoreleaseReturnValue"); 02020 } 02021 02022 /// Do a fused retain/autorelease of the given object. 02023 /// call i8* @objc_retainAutorelease(i8* %value) 02024 /// or 02025 /// %retain = call i8* @objc_retainBlock(i8* %value) 02026 /// call i8* @objc_autorelease(i8* %retain) 02027 llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type, 02028 llvm::Value *value) { 02029 if (!type->isBlockPointerType()) 02030 return EmitARCRetainAutoreleaseNonBlock(value); 02031 02032 if (isa<llvm::ConstantPointerNull>(value)) return value; 02033 02034 llvm::Type *origType = value->getType(); 02035 value = Builder.CreateBitCast(value, Int8PtrTy); 02036 value = EmitARCRetainBlock(value, /*mandatory*/ true); 02037 value = EmitARCAutorelease(value); 02038 return Builder.CreateBitCast(value, origType); 02039 } 02040 02041 /// Do a fused retain/autorelease of the given object. 02042 /// call i8* @objc_retainAutorelease(i8* %value) 02043 llvm::Value * 02044 CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) { 02045 return emitARCValueOperation(*this, value, 02046 CGM.getARCEntrypoints().objc_retainAutorelease, 02047 "objc_retainAutorelease"); 02048 } 02049 02050 /// i8* @objc_loadWeak(i8** %addr) 02051 /// Essentially objc_autorelease(objc_loadWeakRetained(addr)). 02052 llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) { 02053 return emitARCLoadOperation(*this, addr, 02054 CGM.getARCEntrypoints().objc_loadWeak, 02055 "objc_loadWeak"); 02056 } 02057 02058 /// i8* @objc_loadWeakRetained(i8** %addr) 02059 llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) { 02060 return emitARCLoadOperation(*this, addr, 02061 CGM.getARCEntrypoints().objc_loadWeakRetained, 02062 "objc_loadWeakRetained"); 02063 } 02064 02065 /// i8* @objc_storeWeak(i8** %addr, i8* %value) 02066 /// Returns %value. 02067 llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr, 02068 llvm::Value *value, 02069 bool ignored) { 02070 return emitARCStoreOperation(*this, addr, value, 02071 CGM.getARCEntrypoints().objc_storeWeak, 02072 "objc_storeWeak", ignored); 02073 } 02074 02075 /// i8* @objc_initWeak(i8** %addr, i8* %value) 02076 /// Returns %value. %addr is known to not have a current weak entry. 02077 /// Essentially equivalent to: 02078 /// *addr = nil; objc_storeWeak(addr, value); 02079 void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) { 02080 // If we're initializing to null, just write null to memory; no need 02081 // to get the runtime involved. But don't do this if optimization 02082 // is enabled, because accounting for this would make the optimizer 02083 // much more complicated. 02084 if (isa<llvm::ConstantPointerNull>(value) && 02085 CGM.getCodeGenOpts().OptimizationLevel == 0) { 02086 Builder.CreateStore(value, addr); 02087 return; 02088 } 02089 02090 emitARCStoreOperation(*this, addr, value, 02091 CGM.getARCEntrypoints().objc_initWeak, 02092 "objc_initWeak", /*ignored*/ true); 02093 } 02094 02095 /// void @objc_destroyWeak(i8** %addr) 02096 /// Essentially objc_storeWeak(addr, nil). 02097 void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) { 02098 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak; 02099 if (!fn) { 02100 std::vector<llvm::Type*> args(1, Int8PtrPtrTy); 02101 llvm::FunctionType *fnType = 02102 llvm::FunctionType::get(Builder.getVoidTy(), args, false); 02103 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak"); 02104 } 02105 02106 // Cast the argument to 'id*'. 02107 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy); 02108 02109 llvm::CallInst *call = Builder.CreateCall(fn, addr); 02110 call->setDoesNotThrow(); 02111 } 02112 02113 /// void @objc_moveWeak(i8** %dest, i8** %src) 02114 /// Disregards the current value in %dest. Leaves %src pointing to nothing. 02115 /// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)). 02116 void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) { 02117 emitARCCopyOperation(*this, dst, src, 02118 CGM.getARCEntrypoints().objc_moveWeak, 02119 "objc_moveWeak"); 02120 } 02121 02122 /// void @objc_copyWeak(i8** %dest, i8** %src) 02123 /// Disregards the current value in %dest. Essentially 02124 /// objc_release(objc_initWeak(dest, objc_readWeakRetained(src))) 02125 void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) { 02126 emitARCCopyOperation(*this, dst, src, 02127 CGM.getARCEntrypoints().objc_copyWeak, 02128 "objc_copyWeak"); 02129 } 02130 02131 /// Produce the code to do a objc_autoreleasepool_push. 02132 /// call i8* @objc_autoreleasePoolPush(void) 02133 llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() { 02134 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush; 02135 if (!fn) { 02136 llvm::FunctionType *fnType = 02137 llvm::FunctionType::get(Int8PtrTy, false); 02138 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush"); 02139 } 02140 02141 llvm::CallInst *call = Builder.CreateCall(fn); 02142 call->setDoesNotThrow(); 02143 02144 return call; 02145 } 02146 02147 /// Produce the code to do a primitive release. 02148 /// call void @objc_autoreleasePoolPop(i8* %ptr) 02149 void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) { 02150 assert(value->getType() == Int8PtrTy); 02151 02152 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop; 02153 if (!fn) { 02154 std::vector<llvm::Type*> args(1, Int8PtrTy); 02155 llvm::FunctionType *fnType = 02156 llvm::FunctionType::get(Builder.getVoidTy(), args, false); 02157 02158 // We don't want to use a weak import here; instead we should not 02159 // fall into this path. 02160 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop"); 02161 } 02162 02163 llvm::CallInst *call = Builder.CreateCall(fn, value); 02164 call->setDoesNotThrow(); 02165 } 02166 02167 /// Produce the code to do an MRR version objc_autoreleasepool_push. 02168 /// Which is: [[NSAutoreleasePool alloc] init]; 02169 /// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class. 02170 /// init is declared as: - (id) init; in its NSObject super class. 02171 /// 02172 llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() { 02173 CGObjCRuntime &Runtime = CGM.getObjCRuntime(); 02174 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder); 02175 // [NSAutoreleasePool alloc] 02176 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc"); 02177 Selector AllocSel = getContext().Selectors.getSelector(0, &II); 02178 CallArgList Args; 02179 RValue AllocRV = 02180 Runtime.GenerateMessageSend(*this, ReturnValueSlot(), 02181 getContext().getObjCIdType(), 02182 AllocSel, Receiver, Args); 02183 02184 // [Receiver init] 02185 Receiver = AllocRV.getScalarVal(); 02186 II = &CGM.getContext().Idents.get("init"); 02187 Selector InitSel = getContext().Selectors.getSelector(0, &II); 02188 RValue InitRV = 02189 Runtime.GenerateMessageSend(*this, ReturnValueSlot(), 02190 getContext().getObjCIdType(), 02191 InitSel, Receiver, Args); 02192 return InitRV.getScalarVal(); 02193 } 02194 02195 /// Produce the code to do a primitive release. 02196 /// [tmp drain]; 02197 void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) { 02198 IdentifierInfo *II = &CGM.getContext().Idents.get("drain"); 02199 Selector DrainSel = getContext().Selectors.getSelector(0, &II); 02200 CallArgList Args; 02201 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(), 02202 getContext().VoidTy, DrainSel, Arg, Args); 02203 } 02204 02205 void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF, 02206 llvm::Value *addr, 02207 QualType type) { 02208 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy"); 02209 CGF.EmitARCRelease(ptr, /*precise*/ true); 02210 } 02211 02212 void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF, 02213 llvm::Value *addr, 02214 QualType type) { 02215 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy"); 02216 CGF.EmitARCRelease(ptr, /*precise*/ false); 02217 } 02218 02219 void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF, 02220 llvm::Value *addr, 02221 QualType type) { 02222 CGF.EmitARCDestroyWeak(addr); 02223 } 02224 02225 namespace { 02226 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup { 02227 llvm::Value *Token; 02228 02229 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {} 02230 02231 void Emit(CodeGenFunction &CGF, Flags flags) { 02232 CGF.EmitObjCAutoreleasePoolPop(Token); 02233 } 02234 }; 02235 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup { 02236 llvm::Value *Token; 02237 02238 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {} 02239 02240 void Emit(CodeGenFunction &CGF, Flags flags) { 02241 CGF.EmitObjCMRRAutoreleasePoolPop(Token); 02242 } 02243 }; 02244 } 02245 02246 void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) { 02247 if (CGM.getLangOpts().ObjCAutoRefCount) 02248 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr); 02249 else 02250 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr); 02251 } 02252 02253 static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF, 02254 LValue lvalue, 02255 QualType type) { 02256 switch (type.getObjCLifetime()) { 02257 case Qualifiers::OCL_None: 02258 case Qualifiers::OCL_ExplicitNone: 02259 case Qualifiers::OCL_Strong: 02260 case Qualifiers::OCL_Autoreleasing: 02261 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(), 02262 false); 02263 02264 case Qualifiers::OCL_Weak: 02265 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()), 02266 true); 02267 } 02268 02269 llvm_unreachable("impossible lifetime!"); 02270 } 02271 02272 static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF, 02273 const Expr *e) { 02274 e = e->IgnoreParens(); 02275 QualType type = e->getType(); 02276 02277 // If we're loading retained from a __strong xvalue, we can avoid 02278 // an extra retain/release pair by zeroing out the source of this 02279 // "move" operation. 02280 if (e->isXValue() && 02281 !type.isConstQualified() && 02282 type.getObjCLifetime() == Qualifiers::OCL_Strong) { 02283 // Emit the lvalue. 02284 LValue lv = CGF.EmitLValue(e); 02285 02286 // Load the object pointer. 02287 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal(); 02288 02289 // Set the source pointer to NULL. 02290 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv); 02291 02292 return TryEmitResult(result, true); 02293 } 02294 02295 // As a very special optimization, in ARC++, if the l-value is the 02296 // result of a non-volatile assignment, do a simple retain of the 02297 // result of the call to objc_storeWeak instead of reloading. 02298 if (CGF.getLangOpts().CPlusPlus && 02299 !type.isVolatileQualified() && 02300 type.getObjCLifetime() == Qualifiers::OCL_Weak && 02301 isa<BinaryOperator>(e) && 02302 cast<BinaryOperator>(e)->getOpcode() == BO_Assign) 02303 return TryEmitResult(CGF.EmitScalarExpr(e), false); 02304 02305 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type); 02306 } 02307 02308 static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF, 02309 llvm::Value *value); 02310 02311 /// Given that the given expression is some sort of call (which does 02312 /// not return retained), emit a retain following it. 02313 static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) { 02314 llvm::Value *value = CGF.EmitScalarExpr(e); 02315 return emitARCRetainAfterCall(CGF, value); 02316 } 02317 02318 static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF, 02319 llvm::Value *value) { 02320 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) { 02321 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP(); 02322 02323 // Place the retain immediately following the call. 02324 CGF.Builder.SetInsertPoint(call->getParent(), 02325 ++llvm::BasicBlock::iterator(call)); 02326 value = CGF.EmitARCRetainAutoreleasedReturnValue(value); 02327 02328 CGF.Builder.restoreIP(ip); 02329 return value; 02330 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) { 02331 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP(); 02332 02333 // Place the retain at the beginning of the normal destination block. 02334 llvm::BasicBlock *BB = invoke->getNormalDest(); 02335 CGF.Builder.SetInsertPoint(BB, BB->begin()); 02336 value = CGF.EmitARCRetainAutoreleasedReturnValue(value); 02337 02338 CGF.Builder.restoreIP(ip); 02339 return value; 02340 02341 // Bitcasts can arise because of related-result returns. Rewrite 02342 // the operand. 02343 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) { 02344 llvm::Value *operand = bitcast->getOperand(0); 02345 operand = emitARCRetainAfterCall(CGF, operand); 02346 bitcast->setOperand(0, operand); 02347 return bitcast; 02348 02349 // Generic fall-back case. 02350 } else { 02351 // Retain using the non-block variant: we never need to do a copy 02352 // of a block that's been returned to us. 02353 return CGF.EmitARCRetainNonBlock(value); 02354 } 02355 } 02356 02357 /// Determine whether it might be important to emit a separate 02358 /// objc_retain_block on the result of the given expression, or 02359 /// whether it's okay to just emit it in a +1 context. 02360 static bool shouldEmitSeparateBlockRetain(const Expr *e) { 02361 assert(e->getType()->isBlockPointerType()); 02362 e = e->IgnoreParens(); 02363 02364 // For future goodness, emit block expressions directly in +1 02365 // contexts if we can. 02366 if (isa<BlockExpr>(e)) 02367 return false; 02368 02369 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) { 02370 switch (cast->getCastKind()) { 02371 // Emitting these operations in +1 contexts is goodness. 02372 case CK_LValueToRValue: 02373 case CK_ARCReclaimReturnedObject: 02374 case CK_ARCConsumeObject: 02375 case CK_ARCProduceObject: 02376 return false; 02377 02378 // These operations preserve a block type. 02379 case CK_NoOp: 02380 case CK_BitCast: 02381 return shouldEmitSeparateBlockRetain(cast->getSubExpr()); 02382 02383 // These operations are known to be bad (or haven't been considered). 02384 case CK_AnyPointerToBlockPointerCast: 02385 default: 02386 return true; 02387 } 02388 } 02389 02390 return true; 02391 } 02392 02393 /// Try to emit a PseudoObjectExpr at +1. 02394 /// 02395 /// This massively duplicates emitPseudoObjectRValue. 02396 static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF, 02397 const PseudoObjectExpr *E) { 02398 llvm::SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques; 02399 02400 // Find the result expression. 02401 const Expr *resultExpr = E->getResultExpr(); 02402 assert(resultExpr); 02403 TryEmitResult result; 02404 02405 for (PseudoObjectExpr::const_semantics_iterator 02406 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) { 02407 const Expr *semantic = *i; 02408 02409 // If this semantic expression is an opaque value, bind it 02410 // to the result of its source expression. 02411 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) { 02412 typedef CodeGenFunction::OpaqueValueMappingData OVMA; 02413 OVMA opaqueData; 02414 02415 // If this semantic is the result of the pseudo-object 02416 // expression, try to evaluate the source as +1. 02417 if (ov == resultExpr) { 02418 assert(!OVMA::shouldBindAsLValue(ov)); 02419 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr()); 02420 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer())); 02421 02422 // Otherwise, just bind it. 02423 } else { 02424 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr()); 02425 } 02426 opaques.push_back(opaqueData); 02427 02428 // Otherwise, if the expression is the result, evaluate it 02429 // and remember the result. 02430 } else if (semantic == resultExpr) { 02431 result = tryEmitARCRetainScalarExpr(CGF, semantic); 02432 02433 // Otherwise, evaluate the expression in an ignored context. 02434 } else { 02435 CGF.EmitIgnoredExpr(semantic); 02436 } 02437 } 02438 02439 // Unbind all the opaques now. 02440 for (unsigned i = 0, e = opaques.size(); i != e; ++i) 02441 opaques[i].unbind(CGF); 02442 02443 return result; 02444 } 02445 02446 static TryEmitResult 02447 tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) { 02448 // Look through cleanups. 02449 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) { 02450 CGF.enterFullExpression(cleanups); 02451 CodeGenFunction::RunCleanupsScope scope(CGF); 02452 return tryEmitARCRetainScalarExpr(CGF, cleanups->getSubExpr()); 02453 } 02454 02455 // The desired result type, if it differs from the type of the 02456 // ultimate opaque expression. 02457 llvm::Type *resultType = 0; 02458 02459 while (true) { 02460 e = e->IgnoreParens(); 02461 02462 // There's a break at the end of this if-chain; anything 02463 // that wants to keep looping has to explicitly continue. 02464 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) { 02465 switch (ce->getCastKind()) { 02466 // No-op casts don't change the type, so we just ignore them. 02467 case CK_NoOp: 02468 e = ce->getSubExpr(); 02469 continue; 02470 02471 case CK_LValueToRValue: { 02472 TryEmitResult loadResult 02473 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr()); 02474 if (resultType) { 02475 llvm::Value *value = loadResult.getPointer(); 02476 value = CGF.Builder.CreateBitCast(value, resultType); 02477 loadResult.setPointer(value); 02478 } 02479 return loadResult; 02480 } 02481 02482 // These casts can change the type, so remember that and 02483 // soldier on. We only need to remember the outermost such 02484 // cast, though. 02485 case CK_CPointerToObjCPointerCast: 02486 case CK_BlockPointerToObjCPointerCast: 02487 case CK_AnyPointerToBlockPointerCast: 02488 case CK_BitCast: 02489 if (!resultType) 02490 resultType = CGF.ConvertType(ce->getType()); 02491 e = ce->getSubExpr(); 02492 assert(e->getType()->hasPointerRepresentation()); 02493 continue; 02494 02495 // For consumptions, just emit the subexpression and thus elide 02496 // the retain/release pair. 02497 case CK_ARCConsumeObject: { 02498 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr()); 02499 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType); 02500 return TryEmitResult(result, true); 02501 } 02502 02503 // Block extends are net +0. Naively, we could just recurse on 02504 // the subexpression, but actually we need to ensure that the 02505 // value is copied as a block, so there's a little filter here. 02506 case CK_ARCExtendBlockObject: { 02507 llvm::Value *result; // will be a +0 value 02508 02509 // If we can't safely assume the sub-expression will produce a 02510 // block-copied value, emit the sub-expression at +0. 02511 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) { 02512 result = CGF.EmitScalarExpr(ce->getSubExpr()); 02513 02514 // Otherwise, try to emit the sub-expression at +1 recursively. 02515 } else { 02516 TryEmitResult subresult 02517 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr()); 02518 result = subresult.getPointer(); 02519 02520 // If that produced a retained value, just use that, 02521 // possibly casting down. 02522 if (subresult.getInt()) { 02523 if (resultType) 02524 result = CGF.Builder.CreateBitCast(result, resultType); 02525 return TryEmitResult(result, true); 02526 } 02527 02528 // Otherwise it's +0. 02529 } 02530 02531 // Retain the object as a block, then cast down. 02532 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true); 02533 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType); 02534 return TryEmitResult(result, true); 02535 } 02536 02537 // For reclaims, emit the subexpression as a retained call and 02538 // skip the consumption. 02539 case CK_ARCReclaimReturnedObject: { 02540 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr()); 02541 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType); 02542 return TryEmitResult(result, true); 02543 } 02544 02545 default: 02546 break; 02547 } 02548 02549 // Skip __extension__. 02550 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) { 02551 if (op->getOpcode() == UO_Extension) { 02552 e = op->getSubExpr(); 02553 continue; 02554 } 02555 02556 // For calls and message sends, use the retained-call logic. 02557 // Delegate inits are a special case in that they're the only 02558 // returns-retained expression that *isn't* surrounded by 02559 // a consume. 02560 } else if (isa<CallExpr>(e) || 02561 (isa<ObjCMessageExpr>(e) && 02562 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) { 02563 llvm::Value *result = emitARCRetainCall(CGF, e); 02564 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType); 02565 return TryEmitResult(result, true); 02566 02567 // Look through pseudo-object expressions. 02568 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 02569 TryEmitResult result 02570 = tryEmitARCRetainPseudoObject(CGF, pseudo); 02571 if (resultType) { 02572 llvm::Value *value = result.getPointer(); 02573 value = CGF.Builder.CreateBitCast(value, resultType); 02574 result.setPointer(value); 02575 } 02576 return result; 02577 } 02578 02579 // Conservatively halt the search at any other expression kind. 02580 break; 02581 } 02582 02583 // We didn't find an obvious production, so emit what we've got and 02584 // tell the caller that we didn't manage to retain. 02585 llvm::Value *result = CGF.EmitScalarExpr(e); 02586 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType); 02587 return TryEmitResult(result, false); 02588 } 02589 02590 static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF, 02591 LValue lvalue, 02592 QualType type) { 02593 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type); 02594 llvm::Value *value = result.getPointer(); 02595 if (!result.getInt()) 02596 value = CGF.EmitARCRetain(type, value); 02597 return value; 02598 } 02599 02600 /// EmitARCRetainScalarExpr - Semantically equivalent to 02601 /// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a 02602 /// best-effort attempt to peephole expressions that naturally produce 02603 /// retained objects. 02604 llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) { 02605 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e); 02606 llvm::Value *value = result.getPointer(); 02607 if (!result.getInt()) 02608 value = EmitARCRetain(e->getType(), value); 02609 return value; 02610 } 02611 02612 llvm::Value * 02613 CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) { 02614 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e); 02615 llvm::Value *value = result.getPointer(); 02616 if (result.getInt()) 02617 value = EmitARCAutorelease(value); 02618 else 02619 value = EmitARCRetainAutorelease(e->getType(), value); 02620 return value; 02621 } 02622 02623 llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) { 02624 llvm::Value *result; 02625 bool doRetain; 02626 02627 if (shouldEmitSeparateBlockRetain(e)) { 02628 result = EmitScalarExpr(e); 02629 doRetain = true; 02630 } else { 02631 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e); 02632 result = subresult.getPointer(); 02633 doRetain = !subresult.getInt(); 02634 } 02635 02636 if (doRetain) 02637 result = EmitARCRetainBlock(result, /*mandatory*/ true); 02638 return EmitObjCConsumeObject(e->getType(), result); 02639 } 02640 02641 llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) { 02642 // In ARC, retain and autorelease the expression. 02643 if (getLangOpts().ObjCAutoRefCount) { 02644 // Do so before running any cleanups for the full-expression. 02645 // tryEmitARCRetainScalarExpr does make an effort to do things 02646 // inside cleanups, but there are crazy cases like 02647 // @throw A().foo; 02648 // where a full retain+autorelease is required and would 02649 // otherwise happen after the destructor for the temporary. 02650 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(expr)) { 02651 enterFullExpression(ewc); 02652 expr = ewc->getSubExpr(); 02653 } 02654 02655 CodeGenFunction::RunCleanupsScope cleanups(*this); 02656 return EmitARCRetainAutoreleaseScalarExpr(expr); 02657 } 02658 02659 // Otherwise, use the normal scalar-expression emission. The 02660 // exception machinery doesn't do anything special with the 02661 // exception like retaining it, so there's no safety associated with 02662 // only running cleanups after the throw has started, and when it 02663 // matters it tends to be substantially inferior code. 02664 return EmitScalarExpr(expr); 02665 } 02666 02667 std::pair<LValue,llvm::Value*> 02668 CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e, 02669 bool ignored) { 02670 // Evaluate the RHS first. 02671 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS()); 02672 llvm::Value *value = result.getPointer(); 02673 02674 bool hasImmediateRetain = result.getInt(); 02675 02676 // If we didn't emit a retained object, and the l-value is of block 02677 // type, then we need to emit the block-retain immediately in case 02678 // it invalidates the l-value. 02679 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) { 02680 value = EmitARCRetainBlock(value, /*mandatory*/ false); 02681 hasImmediateRetain = true; 02682 } 02683 02684 LValue lvalue = EmitLValue(e->getLHS()); 02685 02686 // If the RHS was emitted retained, expand this. 02687 if (hasImmediateRetain) { 02688 llvm::Value *oldValue = 02689 EmitLoadOfScalar(lvalue); 02690 EmitStoreOfScalar(value, lvalue); 02691 EmitARCRelease(oldValue, /*precise*/ false); 02692 } else { 02693 value = EmitARCStoreStrong(lvalue, value, ignored); 02694 } 02695 02696 return std::pair<LValue,llvm::Value*>(lvalue, value); 02697 } 02698 02699 std::pair<LValue,llvm::Value*> 02700 CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) { 02701 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS()); 02702 LValue lvalue = EmitLValue(e->getLHS()); 02703 02704 EmitStoreOfScalar(value, lvalue); 02705 02706 return std::pair<LValue,llvm::Value*>(lvalue, value); 02707 } 02708 02709 void CodeGenFunction::EmitObjCAutoreleasePoolStmt( 02710 const ObjCAutoreleasePoolStmt &ARPS) { 02711 const Stmt *subStmt = ARPS.getSubStmt(); 02712 const CompoundStmt &S = cast<CompoundStmt>(*subStmt); 02713 02714 CGDebugInfo *DI = getDebugInfo(); 02715 if (DI) 02716 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc()); 02717 02718 // Keep track of the current cleanup stack depth. 02719 RunCleanupsScope Scope(*this); 02720 if (CGM.getCodeGenOpts().ObjCRuntimeHasARC) { 02721 llvm::Value *token = EmitObjCAutoreleasePoolPush(); 02722 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token); 02723 } else { 02724 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush(); 02725 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token); 02726 } 02727 02728 for (CompoundStmt::const_body_iterator I = S.body_begin(), 02729 E = S.body_end(); I != E; ++I) 02730 EmitStmt(*I); 02731 02732 if (DI) 02733 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc()); 02734 } 02735 02736 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object, 02737 /// make sure it survives garbage collection until this point. 02738 void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) { 02739 // We just use an inline assembly. 02740 llvm::FunctionType *extenderType 02741 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All); 02742 llvm::Value *extender 02743 = llvm::InlineAsm::get(extenderType, 02744 /* assembly */ "", 02745 /* constraints */ "r", 02746 /* side effects */ true); 02747 02748 object = Builder.CreateBitCast(object, VoidPtrTy); 02749 Builder.CreateCall(extender, object)->setDoesNotThrow(); 02750 } 02751 02752 /// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with 02753 /// non-trivial copy assignment function, produce following helper function. 02754 /// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; } 02755 /// 02756 llvm::Constant * 02757 CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction( 02758 const ObjCPropertyImplDecl *PID) { 02759 // FIXME. This api is for NeXt runtime only for now. 02760 if (!getLangOpts().CPlusPlus || !getLangOpts().NeXTRuntime) 02761 return 0; 02762 QualType Ty = PID->getPropertyIvarDecl()->getType(); 02763 if (!Ty->isRecordType()) 02764 return 0; 02765 const ObjCPropertyDecl *PD = PID->getPropertyDecl(); 02766 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic))) 02767 return 0; 02768 llvm::Constant * HelperFn = 0; 02769 if (hasTrivialSetExpr(PID)) 02770 return 0; 02771 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null"); 02772 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty))) 02773 return HelperFn; 02774 02775 ASTContext &C = getContext(); 02776 IdentifierInfo *II 02777 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_"); 02778 FunctionDecl *FD = FunctionDecl::Create(C, 02779 C.getTranslationUnitDecl(), 02780 SourceLocation(), 02781 SourceLocation(), II, C.VoidTy, 0, 02782 SC_Static, 02783 SC_None, 02784 false, 02785 false); 02786 02787 QualType DestTy = C.getPointerType(Ty); 02788 QualType SrcTy = Ty; 02789 SrcTy.addConst(); 02790 SrcTy = C.getPointerType(SrcTy); 02791 02792 FunctionArgList args; 02793 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy); 02794 args.push_back(&dstDecl); 02795 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy); 02796 args.push_back(&srcDecl); 02797 02798 const CGFunctionInfo &FI = 02799 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args, 02800 FunctionType::ExtInfo(), 02801 RequiredArgs::All); 02802 02803 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI); 02804 02805 llvm::Function *Fn = 02806 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, 02807 "__assign_helper_atomic_property_", 02808 &CGM.getModule()); 02809 02810 if (CGM.getModuleDebugInfo()) 02811 DebugInfo = CGM.getModuleDebugInfo(); 02812 02813 02814 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation()); 02815 02816 DeclRefExpr DstExpr(&dstDecl, false, DestTy, 02817 VK_RValue, SourceLocation()); 02818 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(), 02819 VK_LValue, OK_Ordinary, SourceLocation()); 02820 02821 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy, 02822 VK_RValue, SourceLocation()); 02823 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(), 02824 VK_LValue, OK_Ordinary, SourceLocation()); 02825 02826 Expr *Args[2] = { &DST, &SRC }; 02827 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment()); 02828 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(), 02829 Args, 2, DestTy->getPointeeType(), 02830 VK_LValue, SourceLocation()); 02831 02832 EmitStmt(&TheCall); 02833 02834 FinishFunction(); 02835 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy); 02836 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn); 02837 return HelperFn; 02838 } 02839 02840 llvm::Constant * 02841 CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction( 02842 const ObjCPropertyImplDecl *PID) { 02843 // FIXME. This api is for NeXt runtime only for now. 02844 if (!getLangOpts().CPlusPlus || !getLangOpts().NeXTRuntime) 02845 return 0; 02846 const ObjCPropertyDecl *PD = PID->getPropertyDecl(); 02847 QualType Ty = PD->getType(); 02848 if (!Ty->isRecordType()) 02849 return 0; 02850 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic))) 02851 return 0; 02852 llvm::Constant * HelperFn = 0; 02853 02854 if (hasTrivialGetExpr(PID)) 02855 return 0; 02856 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null"); 02857 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty))) 02858 return HelperFn; 02859 02860 02861 ASTContext &C = getContext(); 02862 IdentifierInfo *II 02863 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_"); 02864 FunctionDecl *FD = FunctionDecl::Create(C, 02865 C.getTranslationUnitDecl(), 02866 SourceLocation(), 02867 SourceLocation(), II, C.VoidTy, 0, 02868 SC_Static, 02869 SC_None, 02870 false, 02871 false); 02872 02873 QualType DestTy = C.getPointerType(Ty); 02874 QualType SrcTy = Ty; 02875 SrcTy.addConst(); 02876 SrcTy = C.getPointerType(SrcTy); 02877 02878 FunctionArgList args; 02879 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy); 02880 args.push_back(&dstDecl); 02881 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy); 02882 args.push_back(&srcDecl); 02883 02884 const CGFunctionInfo &FI = 02885 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args, 02886 FunctionType::ExtInfo(), 02887 RequiredArgs::All); 02888 02889 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI); 02890 02891 llvm::Function *Fn = 02892 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, 02893 "__copy_helper_atomic_property_", &CGM.getModule()); 02894 02895 if (CGM.getModuleDebugInfo()) 02896 DebugInfo = CGM.getModuleDebugInfo(); 02897 02898 02899 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation()); 02900 02901 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy, 02902 VK_RValue, SourceLocation()); 02903 02904 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(), 02905 VK_LValue, OK_Ordinary, SourceLocation()); 02906 02907 CXXConstructExpr *CXXConstExpr = 02908 cast<CXXConstructExpr>(PID->getGetterCXXConstructor()); 02909 02910 SmallVector<Expr*, 4> ConstructorArgs; 02911 ConstructorArgs.push_back(&SRC); 02912 CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin(); 02913 ++A; 02914 02915 for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end(); 02916 A != AEnd; ++A) 02917 ConstructorArgs.push_back(*A); 02918 02919 CXXConstructExpr *TheCXXConstructExpr = 02920 CXXConstructExpr::Create(C, Ty, SourceLocation(), 02921 CXXConstExpr->getConstructor(), 02922 CXXConstExpr->isElidable(), 02923 &ConstructorArgs[0], ConstructorArgs.size(), 02924 CXXConstExpr->hadMultipleCandidates(), 02925 CXXConstExpr->isListInitialization(), 02926 CXXConstExpr->requiresZeroInitialization(), 02927 CXXConstExpr->getConstructionKind(), 02928 SourceRange()); 02929 02930 DeclRefExpr DstExpr(&dstDecl, false, DestTy, 02931 VK_RValue, SourceLocation()); 02932 02933 RValue DV = EmitAnyExpr(&DstExpr); 02934 CharUnits Alignment 02935 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType()); 02936 EmitAggExpr(TheCXXConstructExpr, 02937 AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(), 02938 AggValueSlot::IsDestructed, 02939 AggValueSlot::DoesNotNeedGCBarriers, 02940 AggValueSlot::IsNotAliased)); 02941 02942 FinishFunction(); 02943 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy); 02944 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn); 02945 return HelperFn; 02946 } 02947 02948 llvm::Value * 02949 CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) { 02950 // Get selectors for retain/autorelease. 02951 IdentifierInfo *CopyID = &getContext().Idents.get("copy"); 02952 Selector CopySelector = 02953 getContext().Selectors.getNullarySelector(CopyID); 02954 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease"); 02955 Selector AutoreleaseSelector = 02956 getContext().Selectors.getNullarySelector(AutoreleaseID); 02957 02958 // Emit calls to retain/autorelease. 02959 CGObjCRuntime &Runtime = CGM.getObjCRuntime(); 02960 llvm::Value *Val = Block; 02961 RValue Result; 02962 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(), 02963 Ty, CopySelector, 02964 Val, CallArgList(), 0, 0); 02965 Val = Result.getScalarVal(); 02966 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(), 02967 Ty, AutoreleaseSelector, 02968 Val, CallArgList(), 0, 0); 02969 Val = Result.getScalarVal(); 02970 return Val; 02971 } 02972 02973 02974 CGObjCRuntime::~CGObjCRuntime() {}