Path: blob/main/contrib/llvm-project/clang/lib/CodeGen/CGObjC.cpp
35233 views
//===---- CGObjC.cpp - Emit LLVM Code for Objective-C ---------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This contains code to emit Objective-C code as LLVM code.9//10//===----------------------------------------------------------------------===//1112#include "CGDebugInfo.h"13#include "CGObjCRuntime.h"14#include "CodeGenFunction.h"15#include "CodeGenModule.h"16#include "ConstantEmitter.h"17#include "TargetInfo.h"18#include "clang/AST/ASTContext.h"19#include "clang/AST/Attr.h"20#include "clang/AST/DeclObjC.h"21#include "clang/AST/StmtObjC.h"22#include "clang/Basic/Diagnostic.h"23#include "clang/CodeGen/CGFunctionInfo.h"24#include "clang/CodeGen/CodeGenABITypes.h"25#include "llvm/ADT/STLExtras.h"26#include "llvm/Analysis/ObjCARCUtil.h"27#include "llvm/BinaryFormat/MachO.h"28#include "llvm/IR/Constants.h"29#include "llvm/IR/DataLayout.h"30#include "llvm/IR/InlineAsm.h"31#include <optional>32using namespace clang;33using namespace CodeGen;3435typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;36static TryEmitResult37tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);38static RValue AdjustObjCObjectType(CodeGenFunction &CGF,39QualType ET,40RValue Result);4142/// Given the address of a variable of pointer type, find the correct43/// null to store into it.44static llvm::Constant *getNullForVariable(Address addr) {45llvm::Type *type = addr.getElementType();46return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));47}4849/// Emits an instance of NSConstantString representing the object.50llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)51{52llvm::Constant *C =53CGM.getObjCRuntime().GenerateConstantString(E->getString()).getPointer();54return C;55}5657/// EmitObjCBoxedExpr - This routine generates code to call58/// the appropriate expression boxing method. This will either be59/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:],60/// or [NSValue valueWithBytes:objCType:].61///62llvm::Value *63CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {64// Generate the correct selector for this literal's concrete type.65// Get the method.66const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();67const Expr *SubExpr = E->getSubExpr();6869if (E->isExpressibleAsConstantInitializer()) {70ConstantEmitter ConstEmitter(CGM);71return ConstEmitter.tryEmitAbstract(E, E->getType());72}7374assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");75Selector Sel = BoxingMethod->getSelector();7677// Generate a reference to the class pointer, which will be the receiver.78// Assumes that the method was introduced in the class that should be79// messaged (avoids pulling it out of the result type).80CGObjCRuntime &Runtime = CGM.getObjCRuntime();81const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();82llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);8384CallArgList Args;85const ParmVarDecl *ArgDecl = *BoxingMethod->param_begin();86QualType ArgQT = ArgDecl->getType().getUnqualifiedType();8788// ObjCBoxedExpr supports boxing of structs and unions89// via [NSValue valueWithBytes:objCType:]90const QualType ValueType(SubExpr->getType().getCanonicalType());91if (ValueType->isObjCBoxableRecordType()) {92// Emit CodeGen for first parameter93// and cast value to correct type94Address Temporary = CreateMemTemp(SubExpr->getType());95EmitAnyExprToMem(SubExpr, Temporary, Qualifiers(), /*isInit*/ true);96llvm::Value *BitCast = Builder.CreateBitCast(97Temporary.emitRawPointer(*this), ConvertType(ArgQT));98Args.add(RValue::get(BitCast), ArgQT);99100// Create char array to store type encoding101std::string Str;102getContext().getObjCEncodingForType(ValueType, Str);103llvm::Constant *GV = CGM.GetAddrOfConstantCString(Str).getPointer();104105// Cast type encoding to correct type106const ParmVarDecl *EncodingDecl = BoxingMethod->parameters()[1];107QualType EncodingQT = EncodingDecl->getType().getUnqualifiedType();108llvm::Value *Cast = Builder.CreateBitCast(GV, ConvertType(EncodingQT));109110Args.add(RValue::get(Cast), EncodingQT);111} else {112Args.add(EmitAnyExpr(SubExpr), ArgQT);113}114115RValue result = Runtime.GenerateMessageSend(116*this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,117Args, ClassDecl, BoxingMethod);118return Builder.CreateBitCast(result.getScalarVal(),119ConvertType(E->getType()));120}121122llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,123const ObjCMethodDecl *MethodWithObjects) {124ASTContext &Context = CGM.getContext();125const ObjCDictionaryLiteral *DLE = nullptr;126const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);127if (!ALE)128DLE = cast<ObjCDictionaryLiteral>(E);129130// Optimize empty collections by referencing constants, when available.131uint64_t NumElements =132ALE ? ALE->getNumElements() : DLE->getNumElements();133if (NumElements == 0 && CGM.getLangOpts().ObjCRuntime.hasEmptyCollections()) {134StringRef ConstantName = ALE ? "__NSArray0__" : "__NSDictionary0__";135QualType IdTy(CGM.getContext().getObjCIdType());136llvm::Constant *Constant =137CGM.CreateRuntimeVariable(ConvertType(IdTy), ConstantName);138LValue LV = MakeNaturalAlignAddrLValue(Constant, IdTy);139llvm::Value *Ptr = EmitLoadOfScalar(LV, E->getBeginLoc());140cast<llvm::LoadInst>(Ptr)->setMetadata(141llvm::LLVMContext::MD_invariant_load,142llvm::MDNode::get(getLLVMContext(), std::nullopt));143return Builder.CreateBitCast(Ptr, ConvertType(E->getType()));144}145146// Compute the type of the array we're initializing.147llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),148NumElements);149QualType ElementType = Context.getObjCIdType().withConst();150QualType ElementArrayType = Context.getConstantArrayType(151ElementType, APNumElements, nullptr, ArraySizeModifier::Normal,152/*IndexTypeQuals=*/0);153154// Allocate the temporary array(s).155Address Objects = CreateMemTemp(ElementArrayType, "objects");156Address Keys = Address::invalid();157if (DLE)158Keys = CreateMemTemp(ElementArrayType, "keys");159160// In ARC, we may need to do extra work to keep all the keys and161// values alive until after the call.162SmallVector<llvm::Value *, 16> NeededObjects;163bool TrackNeededObjects =164(getLangOpts().ObjCAutoRefCount &&165CGM.getCodeGenOpts().OptimizationLevel != 0);166167// Perform the actual initialialization of the array(s).168for (uint64_t i = 0; i < NumElements; i++) {169if (ALE) {170// Emit the element and store it to the appropriate array slot.171const Expr *Rhs = ALE->getElement(i);172LValue LV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, i),173ElementType, AlignmentSource::Decl);174175llvm::Value *value = EmitScalarExpr(Rhs);176EmitStoreThroughLValue(RValue::get(value), LV, true);177if (TrackNeededObjects) {178NeededObjects.push_back(value);179}180} else {181// Emit the key and store it to the appropriate array slot.182const Expr *Key = DLE->getKeyValueElement(i).Key;183LValue KeyLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Keys, i),184ElementType, AlignmentSource::Decl);185llvm::Value *keyValue = EmitScalarExpr(Key);186EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);187188// Emit the value and store it to the appropriate array slot.189const Expr *Value = DLE->getKeyValueElement(i).Value;190LValue ValueLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, i),191ElementType, AlignmentSource::Decl);192llvm::Value *valueValue = EmitScalarExpr(Value);193EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);194if (TrackNeededObjects) {195NeededObjects.push_back(keyValue);196NeededObjects.push_back(valueValue);197}198}199}200201// Generate the argument list.202CallArgList Args;203ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();204const ParmVarDecl *argDecl = *PI++;205QualType ArgQT = argDecl->getType().getUnqualifiedType();206Args.add(RValue::get(Objects, *this), ArgQT);207if (DLE) {208argDecl = *PI++;209ArgQT = argDecl->getType().getUnqualifiedType();210Args.add(RValue::get(Keys, *this), ArgQT);211}212argDecl = *PI;213ArgQT = argDecl->getType().getUnqualifiedType();214llvm::Value *Count =215llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);216Args.add(RValue::get(Count), ArgQT);217218// Generate a reference to the class pointer, which will be the receiver.219Selector Sel = MethodWithObjects->getSelector();220QualType ResultType = E->getType();221const ObjCObjectPointerType *InterfacePointerType222= ResultType->getAsObjCInterfacePointerType();223assert(InterfacePointerType && "Unexpected InterfacePointerType - null");224ObjCInterfaceDecl *Class225= InterfacePointerType->getObjectType()->getInterface();226CGObjCRuntime &Runtime = CGM.getObjCRuntime();227llvm::Value *Receiver = Runtime.GetClass(*this, Class);228229// Generate the message send.230RValue result = Runtime.GenerateMessageSend(231*this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,232Receiver, Args, Class, MethodWithObjects);233234// The above message send needs these objects, but in ARC they are235// passed in a buffer that is essentially __unsafe_unretained.236// Therefore we must prevent the optimizer from releasing them until237// after the call.238if (TrackNeededObjects) {239EmitARCIntrinsicUse(NeededObjects);240}241242return Builder.CreateBitCast(result.getScalarVal(),243ConvertType(E->getType()));244}245246llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {247return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());248}249250llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(251const ObjCDictionaryLiteral *E) {252return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());253}254255/// Emit a selector.256llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {257// Untyped selector.258// Note that this implementation allows for non-constant strings to be passed259// as arguments to @selector(). Currently, the only thing preventing this260// behaviour is the type checking in the front end.261return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());262}263264llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {265// FIXME: This should pass the Decl not the name.266return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());267}268269/// Adjust the type of an Objective-C object that doesn't match up due270/// to type erasure at various points, e.g., related result types or the use271/// of parameterized classes.272static RValue AdjustObjCObjectType(CodeGenFunction &CGF, QualType ExpT,273RValue Result) {274if (!ExpT->isObjCRetainableType())275return Result;276277// If the converted types are the same, we're done.278llvm::Type *ExpLLVMTy = CGF.ConvertType(ExpT);279if (ExpLLVMTy == Result.getScalarVal()->getType())280return Result;281282// We have applied a substitution. Cast the rvalue appropriately.283return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),284ExpLLVMTy));285}286287/// Decide whether to extend the lifetime of the receiver of a288/// returns-inner-pointer message.289static bool290shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {291switch (message->getReceiverKind()) {292293// For a normal instance message, we should extend unless the294// receiver is loaded from a variable with precise lifetime.295case ObjCMessageExpr::Instance: {296const Expr *receiver = message->getInstanceReceiver();297298// Look through OVEs.299if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {300if (opaque->getSourceExpr())301receiver = opaque->getSourceExpr()->IgnoreParens();302}303304const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);305if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;306receiver = ice->getSubExpr()->IgnoreParens();307308// Look through OVEs.309if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {310if (opaque->getSourceExpr())311receiver = opaque->getSourceExpr()->IgnoreParens();312}313314// Only __strong variables.315if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)316return true;317318// All ivars and fields have precise lifetime.319if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))320return false;321322// Otherwise, check for variables.323const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());324if (!declRef) return true;325const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());326if (!var) return true;327328// All variables have precise lifetime except local variables with329// automatic storage duration that aren't specially marked.330return (var->hasLocalStorage() &&331!var->hasAttr<ObjCPreciseLifetimeAttr>());332}333334case ObjCMessageExpr::Class:335case ObjCMessageExpr::SuperClass:336// It's never necessary for class objects.337return false;338339case ObjCMessageExpr::SuperInstance:340// We generally assume that 'self' lives throughout a method call.341return false;342}343344llvm_unreachable("invalid receiver kind");345}346347/// Given an expression of ObjC pointer type, check whether it was348/// immediately loaded from an ARC __weak l-value.349static const Expr *findWeakLValue(const Expr *E) {350assert(E->getType()->isObjCRetainableType());351E = E->IgnoreParens();352if (auto CE = dyn_cast<CastExpr>(E)) {353if (CE->getCastKind() == CK_LValueToRValue) {354if (CE->getSubExpr()->getType().getObjCLifetime() == Qualifiers::OCL_Weak)355return CE->getSubExpr();356}357}358359return nullptr;360}361362/// The ObjC runtime may provide entrypoints that are likely to be faster363/// than an ordinary message send of the appropriate selector.364///365/// The entrypoints are guaranteed to be equivalent to just sending the366/// corresponding message. If the entrypoint is implemented naively as just a367/// message send, using it is a trade-off: it sacrifices a few cycles of368/// overhead to save a small amount of code. However, it's possible for369/// runtimes to detect and special-case classes that use "standard"370/// behavior; if that's dynamically a large proportion of all objects, using371/// the entrypoint will also be faster than using a message send.372///373/// If the runtime does support a required entrypoint, then this method will374/// generate a call and return the resulting value. Otherwise it will return375/// std::nullopt and the caller can generate a msgSend instead.376static std::optional<llvm::Value *> tryGenerateSpecializedMessageSend(377CodeGenFunction &CGF, QualType ResultType, llvm::Value *Receiver,378const CallArgList &Args, Selector Sel, const ObjCMethodDecl *method,379bool isClassMessage) {380auto &CGM = CGF.CGM;381if (!CGM.getCodeGenOpts().ObjCConvertMessagesToRuntimeCalls)382return std::nullopt;383384auto &Runtime = CGM.getLangOpts().ObjCRuntime;385switch (Sel.getMethodFamily()) {386case OMF_alloc:387if (isClassMessage &&388Runtime.shouldUseRuntimeFunctionsForAlloc() &&389ResultType->isObjCObjectPointerType()) {390// [Foo alloc] -> objc_alloc(Foo) or391// [self alloc] -> objc_alloc(self)392if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "alloc")393return CGF.EmitObjCAlloc(Receiver, CGF.ConvertType(ResultType));394// [Foo allocWithZone:nil] -> objc_allocWithZone(Foo) or395// [self allocWithZone:nil] -> objc_allocWithZone(self)396if (Sel.isKeywordSelector() && Sel.getNumArgs() == 1 &&397Args.size() == 1 && Args.front().getType()->isPointerType() &&398Sel.getNameForSlot(0) == "allocWithZone") {399const llvm::Value* arg = Args.front().getKnownRValue().getScalarVal();400if (isa<llvm::ConstantPointerNull>(arg))401return CGF.EmitObjCAllocWithZone(Receiver,402CGF.ConvertType(ResultType));403return std::nullopt;404}405}406break;407408case OMF_autorelease:409if (ResultType->isObjCObjectPointerType() &&410CGM.getLangOpts().getGC() == LangOptions::NonGC &&411Runtime.shouldUseARCFunctionsForRetainRelease())412return CGF.EmitObjCAutorelease(Receiver, CGF.ConvertType(ResultType));413break;414415case OMF_retain:416if (ResultType->isObjCObjectPointerType() &&417CGM.getLangOpts().getGC() == LangOptions::NonGC &&418Runtime.shouldUseARCFunctionsForRetainRelease())419return CGF.EmitObjCRetainNonBlock(Receiver, CGF.ConvertType(ResultType));420break;421422case OMF_release:423if (ResultType->isVoidType() &&424CGM.getLangOpts().getGC() == LangOptions::NonGC &&425Runtime.shouldUseARCFunctionsForRetainRelease()) {426CGF.EmitObjCRelease(Receiver, ARCPreciseLifetime);427return nullptr;428}429break;430431default:432break;433}434return std::nullopt;435}436437CodeGen::RValue CGObjCRuntime::GeneratePossiblySpecializedMessageSend(438CodeGenFunction &CGF, ReturnValueSlot Return, QualType ResultType,439Selector Sel, llvm::Value *Receiver, const CallArgList &Args,440const ObjCInterfaceDecl *OID, const ObjCMethodDecl *Method,441bool isClassMessage) {442if (std::optional<llvm::Value *> SpecializedResult =443tryGenerateSpecializedMessageSend(CGF, ResultType, Receiver, Args,444Sel, Method, isClassMessage)) {445return RValue::get(*SpecializedResult);446}447return GenerateMessageSend(CGF, Return, ResultType, Sel, Receiver, Args, OID,448Method);449}450451static void AppendFirstImpliedRuntimeProtocols(452const ObjCProtocolDecl *PD,453llvm::UniqueVector<const ObjCProtocolDecl *> &PDs) {454if (!PD->isNonRuntimeProtocol()) {455const auto *Can = PD->getCanonicalDecl();456PDs.insert(Can);457return;458}459460for (const auto *ParentPD : PD->protocols())461AppendFirstImpliedRuntimeProtocols(ParentPD, PDs);462}463464std::vector<const ObjCProtocolDecl *>465CGObjCRuntime::GetRuntimeProtocolList(ObjCProtocolDecl::protocol_iterator begin,466ObjCProtocolDecl::protocol_iterator end) {467std::vector<const ObjCProtocolDecl *> RuntimePds;468llvm::DenseSet<const ObjCProtocolDecl *> NonRuntimePDs;469470for (; begin != end; ++begin) {471const auto *It = *begin;472const auto *Can = It->getCanonicalDecl();473if (Can->isNonRuntimeProtocol())474NonRuntimePDs.insert(Can);475else476RuntimePds.push_back(Can);477}478479// If there are no non-runtime protocols then we can just stop now.480if (NonRuntimePDs.empty())481return RuntimePds;482483// Else we have to search through the non-runtime protocol's inheritancy484// hierarchy DAG stopping whenever a branch either finds a runtime protocol or485// a non-runtime protocol without any parents. These are the "first-implied"486// protocols from a non-runtime protocol.487llvm::UniqueVector<const ObjCProtocolDecl *> FirstImpliedProtos;488for (const auto *PD : NonRuntimePDs)489AppendFirstImpliedRuntimeProtocols(PD, FirstImpliedProtos);490491// Walk the Runtime list to get all protocols implied via the inclusion of492// this protocol, e.g. all protocols it inherits from including itself.493llvm::DenseSet<const ObjCProtocolDecl *> AllImpliedProtocols;494for (const auto *PD : RuntimePds) {495const auto *Can = PD->getCanonicalDecl();496AllImpliedProtocols.insert(Can);497Can->getImpliedProtocols(AllImpliedProtocols);498}499500// Similar to above, walk the list of first-implied protocols to find the set501// all the protocols implied excluding the listed protocols themselves since502// they are not yet a part of the `RuntimePds` list.503for (const auto *PD : FirstImpliedProtos) {504PD->getImpliedProtocols(AllImpliedProtocols);505}506507// From the first-implied list we have to finish building the final protocol508// list. If a protocol in the first-implied list was already implied via some509// inheritance path through some other protocols then it would be redundant to510// add it here and so we skip over it.511for (const auto *PD : FirstImpliedProtos) {512if (!AllImpliedProtocols.contains(PD)) {513RuntimePds.push_back(PD);514}515}516517return RuntimePds;518}519520/// Instead of '[[MyClass alloc] init]', try to generate521/// 'objc_alloc_init(MyClass)'. This provides a code size improvement on the522/// caller side, as well as the optimized objc_alloc.523static std::optional<llvm::Value *>524tryEmitSpecializedAllocInit(CodeGenFunction &CGF, const ObjCMessageExpr *OME) {525auto &Runtime = CGF.getLangOpts().ObjCRuntime;526if (!Runtime.shouldUseRuntimeFunctionForCombinedAllocInit())527return std::nullopt;528529// Match the exact pattern '[[MyClass alloc] init]'.530Selector Sel = OME->getSelector();531if (OME->getReceiverKind() != ObjCMessageExpr::Instance ||532!OME->getType()->isObjCObjectPointerType() || !Sel.isUnarySelector() ||533Sel.getNameForSlot(0) != "init")534return std::nullopt;535536// Okay, this is '[receiver init]', check if 'receiver' is '[cls alloc]'537// with 'cls' a Class.538auto *SubOME =539dyn_cast<ObjCMessageExpr>(OME->getInstanceReceiver()->IgnoreParenCasts());540if (!SubOME)541return std::nullopt;542Selector SubSel = SubOME->getSelector();543544if (!SubOME->getType()->isObjCObjectPointerType() ||545!SubSel.isUnarySelector() || SubSel.getNameForSlot(0) != "alloc")546return std::nullopt;547548llvm::Value *Receiver = nullptr;549switch (SubOME->getReceiverKind()) {550case ObjCMessageExpr::Instance:551if (!SubOME->getInstanceReceiver()->getType()->isObjCClassType())552return std::nullopt;553Receiver = CGF.EmitScalarExpr(SubOME->getInstanceReceiver());554break;555556case ObjCMessageExpr::Class: {557QualType ReceiverType = SubOME->getClassReceiver();558const ObjCObjectType *ObjTy = ReceiverType->castAs<ObjCObjectType>();559const ObjCInterfaceDecl *ID = ObjTy->getInterface();560assert(ID && "null interface should be impossible here");561Receiver = CGF.CGM.getObjCRuntime().GetClass(CGF, ID);562break;563}564case ObjCMessageExpr::SuperInstance:565case ObjCMessageExpr::SuperClass:566return std::nullopt;567}568569return CGF.EmitObjCAllocInit(Receiver, CGF.ConvertType(OME->getType()));570}571572RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,573ReturnValueSlot Return) {574// Only the lookup mechanism and first two arguments of the method575// implementation vary between runtimes. We can get the receiver and576// arguments in generic code.577578bool isDelegateInit = E->isDelegateInitCall();579580const ObjCMethodDecl *method = E->getMethodDecl();581582// If the method is -retain, and the receiver's being loaded from583// a __weak variable, peephole the entire operation to objc_loadWeakRetained.584if (method && E->getReceiverKind() == ObjCMessageExpr::Instance &&585method->getMethodFamily() == OMF_retain) {586if (auto lvalueExpr = findWeakLValue(E->getInstanceReceiver())) {587LValue lvalue = EmitLValue(lvalueExpr);588llvm::Value *result = EmitARCLoadWeakRetained(lvalue.getAddress());589return AdjustObjCObjectType(*this, E->getType(), RValue::get(result));590}591}592593if (std::optional<llvm::Value *> Val = tryEmitSpecializedAllocInit(*this, E))594return AdjustObjCObjectType(*this, E->getType(), RValue::get(*Val));595596// We don't retain the receiver in delegate init calls, and this is597// safe because the receiver value is always loaded from 'self',598// which we zero out. We don't want to Block_copy block receivers,599// though.600bool retainSelf =601(!isDelegateInit &&602CGM.getLangOpts().ObjCAutoRefCount &&603method &&604method->hasAttr<NSConsumesSelfAttr>());605606CGObjCRuntime &Runtime = CGM.getObjCRuntime();607bool isSuperMessage = false;608bool isClassMessage = false;609ObjCInterfaceDecl *OID = nullptr;610// Find the receiver611QualType ReceiverType;612llvm::Value *Receiver = nullptr;613switch (E->getReceiverKind()) {614case ObjCMessageExpr::Instance:615ReceiverType = E->getInstanceReceiver()->getType();616isClassMessage = ReceiverType->isObjCClassType();617if (retainSelf) {618TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,619E->getInstanceReceiver());620Receiver = ter.getPointer();621if (ter.getInt()) retainSelf = false;622} else623Receiver = EmitScalarExpr(E->getInstanceReceiver());624break;625626case ObjCMessageExpr::Class: {627ReceiverType = E->getClassReceiver();628OID = ReceiverType->castAs<ObjCObjectType>()->getInterface();629assert(OID && "Invalid Objective-C class message send");630Receiver = Runtime.GetClass(*this, OID);631isClassMessage = true;632break;633}634635case ObjCMessageExpr::SuperInstance:636ReceiverType = E->getSuperType();637Receiver = LoadObjCSelf();638isSuperMessage = true;639break;640641case ObjCMessageExpr::SuperClass:642ReceiverType = E->getSuperType();643Receiver = LoadObjCSelf();644isSuperMessage = true;645isClassMessage = true;646break;647}648649if (retainSelf)650Receiver = EmitARCRetainNonBlock(Receiver);651652// In ARC, we sometimes want to "extend the lifetime"653// (i.e. retain+autorelease) of receivers of returns-inner-pointer654// messages.655if (getLangOpts().ObjCAutoRefCount && method &&656method->hasAttr<ObjCReturnsInnerPointerAttr>() &&657shouldExtendReceiverForInnerPointerMessage(E))658Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);659660QualType ResultType = method ? method->getReturnType() : E->getType();661662CallArgList Args;663EmitCallArgs(Args, method, E->arguments(), /*AC*/AbstractCallee(method));664665// For delegate init calls in ARC, do an unsafe store of null into666// self. This represents the call taking direct ownership of that667// value. We have to do this after emitting the other call668// arguments because they might also reference self, but we don't669// have to worry about any of them modifying self because that would670// be an undefined read and write of an object in unordered671// expressions.672if (isDelegateInit) {673assert(getLangOpts().ObjCAutoRefCount &&674"delegate init calls should only be marked in ARC");675676// Do an unsafe store of null into self.677Address selfAddr =678GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());679Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);680}681682RValue result;683if (isSuperMessage) {684// super is only valid in an Objective-C method685const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);686bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());687result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,688E->getSelector(),689OMD->getClassInterface(),690isCategoryImpl,691Receiver,692isClassMessage,693Args,694method);695} else {696// Call runtime methods directly if we can.697result = Runtime.GeneratePossiblySpecializedMessageSend(698*this, Return, ResultType, E->getSelector(), Receiver, Args, OID,699method, isClassMessage);700}701702// For delegate init calls in ARC, implicitly store the result of703// the call back into self. This takes ownership of the value.704if (isDelegateInit) {705Address selfAddr =706GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());707llvm::Value *newSelf = result.getScalarVal();708709// The delegate return type isn't necessarily a matching type; in710// fact, it's quite likely to be 'id'.711llvm::Type *selfTy = selfAddr.getElementType();712newSelf = Builder.CreateBitCast(newSelf, selfTy);713714Builder.CreateStore(newSelf, selfAddr);715}716717return AdjustObjCObjectType(*this, E->getType(), result);718}719720namespace {721struct FinishARCDealloc final : EHScopeStack::Cleanup {722void Emit(CodeGenFunction &CGF, Flags flags) override {723const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);724725const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());726const ObjCInterfaceDecl *iface = impl->getClassInterface();727if (!iface->getSuperClass()) return;728729bool isCategory = isa<ObjCCategoryImplDecl>(impl);730731// Call [super dealloc] if we have a superclass.732llvm::Value *self = CGF.LoadObjCSelf();733734CallArgList args;735CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),736CGF.getContext().VoidTy,737method->getSelector(),738iface,739isCategory,740self,741/*is class msg*/ false,742args,743method);744}745};746}747748/// StartObjCMethod - Begin emission of an ObjCMethod. This generates749/// the LLVM function and sets the other context used by750/// CodeGenFunction.751void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,752const ObjCContainerDecl *CD) {753SourceLocation StartLoc = OMD->getBeginLoc();754FunctionArgList args;755// Check if we should generate debug info for this method.756if (OMD->hasAttr<NoDebugAttr>())757DebugInfo = nullptr; // disable debug info indefinitely for this function758759llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);760761const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);762if (OMD->isDirectMethod()) {763Fn->setVisibility(llvm::Function::HiddenVisibility);764CGM.SetLLVMFunctionAttributes(OMD, FI, Fn, /*IsThunk=*/false);765CGM.SetLLVMFunctionAttributesForDefinition(OMD, Fn);766} else {767CGM.SetInternalFunctionAttributes(OMD, Fn, FI);768}769770args.push_back(OMD->getSelfDecl());771if (!OMD->isDirectMethod())772args.push_back(OMD->getCmdDecl());773774args.append(OMD->param_begin(), OMD->param_end());775776CurGD = OMD;777CurEHLocation = OMD->getEndLoc();778779StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,780OMD->getLocation(), StartLoc);781782if (OMD->isDirectMethod()) {783// This function is a direct call, it has to implement a nil check784// on entry.785//786// TODO: possibly have several entry points to elide the check787CGM.getObjCRuntime().GenerateDirectMethodPrologue(*this, Fn, OMD, CD);788}789790// In ARC, certain methods get an extra cleanup.791if (CGM.getLangOpts().ObjCAutoRefCount &&792OMD->isInstanceMethod() &&793OMD->getSelector().isUnarySelector()) {794const IdentifierInfo *ident =795OMD->getSelector().getIdentifierInfoForSlot(0);796if (ident->isStr("dealloc"))797EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());798}799}800801static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,802LValue lvalue, QualType type);803804/// Generate an Objective-C method. An Objective-C method is a C function with805/// its pointer, name, and types registered in the class structure.806void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {807StartObjCMethod(OMD, OMD->getClassInterface());808PGO.assignRegionCounters(GlobalDecl(OMD), CurFn);809assert(isa<CompoundStmt>(OMD->getBody()));810incrementProfileCounter(OMD->getBody());811EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));812FinishFunction(OMD->getBodyRBrace());813}814815/// emitStructGetterCall - Call the runtime function to load a property816/// into the return value slot.817static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,818bool isAtomic, bool hasStrong) {819ASTContext &Context = CGF.getContext();820821llvm::Value *src =822CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)823.getPointer(CGF);824825// objc_copyStruct (ReturnValue, &structIvar,826// sizeof (Type of Ivar), isAtomic, false);827CallArgList args;828829llvm::Value *dest = CGF.ReturnValue.emitRawPointer(CGF);830args.add(RValue::get(dest), Context.VoidPtrTy);831args.add(RValue::get(src), Context.VoidPtrTy);832833CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());834args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());835args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);836args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);837838llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();839CGCallee callee = CGCallee::forDirect(fn);840CGF.EmitCall(CGF.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, args),841callee, ReturnValueSlot(), args);842}843844/// Determine whether the given architecture supports unaligned atomic845/// accesses. They don't have to be fast, just faster than a function846/// call and a mutex.847static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {848// FIXME: Allow unaligned atomic load/store on x86. (It is not849// currently supported by the backend.)850return false;851}852853/// Return the maximum size that permits atomic accesses for the given854/// architecture.855static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,856llvm::Triple::ArchType arch) {857// ARM has 8-byte atomic accesses, but it's not clear whether we858// want to rely on them here.859860// In the default case, just assume that any size up to a pointer is861// fine given adequate alignment.862return CharUnits::fromQuantity(CGM.PointerSizeInBytes);863}864865namespace {866class PropertyImplStrategy {867public:868enum StrategyKind {869/// The 'native' strategy is to use the architecture's provided870/// reads and writes.871Native,872873/// Use objc_setProperty and objc_getProperty.874GetSetProperty,875876/// Use objc_setProperty for the setter, but use expression877/// evaluation for the getter.878SetPropertyAndExpressionGet,879880/// Use objc_copyStruct.881CopyStruct,882883/// The 'expression' strategy is to emit normal assignment or884/// lvalue-to-rvalue expressions.885Expression886};887888StrategyKind getKind() const { return StrategyKind(Kind); }889890bool hasStrongMember() const { return HasStrong; }891bool isAtomic() const { return IsAtomic; }892bool isCopy() const { return IsCopy; }893894CharUnits getIvarSize() const { return IvarSize; }895CharUnits getIvarAlignment() const { return IvarAlignment; }896897PropertyImplStrategy(CodeGenModule &CGM,898const ObjCPropertyImplDecl *propImpl);899900private:901LLVM_PREFERRED_TYPE(StrategyKind)902unsigned Kind : 8;903LLVM_PREFERRED_TYPE(bool)904unsigned IsAtomic : 1;905LLVM_PREFERRED_TYPE(bool)906unsigned IsCopy : 1;907LLVM_PREFERRED_TYPE(bool)908unsigned HasStrong : 1;909910CharUnits IvarSize;911CharUnits IvarAlignment;912};913}914915/// Pick an implementation strategy for the given property synthesis.916PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,917const ObjCPropertyImplDecl *propImpl) {918const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();919ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();920921IsCopy = (setterKind == ObjCPropertyDecl::Copy);922IsAtomic = prop->isAtomic();923HasStrong = false; // doesn't matter here.924925// Evaluate the ivar's size and alignment.926ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();927QualType ivarType = ivar->getType();928auto TInfo = CGM.getContext().getTypeInfoInChars(ivarType);929IvarSize = TInfo.Width;930IvarAlignment = TInfo.Align;931932// If we have a copy property, we always have to use setProperty.933// If the property is atomic we need to use getProperty, but in934// the nonatomic case we can just use expression.935if (IsCopy) {936Kind = IsAtomic ? GetSetProperty : SetPropertyAndExpressionGet;937return;938}939940// Handle retain.941if (setterKind == ObjCPropertyDecl::Retain) {942// In GC-only, there's nothing special that needs to be done.943if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {944// fallthrough945946// In ARC, if the property is non-atomic, use expression emission,947// which translates to objc_storeStrong. This isn't required, but948// it's slightly nicer.949} else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {950// Using standard expression emission for the setter is only951// acceptable if the ivar is __strong, which won't be true if952// the property is annotated with __attribute__((NSObject)).953// TODO: falling all the way back to objc_setProperty here is954// just laziness, though; we could still use objc_storeStrong955// if we hacked it right.956if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)957Kind = Expression;958else959Kind = SetPropertyAndExpressionGet;960return;961962// Otherwise, we need to at least use setProperty. However, if963// the property isn't atomic, we can use normal expression964// emission for the getter.965} else if (!IsAtomic) {966Kind = SetPropertyAndExpressionGet;967return;968969// Otherwise, we have to use both setProperty and getProperty.970} else {971Kind = GetSetProperty;972return;973}974}975976// If we're not atomic, just use expression accesses.977if (!IsAtomic) {978Kind = Expression;979return;980}981982// Properties on bitfield ivars need to be emitted using expression983// accesses even if they're nominally atomic.984if (ivar->isBitField()) {985Kind = Expression;986return;987}988989// GC-qualified or ARC-qualified ivars need to be emitted as990// expressions. This actually works out to being atomic anyway,991// except for ARC __strong, but that should trigger the above code.992if (ivarType.hasNonTrivialObjCLifetime() ||993(CGM.getLangOpts().getGC() &&994CGM.getContext().getObjCGCAttrKind(ivarType))) {995Kind = Expression;996return;997}998999// Compute whether the ivar has strong members.1000if (CGM.getLangOpts().getGC())1001if (const RecordType *recordType = ivarType->getAs<RecordType>())1002HasStrong = recordType->getDecl()->hasObjectMember();10031004// We can never access structs with object members with a native1005// access, because we need to use write barriers. This is what1006// objc_copyStruct is for.1007if (HasStrong) {1008Kind = CopyStruct;1009return;1010}10111012// Otherwise, this is target-dependent and based on the size and1013// alignment of the ivar.10141015// If the size of the ivar is not a power of two, give up. We don't1016// want to get into the business of doing compare-and-swaps.1017if (!IvarSize.isPowerOfTwo()) {1018Kind = CopyStruct;1019return;1020}10211022llvm::Triple::ArchType arch =1023CGM.getTarget().getTriple().getArch();10241025// Most architectures require memory to fit within a single cache1026// line, so the alignment has to be at least the size of the access.1027// Otherwise we have to grab a lock.1028if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {1029Kind = CopyStruct;1030return;1031}10321033// If the ivar's size exceeds the architecture's maximum atomic1034// access size, we have to use CopyStruct.1035if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {1036Kind = CopyStruct;1037return;1038}10391040// Otherwise, we can use native loads and stores.1041Kind = Native;1042}10431044/// Generate an Objective-C property getter function.1045///1046/// The given Decl must be an ObjCImplementationDecl. \@synthesize1047/// is illegal within a category.1048void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,1049const ObjCPropertyImplDecl *PID) {1050llvm::Constant *AtomicHelperFn =1051CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);1052ObjCMethodDecl *OMD = PID->getGetterMethodDecl();1053assert(OMD && "Invalid call to generate getter (empty method)");1054StartObjCMethod(OMD, IMP->getClassInterface());10551056generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);10571058FinishFunction(OMD->getEndLoc());1059}10601061static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {1062const Expr *getter = propImpl->getGetterCXXConstructor();1063if (!getter) return true;10641065// Sema only makes only of these when the ivar has a C++ class type,1066// so the form is pretty constrained.10671068// If the property has a reference type, we might just be binding a1069// reference, in which case the result will be a gl-value. We should1070// treat this as a non-trivial operation.1071if (getter->isGLValue())1072return false;10731074// If we selected a trivial copy-constructor, we're okay.1075if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))1076return (construct->getConstructor()->isTrivial());10771078// The constructor might require cleanups (in which case it's never1079// trivial).1080assert(isa<ExprWithCleanups>(getter));1081return false;1082}10831084/// emitCPPObjectAtomicGetterCall - Call the runtime function to1085/// copy the ivar into the resturn slot.1086static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,1087llvm::Value *returnAddr,1088ObjCIvarDecl *ivar,1089llvm::Constant *AtomicHelperFn) {1090// objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,1091// AtomicHelperFn);1092CallArgList args;10931094// The 1st argument is the return Slot.1095args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);10961097// The 2nd argument is the address of the ivar.1098llvm::Value *ivarAddr =1099CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)1100.getPointer(CGF);1101args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);11021103// Third argument is the helper function.1104args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);11051106llvm::FunctionCallee copyCppAtomicObjectFn =1107CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();1108CGCallee callee = CGCallee::forDirect(copyCppAtomicObjectFn);1109CGF.EmitCall(1110CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),1111callee, ReturnValueSlot(), args);1112}11131114// emitCmdValueForGetterSetterBody - Handle emitting the load necessary for1115// the `_cmd` selector argument for getter/setter bodies. For direct methods,1116// this returns an undefined/poison value; this matches behavior prior to `_cmd`1117// being removed from the direct method ABI as the getter/setter caller would1118// never load one. For non-direct methods, this emits a load of the implicit1119// `_cmd` storage.1120static llvm::Value *emitCmdValueForGetterSetterBody(CodeGenFunction &CGF,1121ObjCMethodDecl *MD) {1122if (MD->isDirectMethod()) {1123// Direct methods do not have a `_cmd` argument. Emit an undefined/poison1124// value. This will be passed to objc_getProperty/objc_setProperty, which1125// has not appeared bothered by the `_cmd` argument being undefined before.1126llvm::Type *selType = CGF.ConvertType(CGF.getContext().getObjCSelType());1127return llvm::PoisonValue::get(selType);1128}11291130return CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(MD->getCmdDecl()), "cmd");1131}11321133void1134CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,1135const ObjCPropertyImplDecl *propImpl,1136const ObjCMethodDecl *GetterMethodDecl,1137llvm::Constant *AtomicHelperFn) {11381139ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();11401141if (ivar->getType().isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct) {1142if (!AtomicHelperFn) {1143LValue Src =1144EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);1145LValue Dst = MakeAddrLValue(ReturnValue, ivar->getType());1146callCStructCopyConstructor(Dst, Src);1147} else {1148ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();1149emitCPPObjectAtomicGetterCall(*this, ReturnValue.emitRawPointer(*this),1150ivar, AtomicHelperFn);1151}1152return;1153}11541155// If there's a non-trivial 'get' expression, we just have to emit that.1156if (!hasTrivialGetExpr(propImpl)) {1157if (!AtomicHelperFn) {1158auto *ret = ReturnStmt::Create(getContext(), SourceLocation(),1159propImpl->getGetterCXXConstructor(),1160/* NRVOCandidate=*/nullptr);1161EmitReturnStmt(*ret);1162}1163else {1164ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();1165emitCPPObjectAtomicGetterCall(*this, ReturnValue.emitRawPointer(*this),1166ivar, AtomicHelperFn);1167}1168return;1169}11701171const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();1172QualType propType = prop->getType();1173ObjCMethodDecl *getterMethod = propImpl->getGetterMethodDecl();11741175// Pick an implementation strategy.1176PropertyImplStrategy strategy(CGM, propImpl);1177switch (strategy.getKind()) {1178case PropertyImplStrategy::Native: {1179// We don't need to do anything for a zero-size struct.1180if (strategy.getIvarSize().isZero())1181return;11821183LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);11841185// Currently, all atomic accesses have to be through integer1186// types, so there's no point in trying to pick a prettier type.1187uint64_t ivarSize = getContext().toBits(strategy.getIvarSize());1188llvm::Type *bitcastType = llvm::Type::getIntNTy(getLLVMContext(), ivarSize);11891190// Perform an atomic load. This does not impose ordering constraints.1191Address ivarAddr = LV.getAddress();1192ivarAddr = ivarAddr.withElementType(bitcastType);1193llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");1194load->setAtomic(llvm::AtomicOrdering::Unordered);11951196// Store that value into the return address. Doing this with a1197// bitcast is likely to produce some pretty ugly IR, but it's not1198// the *most* terrible thing in the world.1199llvm::Type *retTy = ConvertType(getterMethod->getReturnType());1200uint64_t retTySize = CGM.getDataLayout().getTypeSizeInBits(retTy);1201llvm::Value *ivarVal = load;1202if (ivarSize > retTySize) {1203bitcastType = llvm::Type::getIntNTy(getLLVMContext(), retTySize);1204ivarVal = Builder.CreateTrunc(load, bitcastType);1205}1206Builder.CreateStore(ivarVal, ReturnValue.withElementType(bitcastType));12071208// Make sure we don't do an autorelease.1209AutoreleaseResult = false;1210return;1211}12121213case PropertyImplStrategy::GetSetProperty: {1214llvm::FunctionCallee getPropertyFn =1215CGM.getObjCRuntime().GetPropertyGetFunction();1216if (!getPropertyFn) {1217CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");1218return;1219}1220CGCallee callee = CGCallee::forDirect(getPropertyFn);12211222// Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).1223// FIXME: Can't this be simpler? This might even be worse than the1224// corresponding gcc code.1225llvm::Value *cmd = emitCmdValueForGetterSetterBody(*this, getterMethod);1226llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);1227llvm::Value *ivarOffset =1228EmitIvarOffsetAsPointerDiff(classImpl->getClassInterface(), ivar);12291230CallArgList args;1231args.add(RValue::get(self), getContext().getObjCIdType());1232args.add(RValue::get(cmd), getContext().getObjCSelType());1233args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());1234args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),1235getContext().BoolTy);12361237// FIXME: We shouldn't need to get the function info here, the1238// runtime already should have computed it to build the function.1239llvm::CallBase *CallInstruction;1240RValue RV = EmitCall(getTypes().arrangeBuiltinFunctionCall(1241getContext().getObjCIdType(), args),1242callee, ReturnValueSlot(), args, &CallInstruction);1243if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))1244call->setTailCall();12451246// We need to fix the type here. Ivars with copy & retain are1247// always objects so we don't need to worry about complex or1248// aggregates.1249RV = RValue::get(Builder.CreateBitCast(1250RV.getScalarVal(),1251getTypes().ConvertType(getterMethod->getReturnType())));12521253EmitReturnOfRValue(RV, propType);12541255// objc_getProperty does an autorelease, so we should suppress ours.1256AutoreleaseResult = false;12571258return;1259}12601261case PropertyImplStrategy::CopyStruct:1262emitStructGetterCall(*this, ivar, strategy.isAtomic(),1263strategy.hasStrongMember());1264return;12651266case PropertyImplStrategy::Expression:1267case PropertyImplStrategy::SetPropertyAndExpressionGet: {1268LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);12691270QualType ivarType = ivar->getType();1271switch (getEvaluationKind(ivarType)) {1272case TEK_Complex: {1273ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());1274EmitStoreOfComplex(pair, MakeAddrLValue(ReturnValue, ivarType),1275/*init*/ true);1276return;1277}1278case TEK_Aggregate: {1279// The return value slot is guaranteed to not be aliased, but1280// that's not necessarily the same as "on the stack", so1281// we still potentially need objc_memmove_collectable.1282EmitAggregateCopy(/* Dest= */ MakeAddrLValue(ReturnValue, ivarType),1283/* Src= */ LV, ivarType, getOverlapForReturnValue());1284return;1285}1286case TEK_Scalar: {1287llvm::Value *value;1288if (propType->isReferenceType()) {1289value = LV.getAddress().emitRawPointer(*this);1290} else {1291// We want to load and autoreleaseReturnValue ARC __weak ivars.1292if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {1293if (getLangOpts().ObjCAutoRefCount) {1294value = emitARCRetainLoadOfScalar(*this, LV, ivarType);1295} else {1296value = EmitARCLoadWeak(LV.getAddress());1297}12981299// Otherwise we want to do a simple load, suppressing the1300// final autorelease.1301} else {1302value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();1303AutoreleaseResult = false;1304}13051306value = Builder.CreateBitCast(1307value, ConvertType(GetterMethodDecl->getReturnType()));1308}13091310EmitReturnOfRValue(RValue::get(value), propType);1311return;1312}1313}1314llvm_unreachable("bad evaluation kind");1315}13161317}1318llvm_unreachable("bad @property implementation strategy!");1319}13201321/// emitStructSetterCall - Call the runtime function to store the value1322/// from the first formal parameter into the given ivar.1323static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,1324ObjCIvarDecl *ivar) {1325// objc_copyStruct (&structIvar, &Arg,1326// sizeof (struct something), true, false);1327CallArgList args;13281329// The first argument is the address of the ivar.1330llvm::Value *ivarAddr =1331CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)1332.getPointer(CGF);1333ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);1334args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);13351336// The second argument is the address of the parameter variable.1337ParmVarDecl *argVar = *OMD->param_begin();1338DeclRefExpr argRef(CGF.getContext(), argVar, false,1339argVar->getType().getNonReferenceType(), VK_LValue,1340SourceLocation());1341llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(CGF);1342args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);13431344// The third argument is the sizeof the type.1345llvm::Value *size =1346CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));1347args.add(RValue::get(size), CGF.getContext().getSizeType());13481349// The fourth argument is the 'isAtomic' flag.1350args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);13511352// The fifth argument is the 'hasStrong' flag.1353// FIXME: should this really always be false?1354args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);13551356llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetSetStructFunction();1357CGCallee callee = CGCallee::forDirect(fn);1358CGF.EmitCall(1359CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),1360callee, ReturnValueSlot(), args);1361}13621363/// emitCPPObjectAtomicSetterCall - Call the runtime function to store1364/// the value from the first formal parameter into the given ivar, using1365/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.1366static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,1367ObjCMethodDecl *OMD,1368ObjCIvarDecl *ivar,1369llvm::Constant *AtomicHelperFn) {1370// objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,1371// AtomicHelperFn);1372CallArgList args;13731374// The first argument is the address of the ivar.1375llvm::Value *ivarAddr =1376CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)1377.getPointer(CGF);1378args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);13791380// The second argument is the address of the parameter variable.1381ParmVarDecl *argVar = *OMD->param_begin();1382DeclRefExpr argRef(CGF.getContext(), argVar, false,1383argVar->getType().getNonReferenceType(), VK_LValue,1384SourceLocation());1385llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(CGF);1386args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);13871388// Third argument is the helper function.1389args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);13901391llvm::FunctionCallee fn =1392CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();1393CGCallee callee = CGCallee::forDirect(fn);1394CGF.EmitCall(1395CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),1396callee, ReturnValueSlot(), args);1397}139813991400static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {1401Expr *setter = PID->getSetterCXXAssignment();1402if (!setter) return true;14031404// Sema only makes only of these when the ivar has a C++ class type,1405// so the form is pretty constrained.14061407// An operator call is trivial if the function it calls is trivial.1408// This also implies that there's nothing non-trivial going on with1409// the arguments, because operator= can only be trivial if it's a1410// synthesized assignment operator and therefore both parameters are1411// references.1412if (CallExpr *call = dyn_cast<CallExpr>(setter)) {1413if (const FunctionDecl *callee1414= dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))1415if (callee->isTrivial())1416return true;1417return false;1418}14191420assert(isa<ExprWithCleanups>(setter));1421return false;1422}14231424static bool UseOptimizedSetter(CodeGenModule &CGM) {1425if (CGM.getLangOpts().getGC() != LangOptions::NonGC)1426return false;1427return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();1428}14291430void1431CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,1432const ObjCPropertyImplDecl *propImpl,1433llvm::Constant *AtomicHelperFn) {1434ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();1435ObjCMethodDecl *setterMethod = propImpl->getSetterMethodDecl();14361437if (ivar->getType().isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct) {1438ParmVarDecl *PVD = *setterMethod->param_begin();1439if (!AtomicHelperFn) {1440// Call the move assignment operator instead of calling the copy1441// assignment operator and destructor.1442LValue Dst = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar,1443/*quals*/ 0);1444LValue Src = MakeAddrLValue(GetAddrOfLocalVar(PVD), ivar->getType());1445callCStructMoveAssignmentOperator(Dst, Src);1446} else {1447// If atomic, assignment is called via a locking api.1448emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar, AtomicHelperFn);1449}1450// Decativate the destructor for the setter parameter.1451DeactivateCleanupBlock(CalleeDestructedParamCleanups[PVD], AllocaInsertPt);1452return;1453}14541455// Just use the setter expression if Sema gave us one and it's1456// non-trivial.1457if (!hasTrivialSetExpr(propImpl)) {1458if (!AtomicHelperFn)1459// If non-atomic, assignment is called directly.1460EmitStmt(propImpl->getSetterCXXAssignment());1461else1462// If atomic, assignment is called via a locking api.1463emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,1464AtomicHelperFn);1465return;1466}14671468PropertyImplStrategy strategy(CGM, propImpl);1469switch (strategy.getKind()) {1470case PropertyImplStrategy::Native: {1471// We don't need to do anything for a zero-size struct.1472if (strategy.getIvarSize().isZero())1473return;14741475Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());14761477LValue ivarLValue =1478EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);1479Address ivarAddr = ivarLValue.getAddress();14801481// Currently, all atomic accesses have to be through integer1482// types, so there's no point in trying to pick a prettier type.1483llvm::Type *castType = llvm::Type::getIntNTy(1484getLLVMContext(), getContext().toBits(strategy.getIvarSize()));14851486// Cast both arguments to the chosen operation type.1487argAddr = argAddr.withElementType(castType);1488ivarAddr = ivarAddr.withElementType(castType);14891490llvm::Value *load = Builder.CreateLoad(argAddr);14911492// Perform an atomic store. There are no memory ordering requirements.1493llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);1494store->setAtomic(llvm::AtomicOrdering::Unordered);1495return;1496}14971498case PropertyImplStrategy::GetSetProperty:1499case PropertyImplStrategy::SetPropertyAndExpressionGet: {15001501llvm::FunctionCallee setOptimizedPropertyFn = nullptr;1502llvm::FunctionCallee setPropertyFn = nullptr;1503if (UseOptimizedSetter(CGM)) {1504// 10.8 and iOS 6.0 code and GC is off1505setOptimizedPropertyFn =1506CGM.getObjCRuntime().GetOptimizedPropertySetFunction(1507strategy.isAtomic(), strategy.isCopy());1508if (!setOptimizedPropertyFn) {1509CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");1510return;1511}1512}1513else {1514setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();1515if (!setPropertyFn) {1516CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");1517return;1518}1519}15201521// Emit objc_setProperty((id) self, _cmd, offset, arg,1522// <is-atomic>, <is-copy>).1523llvm::Value *cmd = emitCmdValueForGetterSetterBody(*this, setterMethod);1524llvm::Value *self =1525Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);1526llvm::Value *ivarOffset =1527EmitIvarOffsetAsPointerDiff(classImpl->getClassInterface(), ivar);1528Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());1529llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");1530arg = Builder.CreateBitCast(arg, VoidPtrTy);15311532CallArgList args;1533args.add(RValue::get(self), getContext().getObjCIdType());1534args.add(RValue::get(cmd), getContext().getObjCSelType());1535if (setOptimizedPropertyFn) {1536args.add(RValue::get(arg), getContext().getObjCIdType());1537args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());1538CGCallee callee = CGCallee::forDirect(setOptimizedPropertyFn);1539EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),1540callee, ReturnValueSlot(), args);1541} else {1542args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());1543args.add(RValue::get(arg), getContext().getObjCIdType());1544args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),1545getContext().BoolTy);1546args.add(RValue::get(Builder.getInt1(strategy.isCopy())),1547getContext().BoolTy);1548// FIXME: We shouldn't need to get the function info here, the runtime1549// already should have computed it to build the function.1550CGCallee callee = CGCallee::forDirect(setPropertyFn);1551EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),1552callee, ReturnValueSlot(), args);1553}15541555return;1556}15571558case PropertyImplStrategy::CopyStruct:1559emitStructSetterCall(*this, setterMethod, ivar);1560return;15611562case PropertyImplStrategy::Expression:1563break;1564}15651566// Otherwise, fake up some ASTs and emit a normal assignment.1567ValueDecl *selfDecl = setterMethod->getSelfDecl();1568DeclRefExpr self(getContext(), selfDecl, false, selfDecl->getType(),1569VK_LValue, SourceLocation());1570ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack, selfDecl->getType(),1571CK_LValueToRValue, &self, VK_PRValue,1572FPOptionsOverride());1573ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),1574SourceLocation(), SourceLocation(),1575&selfLoad, true, true);15761577ParmVarDecl *argDecl = *setterMethod->param_begin();1578QualType argType = argDecl->getType().getNonReferenceType();1579DeclRefExpr arg(getContext(), argDecl, false, argType, VK_LValue,1580SourceLocation());1581ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,1582argType.getUnqualifiedType(), CK_LValueToRValue,1583&arg, VK_PRValue, FPOptionsOverride());15841585// The property type can differ from the ivar type in some situations with1586// Objective-C pointer types, we can always bit cast the RHS in these cases.1587// The following absurdity is just to ensure well-formed IR.1588CastKind argCK = CK_NoOp;1589if (ivarRef.getType()->isObjCObjectPointerType()) {1590if (argLoad.getType()->isObjCObjectPointerType())1591argCK = CK_BitCast;1592else if (argLoad.getType()->isBlockPointerType())1593argCK = CK_BlockPointerToObjCPointerCast;1594else1595argCK = CK_CPointerToObjCPointerCast;1596} else if (ivarRef.getType()->isBlockPointerType()) {1597if (argLoad.getType()->isBlockPointerType())1598argCK = CK_BitCast;1599else1600argCK = CK_AnyPointerToBlockPointerCast;1601} else if (ivarRef.getType()->isPointerType()) {1602argCK = CK_BitCast;1603} else if (argLoad.getType()->isAtomicType() &&1604!ivarRef.getType()->isAtomicType()) {1605argCK = CK_AtomicToNonAtomic;1606} else if (!argLoad.getType()->isAtomicType() &&1607ivarRef.getType()->isAtomicType()) {1608argCK = CK_NonAtomicToAtomic;1609}1610ImplicitCastExpr argCast(ImplicitCastExpr::OnStack, ivarRef.getType(), argCK,1611&argLoad, VK_PRValue, FPOptionsOverride());1612Expr *finalArg = &argLoad;1613if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),1614argLoad.getType()))1615finalArg = &argCast;16161617BinaryOperator *assign = BinaryOperator::Create(1618getContext(), &ivarRef, finalArg, BO_Assign, ivarRef.getType(),1619VK_PRValue, OK_Ordinary, SourceLocation(), FPOptionsOverride());1620EmitStmt(assign);1621}16221623/// Generate an Objective-C property setter function.1624///1625/// The given Decl must be an ObjCImplementationDecl. \@synthesize1626/// is illegal within a category.1627void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,1628const ObjCPropertyImplDecl *PID) {1629llvm::Constant *AtomicHelperFn =1630CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);1631ObjCMethodDecl *OMD = PID->getSetterMethodDecl();1632assert(OMD && "Invalid call to generate setter (empty method)");1633StartObjCMethod(OMD, IMP->getClassInterface());16341635generateObjCSetterBody(IMP, PID, AtomicHelperFn);16361637FinishFunction(OMD->getEndLoc());1638}16391640namespace {1641struct DestroyIvar final : EHScopeStack::Cleanup {1642private:1643llvm::Value *addr;1644const ObjCIvarDecl *ivar;1645CodeGenFunction::Destroyer *destroyer;1646bool useEHCleanupForArray;1647public:1648DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,1649CodeGenFunction::Destroyer *destroyer,1650bool useEHCleanupForArray)1651: addr(addr), ivar(ivar), destroyer(destroyer),1652useEHCleanupForArray(useEHCleanupForArray) {}16531654void Emit(CodeGenFunction &CGF, Flags flags) override {1655LValue lvalue1656= CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);1657CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,1658flags.isForNormalCleanup() && useEHCleanupForArray);1659}1660};1661}16621663/// Like CodeGenFunction::destroyARCStrong, but do it with a call.1664static void destroyARCStrongWithStore(CodeGenFunction &CGF,1665Address addr,1666QualType type) {1667llvm::Value *null = getNullForVariable(addr);1668CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);1669}16701671static void emitCXXDestructMethod(CodeGenFunction &CGF,1672ObjCImplementationDecl *impl) {1673CodeGenFunction::RunCleanupsScope scope(CGF);16741675llvm::Value *self = CGF.LoadObjCSelf();16761677const ObjCInterfaceDecl *iface = impl->getClassInterface();1678for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();1679ivar; ivar = ivar->getNextIvar()) {1680QualType type = ivar->getType();16811682// Check whether the ivar is a destructible type.1683QualType::DestructionKind dtorKind = type.isDestructedType();1684if (!dtorKind) continue;16851686CodeGenFunction::Destroyer *destroyer = nullptr;16871688// Use a call to objc_storeStrong to destroy strong ivars, for the1689// general benefit of the tools.1690if (dtorKind == QualType::DK_objc_strong_lifetime) {1691destroyer = destroyARCStrongWithStore;16921693// Otherwise use the default for the destruction kind.1694} else {1695destroyer = CGF.getDestroyer(dtorKind);1696}16971698CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);16991700CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,1701cleanupKind & EHCleanup);1702}17031704assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");1705}17061707void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,1708ObjCMethodDecl *MD,1709bool ctor) {1710MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());1711StartObjCMethod(MD, IMP->getClassInterface());17121713// Emit .cxx_construct.1714if (ctor) {1715// Suppress the final autorelease in ARC.1716AutoreleaseResult = false;17171718for (const auto *IvarInit : IMP->inits()) {1719FieldDecl *Field = IvarInit->getAnyMember();1720ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);1721LValue LV = EmitLValueForIvar(TypeOfSelfObject(),1722LoadObjCSelf(), Ivar, 0);1723EmitAggExpr(IvarInit->getInit(),1724AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,1725AggValueSlot::DoesNotNeedGCBarriers,1726AggValueSlot::IsNotAliased,1727AggValueSlot::DoesNotOverlap));1728}1729// constructor returns 'self'.1730CodeGenTypes &Types = CGM.getTypes();1731QualType IdTy(CGM.getContext().getObjCIdType());1732llvm::Value *SelfAsId =1733Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));1734EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);17351736// Emit .cxx_destruct.1737} else {1738emitCXXDestructMethod(*this, IMP);1739}1740FinishFunction();1741}17421743llvm::Value *CodeGenFunction::LoadObjCSelf() {1744VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();1745DeclRefExpr DRE(getContext(), Self,1746/*is enclosing local*/ (CurFuncDecl != CurCodeDecl),1747Self->getType(), VK_LValue, SourceLocation());1748return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());1749}17501751QualType CodeGenFunction::TypeOfSelfObject() {1752const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);1753ImplicitParamDecl *selfDecl = OMD->getSelfDecl();1754const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(1755getContext().getCanonicalType(selfDecl->getType()));1756return PTy->getPointeeType();1757}17581759void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){1760llvm::FunctionCallee EnumerationMutationFnPtr =1761CGM.getObjCRuntime().EnumerationMutationFunction();1762if (!EnumerationMutationFnPtr) {1763CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");1764return;1765}1766CGCallee EnumerationMutationFn =1767CGCallee::forDirect(EnumerationMutationFnPtr);17681769CGDebugInfo *DI = getDebugInfo();1770if (DI)1771DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());17721773RunCleanupsScope ForScope(*this);17741775// The local variable comes into scope immediately.1776AutoVarEmission variable = AutoVarEmission::invalid();1777if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))1778variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));17791780JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");17811782// Fast enumeration state.1783QualType StateTy = CGM.getObjCFastEnumerationStateType();1784Address StatePtr = CreateMemTemp(StateTy, "state.ptr");1785EmitNullInitialization(StatePtr, StateTy);17861787// Number of elements in the items array.1788static const unsigned NumItems = 16;17891790// Fetch the countByEnumeratingWithState:objects:count: selector.1791const IdentifierInfo *II[] = {1792&CGM.getContext().Idents.get("countByEnumeratingWithState"),1793&CGM.getContext().Idents.get("objects"),1794&CGM.getContext().Idents.get("count")};1795Selector FastEnumSel =1796CGM.getContext().Selectors.getSelector(std::size(II), &II[0]);17971798QualType ItemsTy = getContext().getConstantArrayType(1799getContext().getObjCIdType(), llvm::APInt(32, NumItems), nullptr,1800ArraySizeModifier::Normal, 0);1801Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");18021803// Emit the collection pointer. In ARC, we do a retain.1804llvm::Value *Collection;1805if (getLangOpts().ObjCAutoRefCount) {1806Collection = EmitARCRetainScalarExpr(S.getCollection());18071808// Enter a cleanup to do the release.1809EmitObjCConsumeObject(S.getCollection()->getType(), Collection);1810} else {1811Collection = EmitScalarExpr(S.getCollection());1812}18131814// The 'continue' label needs to appear within the cleanup for the1815// collection object.1816JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");18171818// Send it our message:1819CallArgList Args;18201821// The first argument is a temporary of the enumeration-state type.1822Args.add(RValue::get(StatePtr, *this), getContext().getPointerType(StateTy));18231824// The second argument is a temporary array with space for NumItems1825// pointers. We'll actually be loading elements from the array1826// pointer written into the control state; this buffer is so that1827// collections that *aren't* backed by arrays can still queue up1828// batches of elements.1829Args.add(RValue::get(ItemsPtr, *this), getContext().getPointerType(ItemsTy));18301831// The third argument is the capacity of that temporary array.1832llvm::Type *NSUIntegerTy = ConvertType(getContext().getNSUIntegerType());1833llvm::Constant *Count = llvm::ConstantInt::get(NSUIntegerTy, NumItems);1834Args.add(RValue::get(Count), getContext().getNSUIntegerType());18351836// Start the enumeration.1837RValue CountRV =1838CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),1839getContext().getNSUIntegerType(),1840FastEnumSel, Collection, Args);18411842// The initial number of objects that were returned in the buffer.1843llvm::Value *initialBufferLimit = CountRV.getScalarVal();18441845llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");1846llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");18471848llvm::Value *zero = llvm::Constant::getNullValue(NSUIntegerTy);18491850// If the limit pointer was zero to begin with, the collection is1851// empty; skip all this. Set the branch weight assuming this has the same1852// probability of exiting the loop as any other loop exit.1853uint64_t EntryCount = getCurrentProfileCount();1854Builder.CreateCondBr(1855Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,1856LoopInitBB,1857createProfileWeights(EntryCount, getProfileCount(S.getBody())));18581859// Otherwise, initialize the loop.1860EmitBlock(LoopInitBB);18611862// Save the initial mutations value. This is the value at an1863// address that was written into the state object by1864// countByEnumeratingWithState:objects:count:.1865Address StateMutationsPtrPtr =1866Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");1867llvm::Value *StateMutationsPtr1868= Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");18691870llvm::Type *UnsignedLongTy = ConvertType(getContext().UnsignedLongTy);1871llvm::Value *initialMutations =1872Builder.CreateAlignedLoad(UnsignedLongTy, StateMutationsPtr,1873getPointerAlign(), "forcoll.initial-mutations");18741875// Start looping. This is the point we return to whenever we have a1876// fresh, non-empty batch of objects.1877llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");1878EmitBlock(LoopBodyBB);18791880// The current index into the buffer.1881llvm::PHINode *index = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.index");1882index->addIncoming(zero, LoopInitBB);18831884// The current buffer size.1885llvm::PHINode *count = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.count");1886count->addIncoming(initialBufferLimit, LoopInitBB);18871888incrementProfileCounter(&S);18891890// Check whether the mutations value has changed from where it was1891// at start. StateMutationsPtr should actually be invariant between1892// refreshes.1893StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");1894llvm::Value *currentMutations1895= Builder.CreateAlignedLoad(UnsignedLongTy, StateMutationsPtr,1896getPointerAlign(), "statemutations");18971898llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");1899llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");19001901Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),1902WasNotMutatedBB, WasMutatedBB);19031904// If so, call the enumeration-mutation function.1905EmitBlock(WasMutatedBB);1906llvm::Type *ObjCIdType = ConvertType(getContext().getObjCIdType());1907llvm::Value *V =1908Builder.CreateBitCast(Collection, ObjCIdType);1909CallArgList Args2;1910Args2.add(RValue::get(V), getContext().getObjCIdType());1911// FIXME: We shouldn't need to get the function info here, the runtime already1912// should have computed it to build the function.1913EmitCall(1914CGM.getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, Args2),1915EnumerationMutationFn, ReturnValueSlot(), Args2);19161917// Otherwise, or if the mutation function returns, just continue.1918EmitBlock(WasNotMutatedBB);19191920// Initialize the element variable.1921RunCleanupsScope elementVariableScope(*this);1922bool elementIsVariable;1923LValue elementLValue;1924QualType elementType;1925if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {1926// Initialize the variable, in case it's a __block variable or something.1927EmitAutoVarInit(variable);19281929const VarDecl *D = cast<VarDecl>(SD->getSingleDecl());1930DeclRefExpr tempDRE(getContext(), const_cast<VarDecl *>(D), false,1931D->getType(), VK_LValue, SourceLocation());1932elementLValue = EmitLValue(&tempDRE);1933elementType = D->getType();1934elementIsVariable = true;19351936if (D->isARCPseudoStrong())1937elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);1938} else {1939elementLValue = LValue(); // suppress warning1940elementType = cast<Expr>(S.getElement())->getType();1941elementIsVariable = false;1942}1943llvm::Type *convertedElementType = ConvertType(elementType);19441945// Fetch the buffer out of the enumeration state.1946// TODO: this pointer should actually be invariant between1947// refreshes, which would help us do certain loop optimizations.1948Address StateItemsPtr =1949Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");1950llvm::Value *EnumStateItems =1951Builder.CreateLoad(StateItemsPtr, "stateitems");19521953// Fetch the value at the current index from the buffer.1954llvm::Value *CurrentItemPtr = Builder.CreateInBoundsGEP(1955ObjCIdType, EnumStateItems, index, "currentitem.ptr");1956llvm::Value *CurrentItem =1957Builder.CreateAlignedLoad(ObjCIdType, CurrentItemPtr, getPointerAlign());19581959if (SanOpts.has(SanitizerKind::ObjCCast)) {1960// Before using an item from the collection, check that the implicit cast1961// from id to the element type is valid. This is done with instrumentation1962// roughly corresponding to:1963//1964// if (![item isKindOfClass:expectedCls]) { /* emit diagnostic */ }1965const ObjCObjectPointerType *ObjPtrTy =1966elementType->getAsObjCInterfacePointerType();1967const ObjCInterfaceType *InterfaceTy =1968ObjPtrTy ? ObjPtrTy->getInterfaceType() : nullptr;1969if (InterfaceTy) {1970SanitizerScope SanScope(this);1971auto &C = CGM.getContext();1972assert(InterfaceTy->getDecl() && "No decl for ObjC interface type");1973Selector IsKindOfClassSel = GetUnarySelector("isKindOfClass", C);1974CallArgList IsKindOfClassArgs;1975llvm::Value *Cls =1976CGM.getObjCRuntime().GetClass(*this, InterfaceTy->getDecl());1977IsKindOfClassArgs.add(RValue::get(Cls), C.getObjCClassType());1978llvm::Value *IsClass =1979CGM.getObjCRuntime()1980.GenerateMessageSend(*this, ReturnValueSlot(), C.BoolTy,1981IsKindOfClassSel, CurrentItem,1982IsKindOfClassArgs)1983.getScalarVal();1984llvm::Constant *StaticData[] = {1985EmitCheckSourceLocation(S.getBeginLoc()),1986EmitCheckTypeDescriptor(QualType(InterfaceTy, 0))};1987EmitCheck({{IsClass, SanitizerKind::ObjCCast}},1988SanitizerHandler::InvalidObjCCast,1989ArrayRef<llvm::Constant *>(StaticData), CurrentItem);1990}1991}19921993// Cast that value to the right type.1994CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,1995"currentitem");19961997// Make sure we have an l-value. Yes, this gets evaluated every1998// time through the loop.1999if (!elementIsVariable) {2000elementLValue = EmitLValue(cast<Expr>(S.getElement()));2001EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);2002} else {2003EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue,2004/*isInit*/ true);2005}20062007// If we do have an element variable, this assignment is the end of2008// its initialization.2009if (elementIsVariable)2010EmitAutoVarCleanups(variable);20112012// Perform the loop body, setting up break and continue labels.2013BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));2014{2015RunCleanupsScope Scope(*this);2016EmitStmt(S.getBody());2017}2018BreakContinueStack.pop_back();20192020// Destroy the element variable now.2021elementVariableScope.ForceCleanup();20222023// Check whether there are more elements.2024EmitBlock(AfterBody.getBlock());20252026llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");20272028// First we check in the local buffer.2029llvm::Value *indexPlusOne =2030Builder.CreateNUWAdd(index, llvm::ConstantInt::get(NSUIntegerTy, 1));20312032// If we haven't overrun the buffer yet, we can continue.2033// Set the branch weights based on the simplifying assumption that this is2034// like a while-loop, i.e., ignoring that the false branch fetches more2035// elements and then returns to the loop.2036Builder.CreateCondBr(2037Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,2038createProfileWeights(getProfileCount(S.getBody()), EntryCount));20392040index->addIncoming(indexPlusOne, AfterBody.getBlock());2041count->addIncoming(count, AfterBody.getBlock());20422043// Otherwise, we have to fetch more elements.2044EmitBlock(FetchMoreBB);20452046CountRV =2047CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),2048getContext().getNSUIntegerType(),2049FastEnumSel, Collection, Args);20502051// If we got a zero count, we're done.2052llvm::Value *refetchCount = CountRV.getScalarVal();20532054// (note that the message send might split FetchMoreBB)2055index->addIncoming(zero, Builder.GetInsertBlock());2056count->addIncoming(refetchCount, Builder.GetInsertBlock());20572058Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),2059EmptyBB, LoopBodyBB);20602061// No more elements.2062EmitBlock(EmptyBB);20632064if (!elementIsVariable) {2065// If the element was not a declaration, set it to be null.20662067llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);2068elementLValue = EmitLValue(cast<Expr>(S.getElement()));2069EmitStoreThroughLValue(RValue::get(null), elementLValue);2070}20712072if (DI)2073DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());20742075ForScope.ForceCleanup();2076EmitBlock(LoopEnd.getBlock());2077}20782079void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {2080CGM.getObjCRuntime().EmitTryStmt(*this, S);2081}20822083void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {2084CGM.getObjCRuntime().EmitThrowStmt(*this, S);2085}20862087void CodeGenFunction::EmitObjCAtSynchronizedStmt(2088const ObjCAtSynchronizedStmt &S) {2089CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);2090}20912092namespace {2093struct CallObjCRelease final : EHScopeStack::Cleanup {2094CallObjCRelease(llvm::Value *object) : object(object) {}2095llvm::Value *object;20962097void Emit(CodeGenFunction &CGF, Flags flags) override {2098// Releases at the end of the full-expression are imprecise.2099CGF.EmitARCRelease(object, ARCImpreciseLifetime);2100}2101};2102}21032104/// Produce the code for a CK_ARCConsumeObject. Does a primitive2105/// release at the end of the full-expression.2106llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,2107llvm::Value *object) {2108// If we're in a conditional branch, we need to make the cleanup2109// conditional.2110pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);2111return object;2112}21132114llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,2115llvm::Value *value) {2116return EmitARCRetainAutorelease(type, value);2117}21182119/// Given a number of pointers, inform the optimizer that they're2120/// being intrinsically used up until this point in the program.2121void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {2122llvm::Function *&fn = CGM.getObjCEntrypoints().clang_arc_use;2123if (!fn)2124fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_use);21252126// This isn't really a "runtime" function, but as an intrinsic it2127// doesn't really matter as long as we align things up.2128EmitNounwindRuntimeCall(fn, values);2129}21302131/// Emit a call to "clang.arc.noop.use", which consumes the result of a call2132/// that has operand bundle "clang.arc.attachedcall".2133void CodeGenFunction::EmitARCNoopIntrinsicUse(ArrayRef<llvm::Value *> values) {2134llvm::Function *&fn = CGM.getObjCEntrypoints().clang_arc_noop_use;2135if (!fn)2136fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_noop_use);2137EmitNounwindRuntimeCall(fn, values);2138}21392140static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM, llvm::Value *RTF) {2141if (auto *F = dyn_cast<llvm::Function>(RTF)) {2142// If the target runtime doesn't naturally support ARC, emit weak2143// references to the runtime support library. We don't really2144// permit this to fail, but we need a particular relocation style.2145if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC() &&2146!CGM.getTriple().isOSBinFormatCOFF()) {2147F->setLinkage(llvm::Function::ExternalWeakLinkage);2148}2149}2150}21512152static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM,2153llvm::FunctionCallee RTF) {2154setARCRuntimeFunctionLinkage(CGM, RTF.getCallee());2155}21562157static llvm::Function *getARCIntrinsic(llvm::Intrinsic::ID IntID,2158CodeGenModule &CGM) {2159llvm::Function *fn = CGM.getIntrinsic(IntID);2160setARCRuntimeFunctionLinkage(CGM, fn);2161return fn;2162}21632164/// Perform an operation having the signature2165/// i8* (i8*)2166/// where a null input causes a no-op and returns null.2167static llvm::Value *emitARCValueOperation(2168CodeGenFunction &CGF, llvm::Value *value, llvm::Type *returnType,2169llvm::Function *&fn, llvm::Intrinsic::ID IntID,2170llvm::CallInst::TailCallKind tailKind = llvm::CallInst::TCK_None) {2171if (isa<llvm::ConstantPointerNull>(value))2172return value;21732174if (!fn)2175fn = getARCIntrinsic(IntID, CGF.CGM);21762177// Cast the argument to 'id'.2178llvm::Type *origType = returnType ? returnType : value->getType();2179value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);21802181// Call the function.2182llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);2183call->setTailCallKind(tailKind);21842185// Cast the result back to the original type.2186return CGF.Builder.CreateBitCast(call, origType);2187}21882189/// Perform an operation having the following signature:2190/// i8* (i8**)2191static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF, Address addr,2192llvm::Function *&fn,2193llvm::Intrinsic::ID IntID) {2194if (!fn)2195fn = getARCIntrinsic(IntID, CGF.CGM);21962197return CGF.EmitNounwindRuntimeCall(fn, addr.emitRawPointer(CGF));2198}21992200/// Perform an operation having the following signature:2201/// i8* (i8**, i8*)2202static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF, Address addr,2203llvm::Value *value,2204llvm::Function *&fn,2205llvm::Intrinsic::ID IntID,2206bool ignored) {2207assert(addr.getElementType() == value->getType());22082209if (!fn)2210fn = getARCIntrinsic(IntID, CGF.CGM);22112212llvm::Type *origType = value->getType();22132214llvm::Value *args[] = {2215CGF.Builder.CreateBitCast(addr.emitRawPointer(CGF), CGF.Int8PtrPtrTy),2216CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)};2217llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);22182219if (ignored) return nullptr;22202221return CGF.Builder.CreateBitCast(result, origType);2222}22232224/// Perform an operation having the following signature:2225/// void (i8**, i8**)2226static void emitARCCopyOperation(CodeGenFunction &CGF, Address dst, Address src,2227llvm::Function *&fn,2228llvm::Intrinsic::ID IntID) {2229assert(dst.getType() == src.getType());22302231if (!fn)2232fn = getARCIntrinsic(IntID, CGF.CGM);22332234llvm::Value *args[] = {2235CGF.Builder.CreateBitCast(dst.emitRawPointer(CGF), CGF.Int8PtrPtrTy),2236CGF.Builder.CreateBitCast(src.emitRawPointer(CGF), CGF.Int8PtrPtrTy)};2237CGF.EmitNounwindRuntimeCall(fn, args);2238}22392240/// Perform an operation having the signature2241/// i8* (i8*)2242/// where a null input causes a no-op and returns null.2243static llvm::Value *emitObjCValueOperation(CodeGenFunction &CGF,2244llvm::Value *value,2245llvm::Type *returnType,2246llvm::FunctionCallee &fn,2247StringRef fnName) {2248if (isa<llvm::ConstantPointerNull>(value))2249return value;22502251if (!fn) {2252llvm::FunctionType *fnType =2253llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);2254fn = CGF.CGM.CreateRuntimeFunction(fnType, fnName);22552256// We have Native ARC, so set nonlazybind attribute for performance2257if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))2258if (fnName == "objc_retain")2259f->addFnAttr(llvm::Attribute::NonLazyBind);2260}22612262// Cast the argument to 'id'.2263llvm::Type *origType = returnType ? returnType : value->getType();2264value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);22652266// Call the function.2267llvm::CallBase *Inst = CGF.EmitCallOrInvoke(fn, value);22682269// Mark calls to objc_autorelease as tail on the assumption that methods2270// overriding autorelease do not touch anything on the stack.2271if (fnName == "objc_autorelease")2272if (auto *Call = dyn_cast<llvm::CallInst>(Inst))2273Call->setTailCall();22742275// Cast the result back to the original type.2276return CGF.Builder.CreateBitCast(Inst, origType);2277}22782279/// Produce the code to do a retain. Based on the type, calls one of:2280/// call i8* \@objc_retain(i8* %value)2281/// call i8* \@objc_retainBlock(i8* %value)2282llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {2283if (type->isBlockPointerType())2284return EmitARCRetainBlock(value, /*mandatory*/ false);2285else2286return EmitARCRetainNonBlock(value);2287}22882289/// Retain the given object, with normal retain semantics.2290/// call i8* \@objc_retain(i8* %value)2291llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {2292return emitARCValueOperation(*this, value, nullptr,2293CGM.getObjCEntrypoints().objc_retain,2294llvm::Intrinsic::objc_retain);2295}22962297/// Retain the given block, with _Block_copy semantics.2298/// call i8* \@objc_retainBlock(i8* %value)2299///2300/// \param mandatory - If false, emit the call with metadata2301/// indicating that it's okay for the optimizer to eliminate this call2302/// if it can prove that the block never escapes except down the stack.2303llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,2304bool mandatory) {2305llvm::Value *result2306= emitARCValueOperation(*this, value, nullptr,2307CGM.getObjCEntrypoints().objc_retainBlock,2308llvm::Intrinsic::objc_retainBlock);23092310// If the copy isn't mandatory, add !clang.arc.copy_on_escape to2311// tell the optimizer that it doesn't need to do this copy if the2312// block doesn't escape, where being passed as an argument doesn't2313// count as escaping.2314if (!mandatory && isa<llvm::Instruction>(result)) {2315llvm::CallInst *call2316= cast<llvm::CallInst>(result->stripPointerCasts());2317assert(call->getCalledOperand() ==2318CGM.getObjCEntrypoints().objc_retainBlock);23192320call->setMetadata("clang.arc.copy_on_escape",2321llvm::MDNode::get(Builder.getContext(), std::nullopt));2322}23232324return result;2325}23262327static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF) {2328// Fetch the void(void) inline asm which marks that we're going to2329// do something with the autoreleased return value.2330llvm::InlineAsm *&marker2331= CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker;2332if (!marker) {2333StringRef assembly2334= CGF.CGM.getTargetCodeGenInfo()2335.getARCRetainAutoreleasedReturnValueMarker();23362337// If we have an empty assembly string, there's nothing to do.2338if (assembly.empty()) {23392340// Otherwise, at -O0, build an inline asm that we're going to call2341// in a moment.2342} else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {2343llvm::FunctionType *type =2344llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false);23452346marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);23472348// If we're at -O1 and above, we don't want to litter the code2349// with this marker yet, so leave a breadcrumb for the ARC2350// optimizer to pick up.2351} else {2352const char *retainRVMarkerKey = llvm::objcarc::getRVMarkerModuleFlagStr();2353if (!CGF.CGM.getModule().getModuleFlag(retainRVMarkerKey)) {2354auto *str = llvm::MDString::get(CGF.getLLVMContext(), assembly);2355CGF.CGM.getModule().addModuleFlag(llvm::Module::Error,2356retainRVMarkerKey, str);2357}2358}2359}23602361// Call the marker asm if we made one, which we do only at -O0.2362if (marker)2363CGF.Builder.CreateCall(marker, std::nullopt,2364CGF.getBundlesForFunclet(marker));2365}23662367static llvm::Value *emitOptimizedARCReturnCall(llvm::Value *value,2368bool IsRetainRV,2369CodeGenFunction &CGF) {2370emitAutoreleasedReturnValueMarker(CGF);23712372// Add operand bundle "clang.arc.attachedcall" to the call instead of emitting2373// retainRV or claimRV calls in the IR. We currently do this only when the2374// optimization level isn't -O0 since global-isel, which is currently run at2375// -O0, doesn't know about the operand bundle.2376ObjCEntrypoints &EPs = CGF.CGM.getObjCEntrypoints();2377llvm::Function *&EP = IsRetainRV2378? EPs.objc_retainAutoreleasedReturnValue2379: EPs.objc_unsafeClaimAutoreleasedReturnValue;2380llvm::Intrinsic::ID IID =2381IsRetainRV ? llvm::Intrinsic::objc_retainAutoreleasedReturnValue2382: llvm::Intrinsic::objc_unsafeClaimAutoreleasedReturnValue;2383EP = getARCIntrinsic(IID, CGF.CGM);23842385llvm::Triple::ArchType Arch = CGF.CGM.getTriple().getArch();23862387// FIXME: Do this on all targets and at -O0 too. This can be enabled only if2388// the target backend knows how to handle the operand bundle.2389if (CGF.CGM.getCodeGenOpts().OptimizationLevel > 0 &&2390(Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::x86_64)) {2391llvm::Value *bundleArgs[] = {EP};2392llvm::OperandBundleDef OB("clang.arc.attachedcall", bundleArgs);2393auto *oldCall = cast<llvm::CallBase>(value);2394llvm::CallBase *newCall = llvm::CallBase::addOperandBundle(2395oldCall, llvm::LLVMContext::OB_clang_arc_attachedcall, OB, oldCall);2396newCall->copyMetadata(*oldCall);2397oldCall->replaceAllUsesWith(newCall);2398oldCall->eraseFromParent();2399CGF.EmitARCNoopIntrinsicUse(newCall);2400return newCall;2401}24022403bool isNoTail =2404CGF.CGM.getTargetCodeGenInfo().markARCOptimizedReturnCallsAsNoTail();2405llvm::CallInst::TailCallKind tailKind =2406isNoTail ? llvm::CallInst::TCK_NoTail : llvm::CallInst::TCK_None;2407return emitARCValueOperation(CGF, value, nullptr, EP, IID, tailKind);2408}24092410/// Retain the given object which is the result of a function call.2411/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)2412///2413/// Yes, this function name is one character away from a different2414/// call with completely different semantics.2415llvm::Value *2416CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {2417return emitOptimizedARCReturnCall(value, true, *this);2418}24192420/// Claim a possibly-autoreleased return value at +0. This is only2421/// valid to do in contexts which do not rely on the retain to keep2422/// the object valid for all of its uses; for example, when2423/// the value is ignored, or when it is being assigned to an2424/// __unsafe_unretained variable.2425///2426/// call i8* \@objc_unsafeClaimAutoreleasedReturnValue(i8* %value)2427llvm::Value *2428CodeGenFunction::EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value) {2429return emitOptimizedARCReturnCall(value, false, *this);2430}24312432/// Release the given object.2433/// call void \@objc_release(i8* %value)2434void CodeGenFunction::EmitARCRelease(llvm::Value *value,2435ARCPreciseLifetime_t precise) {2436if (isa<llvm::ConstantPointerNull>(value)) return;24372438llvm::Function *&fn = CGM.getObjCEntrypoints().objc_release;2439if (!fn)2440fn = getARCIntrinsic(llvm::Intrinsic::objc_release, CGM);24412442// Cast the argument to 'id'.2443value = Builder.CreateBitCast(value, Int8PtrTy);24442445// Call objc_release.2446llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);24472448if (precise == ARCImpreciseLifetime) {2449call->setMetadata("clang.imprecise_release",2450llvm::MDNode::get(Builder.getContext(), std::nullopt));2451}2452}24532454/// Destroy a __strong variable.2455///2456/// At -O0, emit a call to store 'null' into the address;2457/// instrumenting tools prefer this because the address is exposed,2458/// but it's relatively cumbersome to optimize.2459///2460/// At -O1 and above, just load and call objc_release.2461///2462/// call void \@objc_storeStrong(i8** %addr, i8* null)2463void CodeGenFunction::EmitARCDestroyStrong(Address addr,2464ARCPreciseLifetime_t precise) {2465if (CGM.getCodeGenOpts().OptimizationLevel == 0) {2466llvm::Value *null = getNullForVariable(addr);2467EmitARCStoreStrongCall(addr, null, /*ignored*/ true);2468return;2469}24702471llvm::Value *value = Builder.CreateLoad(addr);2472EmitARCRelease(value, precise);2473}24742475/// Store into a strong object. Always calls this:2476/// call void \@objc_storeStrong(i8** %addr, i8* %value)2477llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(Address addr,2478llvm::Value *value,2479bool ignored) {2480assert(addr.getElementType() == value->getType());24812482llvm::Function *&fn = CGM.getObjCEntrypoints().objc_storeStrong;2483if (!fn)2484fn = getARCIntrinsic(llvm::Intrinsic::objc_storeStrong, CGM);24852486llvm::Value *args[] = {2487Builder.CreateBitCast(addr.emitRawPointer(*this), Int8PtrPtrTy),2488Builder.CreateBitCast(value, Int8PtrTy)};2489EmitNounwindRuntimeCall(fn, args);24902491if (ignored) return nullptr;2492return value;2493}24942495/// Store into a strong object. Sometimes calls this:2496/// call void \@objc_storeStrong(i8** %addr, i8* %value)2497/// Other times, breaks it down into components.2498llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,2499llvm::Value *newValue,2500bool ignored) {2501QualType type = dst.getType();2502bool isBlock = type->isBlockPointerType();25032504// Use a store barrier at -O0 unless this is a block type or the2505// lvalue is inadequately aligned.2506if (shouldUseFusedARCCalls() &&2507!isBlock &&2508(dst.getAlignment().isZero() ||2509dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {2510return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);2511}25122513// Otherwise, split it out.25142515// Retain the new value.2516newValue = EmitARCRetain(type, newValue);25172518// Read the old value.2519llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());25202521// Store. We do this before the release so that any deallocs won't2522// see the old value.2523EmitStoreOfScalar(newValue, dst);25242525// Finally, release the old value.2526EmitARCRelease(oldValue, dst.isARCPreciseLifetime());25272528return newValue;2529}25302531/// Autorelease the given object.2532/// call i8* \@objc_autorelease(i8* %value)2533llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {2534return emitARCValueOperation(*this, value, nullptr,2535CGM.getObjCEntrypoints().objc_autorelease,2536llvm::Intrinsic::objc_autorelease);2537}25382539/// Autorelease the given object.2540/// call i8* \@objc_autoreleaseReturnValue(i8* %value)2541llvm::Value *2542CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {2543return emitARCValueOperation(*this, value, nullptr,2544CGM.getObjCEntrypoints().objc_autoreleaseReturnValue,2545llvm::Intrinsic::objc_autoreleaseReturnValue,2546llvm::CallInst::TCK_Tail);2547}25482549/// Do a fused retain/autorelease of the given object.2550/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)2551llvm::Value *2552CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {2553return emitARCValueOperation(*this, value, nullptr,2554CGM.getObjCEntrypoints().objc_retainAutoreleaseReturnValue,2555llvm::Intrinsic::objc_retainAutoreleaseReturnValue,2556llvm::CallInst::TCK_Tail);2557}25582559/// Do a fused retain/autorelease of the given object.2560/// call i8* \@objc_retainAutorelease(i8* %value)2561/// or2562/// %retain = call i8* \@objc_retainBlock(i8* %value)2563/// call i8* \@objc_autorelease(i8* %retain)2564llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,2565llvm::Value *value) {2566if (!type->isBlockPointerType())2567return EmitARCRetainAutoreleaseNonBlock(value);25682569if (isa<llvm::ConstantPointerNull>(value)) return value;25702571llvm::Type *origType = value->getType();2572value = Builder.CreateBitCast(value, Int8PtrTy);2573value = EmitARCRetainBlock(value, /*mandatory*/ true);2574value = EmitARCAutorelease(value);2575return Builder.CreateBitCast(value, origType);2576}25772578/// Do a fused retain/autorelease of the given object.2579/// call i8* \@objc_retainAutorelease(i8* %value)2580llvm::Value *2581CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {2582return emitARCValueOperation(*this, value, nullptr,2583CGM.getObjCEntrypoints().objc_retainAutorelease,2584llvm::Intrinsic::objc_retainAutorelease);2585}25862587/// i8* \@objc_loadWeak(i8** %addr)2588/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).2589llvm::Value *CodeGenFunction::EmitARCLoadWeak(Address addr) {2590return emitARCLoadOperation(*this, addr,2591CGM.getObjCEntrypoints().objc_loadWeak,2592llvm::Intrinsic::objc_loadWeak);2593}25942595/// i8* \@objc_loadWeakRetained(i8** %addr)2596llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(Address addr) {2597return emitARCLoadOperation(*this, addr,2598CGM.getObjCEntrypoints().objc_loadWeakRetained,2599llvm::Intrinsic::objc_loadWeakRetained);2600}26012602/// i8* \@objc_storeWeak(i8** %addr, i8* %value)2603/// Returns %value.2604llvm::Value *CodeGenFunction::EmitARCStoreWeak(Address addr,2605llvm::Value *value,2606bool ignored) {2607return emitARCStoreOperation(*this, addr, value,2608CGM.getObjCEntrypoints().objc_storeWeak,2609llvm::Intrinsic::objc_storeWeak, ignored);2610}26112612/// i8* \@objc_initWeak(i8** %addr, i8* %value)2613/// Returns %value. %addr is known to not have a current weak entry.2614/// Essentially equivalent to:2615/// *addr = nil; objc_storeWeak(addr, value);2616void CodeGenFunction::EmitARCInitWeak(Address addr, llvm::Value *value) {2617// If we're initializing to null, just write null to memory; no need2618// to get the runtime involved. But don't do this if optimization2619// is enabled, because accounting for this would make the optimizer2620// much more complicated.2621if (isa<llvm::ConstantPointerNull>(value) &&2622CGM.getCodeGenOpts().OptimizationLevel == 0) {2623Builder.CreateStore(value, addr);2624return;2625}26262627emitARCStoreOperation(*this, addr, value,2628CGM.getObjCEntrypoints().objc_initWeak,2629llvm::Intrinsic::objc_initWeak, /*ignored*/ true);2630}26312632/// void \@objc_destroyWeak(i8** %addr)2633/// Essentially objc_storeWeak(addr, nil).2634void CodeGenFunction::EmitARCDestroyWeak(Address addr) {2635llvm::Function *&fn = CGM.getObjCEntrypoints().objc_destroyWeak;2636if (!fn)2637fn = getARCIntrinsic(llvm::Intrinsic::objc_destroyWeak, CGM);26382639EmitNounwindRuntimeCall(fn, addr.emitRawPointer(*this));2640}26412642/// void \@objc_moveWeak(i8** %dest, i8** %src)2643/// Disregards the current value in %dest. Leaves %src pointing to nothing.2644/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).2645void CodeGenFunction::EmitARCMoveWeak(Address dst, Address src) {2646emitARCCopyOperation(*this, dst, src,2647CGM.getObjCEntrypoints().objc_moveWeak,2648llvm::Intrinsic::objc_moveWeak);2649}26502651/// void \@objc_copyWeak(i8** %dest, i8** %src)2652/// Disregards the current value in %dest. Essentially2653/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))2654void CodeGenFunction::EmitARCCopyWeak(Address dst, Address src) {2655emitARCCopyOperation(*this, dst, src,2656CGM.getObjCEntrypoints().objc_copyWeak,2657llvm::Intrinsic::objc_copyWeak);2658}26592660void CodeGenFunction::emitARCCopyAssignWeak(QualType Ty, Address DstAddr,2661Address SrcAddr) {2662llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);2663Object = EmitObjCConsumeObject(Ty, Object);2664EmitARCStoreWeak(DstAddr, Object, false);2665}26662667void CodeGenFunction::emitARCMoveAssignWeak(QualType Ty, Address DstAddr,2668Address SrcAddr) {2669llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);2670Object = EmitObjCConsumeObject(Ty, Object);2671EmitARCStoreWeak(DstAddr, Object, false);2672EmitARCDestroyWeak(SrcAddr);2673}26742675/// Produce the code to do a objc_autoreleasepool_push.2676/// call i8* \@objc_autoreleasePoolPush(void)2677llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {2678llvm::Function *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPush;2679if (!fn)2680fn = getARCIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPush, CGM);26812682return EmitNounwindRuntimeCall(fn);2683}26842685/// Produce the code to do a primitive release.2686/// call void \@objc_autoreleasePoolPop(i8* %ptr)2687void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {2688assert(value->getType() == Int8PtrTy);26892690if (getInvokeDest()) {2691// Call the runtime method not the intrinsic if we are handling exceptions2692llvm::FunctionCallee &fn =2693CGM.getObjCEntrypoints().objc_autoreleasePoolPopInvoke;2694if (!fn) {2695llvm::FunctionType *fnType =2696llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);2697fn = CGM.CreateRuntimeFunction(fnType, "objc_autoreleasePoolPop");2698setARCRuntimeFunctionLinkage(CGM, fn);2699}27002701// objc_autoreleasePoolPop can throw.2702EmitRuntimeCallOrInvoke(fn, value);2703} else {2704llvm::FunctionCallee &fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPop;2705if (!fn)2706fn = getARCIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPop, CGM);27072708EmitRuntimeCall(fn, value);2709}2710}27112712/// Produce the code to do an MRR version objc_autoreleasepool_push.2713/// Which is: [[NSAutoreleasePool alloc] init];2714/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.2715/// init is declared as: - (id) init; in its NSObject super class.2716///2717llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {2718CGObjCRuntime &Runtime = CGM.getObjCRuntime();2719llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);2720// [NSAutoreleasePool alloc]2721const IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");2722Selector AllocSel = getContext().Selectors.getSelector(0, &II);2723CallArgList Args;2724RValue AllocRV =2725Runtime.GenerateMessageSend(*this, ReturnValueSlot(),2726getContext().getObjCIdType(),2727AllocSel, Receiver, Args);27282729// [Receiver init]2730Receiver = AllocRV.getScalarVal();2731II = &CGM.getContext().Idents.get("init");2732Selector InitSel = getContext().Selectors.getSelector(0, &II);2733RValue InitRV =2734Runtime.GenerateMessageSend(*this, ReturnValueSlot(),2735getContext().getObjCIdType(),2736InitSel, Receiver, Args);2737return InitRV.getScalarVal();2738}27392740/// Allocate the given objc object.2741/// call i8* \@objc_alloc(i8* %value)2742llvm::Value *CodeGenFunction::EmitObjCAlloc(llvm::Value *value,2743llvm::Type *resultType) {2744return emitObjCValueOperation(*this, value, resultType,2745CGM.getObjCEntrypoints().objc_alloc,2746"objc_alloc");2747}27482749/// Allocate the given objc object.2750/// call i8* \@objc_allocWithZone(i8* %value)2751llvm::Value *CodeGenFunction::EmitObjCAllocWithZone(llvm::Value *value,2752llvm::Type *resultType) {2753return emitObjCValueOperation(*this, value, resultType,2754CGM.getObjCEntrypoints().objc_allocWithZone,2755"objc_allocWithZone");2756}27572758llvm::Value *CodeGenFunction::EmitObjCAllocInit(llvm::Value *value,2759llvm::Type *resultType) {2760return emitObjCValueOperation(*this, value, resultType,2761CGM.getObjCEntrypoints().objc_alloc_init,2762"objc_alloc_init");2763}27642765/// Produce the code to do a primitive release.2766/// [tmp drain];2767void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {2768const IdentifierInfo *II = &CGM.getContext().Idents.get("drain");2769Selector DrainSel = getContext().Selectors.getSelector(0, &II);2770CallArgList Args;2771CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),2772getContext().VoidTy, DrainSel, Arg, Args);2773}27742775void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,2776Address addr,2777QualType type) {2778CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);2779}27802781void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,2782Address addr,2783QualType type) {2784CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);2785}27862787void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,2788Address addr,2789QualType type) {2790CGF.EmitARCDestroyWeak(addr);2791}27922793void CodeGenFunction::emitARCIntrinsicUse(CodeGenFunction &CGF, Address addr,2794QualType type) {2795llvm::Value *value = CGF.Builder.CreateLoad(addr);2796CGF.EmitARCIntrinsicUse(value);2797}27982799/// Autorelease the given object.2800/// call i8* \@objc_autorelease(i8* %value)2801llvm::Value *CodeGenFunction::EmitObjCAutorelease(llvm::Value *value,2802llvm::Type *returnType) {2803return emitObjCValueOperation(2804*this, value, returnType,2805CGM.getObjCEntrypoints().objc_autoreleaseRuntimeFunction,2806"objc_autorelease");2807}28082809/// Retain the given object, with normal retain semantics.2810/// call i8* \@objc_retain(i8* %value)2811llvm::Value *CodeGenFunction::EmitObjCRetainNonBlock(llvm::Value *value,2812llvm::Type *returnType) {2813return emitObjCValueOperation(2814*this, value, returnType,2815CGM.getObjCEntrypoints().objc_retainRuntimeFunction, "objc_retain");2816}28172818/// Release the given object.2819/// call void \@objc_release(i8* %value)2820void CodeGenFunction::EmitObjCRelease(llvm::Value *value,2821ARCPreciseLifetime_t precise) {2822if (isa<llvm::ConstantPointerNull>(value)) return;28232824llvm::FunctionCallee &fn =2825CGM.getObjCEntrypoints().objc_releaseRuntimeFunction;2826if (!fn) {2827llvm::FunctionType *fnType =2828llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);2829fn = CGM.CreateRuntimeFunction(fnType, "objc_release");2830setARCRuntimeFunctionLinkage(CGM, fn);2831// We have Native ARC, so set nonlazybind attribute for performance2832if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))2833f->addFnAttr(llvm::Attribute::NonLazyBind);2834}28352836// Cast the argument to 'id'.2837value = Builder.CreateBitCast(value, Int8PtrTy);28382839// Call objc_release.2840llvm::CallBase *call = EmitCallOrInvoke(fn, value);28412842if (precise == ARCImpreciseLifetime) {2843call->setMetadata("clang.imprecise_release",2844llvm::MDNode::get(Builder.getContext(), std::nullopt));2845}2846}28472848namespace {2849struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {2850llvm::Value *Token;28512852CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}28532854void Emit(CodeGenFunction &CGF, Flags flags) override {2855CGF.EmitObjCAutoreleasePoolPop(Token);2856}2857};2858struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {2859llvm::Value *Token;28602861CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}28622863void Emit(CodeGenFunction &CGF, Flags flags) override {2864CGF.EmitObjCMRRAutoreleasePoolPop(Token);2865}2866};2867}28682869void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {2870if (CGM.getLangOpts().ObjCAutoRefCount)2871EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);2872else2873EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);2874}28752876static bool shouldRetainObjCLifetime(Qualifiers::ObjCLifetime lifetime) {2877switch (lifetime) {2878case Qualifiers::OCL_None:2879case Qualifiers::OCL_ExplicitNone:2880case Qualifiers::OCL_Strong:2881case Qualifiers::OCL_Autoreleasing:2882return true;28832884case Qualifiers::OCL_Weak:2885return false;2886}28872888llvm_unreachable("impossible lifetime!");2889}28902891static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,2892LValue lvalue,2893QualType type) {2894llvm::Value *result;2895bool shouldRetain = shouldRetainObjCLifetime(type.getObjCLifetime());2896if (shouldRetain) {2897result = CGF.EmitLoadOfLValue(lvalue, SourceLocation()).getScalarVal();2898} else {2899assert(type.getObjCLifetime() == Qualifiers::OCL_Weak);2900result = CGF.EmitARCLoadWeakRetained(lvalue.getAddress());2901}2902return TryEmitResult(result, !shouldRetain);2903}29042905static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,2906const Expr *e) {2907e = e->IgnoreParens();2908QualType type = e->getType();29092910// If we're loading retained from a __strong xvalue, we can avoid2911// an extra retain/release pair by zeroing out the source of this2912// "move" operation.2913if (e->isXValue() &&2914!type.isConstQualified() &&2915type.getObjCLifetime() == Qualifiers::OCL_Strong) {2916// Emit the lvalue.2917LValue lv = CGF.EmitLValue(e);29182919// Load the object pointer.2920llvm::Value *result = CGF.EmitLoadOfLValue(lv,2921SourceLocation()).getScalarVal();29222923// Set the source pointer to NULL.2924CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);29252926return TryEmitResult(result, true);2927}29282929// As a very special optimization, in ARC++, if the l-value is the2930// result of a non-volatile assignment, do a simple retain of the2931// result of the call to objc_storeWeak instead of reloading.2932if (CGF.getLangOpts().CPlusPlus &&2933!type.isVolatileQualified() &&2934type.getObjCLifetime() == Qualifiers::OCL_Weak &&2935isa<BinaryOperator>(e) &&2936cast<BinaryOperator>(e)->getOpcode() == BO_Assign)2937return TryEmitResult(CGF.EmitScalarExpr(e), false);29382939// Try to emit code for scalar constant instead of emitting LValue and2940// loading it because we are not guaranteed to have an l-value. One of such2941// cases is DeclRefExpr referencing non-odr-used constant-evaluated variable.2942if (const auto *decl_expr = dyn_cast<DeclRefExpr>(e)) {2943auto *DRE = const_cast<DeclRefExpr *>(decl_expr);2944if (CodeGenFunction::ConstantEmission constant = CGF.tryEmitAsConstant(DRE))2945return TryEmitResult(CGF.emitScalarConstant(constant, DRE),2946!shouldRetainObjCLifetime(type.getObjCLifetime()));2947}29482949return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);2950}29512952typedef llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,2953llvm::Value *value)>2954ValueTransform;29552956/// Insert code immediately after a call.29572958// FIXME: We should find a way to emit the runtime call immediately2959// after the call is emitted to eliminate the need for this function.2960static llvm::Value *emitARCOperationAfterCall(CodeGenFunction &CGF,2961llvm::Value *value,2962ValueTransform doAfterCall,2963ValueTransform doFallback) {2964CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();2965auto *callBase = dyn_cast<llvm::CallBase>(value);29662967if (callBase && llvm::objcarc::hasAttachedCallOpBundle(callBase)) {2968// Fall back if the call base has operand bundle "clang.arc.attachedcall".2969value = doFallback(CGF, value);2970} else if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {2971// Place the retain immediately following the call.2972CGF.Builder.SetInsertPoint(call->getParent(),2973++llvm::BasicBlock::iterator(call));2974value = doAfterCall(CGF, value);2975} else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {2976// Place the retain at the beginning of the normal destination block.2977llvm::BasicBlock *BB = invoke->getNormalDest();2978CGF.Builder.SetInsertPoint(BB, BB->begin());2979value = doAfterCall(CGF, value);29802981// Bitcasts can arise because of related-result returns. Rewrite2982// the operand.2983} else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {2984// Change the insert point to avoid emitting the fall-back call after the2985// bitcast.2986CGF.Builder.SetInsertPoint(bitcast->getParent(), bitcast->getIterator());2987llvm::Value *operand = bitcast->getOperand(0);2988operand = emitARCOperationAfterCall(CGF, operand, doAfterCall, doFallback);2989bitcast->setOperand(0, operand);2990value = bitcast;2991} else {2992auto *phi = dyn_cast<llvm::PHINode>(value);2993if (phi && phi->getNumIncomingValues() == 2 &&2994isa<llvm::ConstantPointerNull>(phi->getIncomingValue(1)) &&2995isa<llvm::CallBase>(phi->getIncomingValue(0))) {2996// Handle phi instructions that are generated when it's necessary to check2997// whether the receiver of a message is null.2998llvm::Value *inVal = phi->getIncomingValue(0);2999inVal = emitARCOperationAfterCall(CGF, inVal, doAfterCall, doFallback);3000phi->setIncomingValue(0, inVal);3001value = phi;3002} else {3003// Generic fall-back case.3004// Retain using the non-block variant: we never need to do a copy3005// of a block that's been returned to us.3006value = doFallback(CGF, value);3007}3008}30093010CGF.Builder.restoreIP(ip);3011return value;3012}30133014/// Given that the given expression is some sort of call (which does3015/// not return retained), emit a retain following it.3016static llvm::Value *emitARCRetainCallResult(CodeGenFunction &CGF,3017const Expr *e) {3018llvm::Value *value = CGF.EmitScalarExpr(e);3019return emitARCOperationAfterCall(CGF, value,3020[](CodeGenFunction &CGF, llvm::Value *value) {3021return CGF.EmitARCRetainAutoreleasedReturnValue(value);3022},3023[](CodeGenFunction &CGF, llvm::Value *value) {3024return CGF.EmitARCRetainNonBlock(value);3025});3026}30273028/// Given that the given expression is some sort of call (which does3029/// not return retained), perform an unsafeClaim following it.3030static llvm::Value *emitARCUnsafeClaimCallResult(CodeGenFunction &CGF,3031const Expr *e) {3032llvm::Value *value = CGF.EmitScalarExpr(e);3033return emitARCOperationAfterCall(CGF, value,3034[](CodeGenFunction &CGF, llvm::Value *value) {3035return CGF.EmitARCUnsafeClaimAutoreleasedReturnValue(value);3036},3037[](CodeGenFunction &CGF, llvm::Value *value) {3038return value;3039});3040}30413042llvm::Value *CodeGenFunction::EmitARCReclaimReturnedObject(const Expr *E,3043bool allowUnsafeClaim) {3044if (allowUnsafeClaim &&3045CGM.getLangOpts().ObjCRuntime.hasARCUnsafeClaimAutoreleasedReturnValue()) {3046return emitARCUnsafeClaimCallResult(*this, E);3047} else {3048llvm::Value *value = emitARCRetainCallResult(*this, E);3049return EmitObjCConsumeObject(E->getType(), value);3050}3051}30523053/// Determine whether it might be important to emit a separate3054/// objc_retain_block on the result of the given expression, or3055/// whether it's okay to just emit it in a +1 context.3056static bool shouldEmitSeparateBlockRetain(const Expr *e) {3057assert(e->getType()->isBlockPointerType());3058e = e->IgnoreParens();30593060// For future goodness, emit block expressions directly in +13061// contexts if we can.3062if (isa<BlockExpr>(e))3063return false;30643065if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {3066switch (cast->getCastKind()) {3067// Emitting these operations in +1 contexts is goodness.3068case CK_LValueToRValue:3069case CK_ARCReclaimReturnedObject:3070case CK_ARCConsumeObject:3071case CK_ARCProduceObject:3072return false;30733074// These operations preserve a block type.3075case CK_NoOp:3076case CK_BitCast:3077return shouldEmitSeparateBlockRetain(cast->getSubExpr());30783079// These operations are known to be bad (or haven't been considered).3080case CK_AnyPointerToBlockPointerCast:3081default:3082return true;3083}3084}30853086return true;3087}30883089namespace {3090/// A CRTP base class for emitting expressions of retainable object3091/// pointer type in ARC.3092template <typename Impl, typename Result> class ARCExprEmitter {3093protected:3094CodeGenFunction &CGF;3095Impl &asImpl() { return *static_cast<Impl*>(this); }30963097ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}30983099public:3100Result visit(const Expr *e);3101Result visitCastExpr(const CastExpr *e);3102Result visitPseudoObjectExpr(const PseudoObjectExpr *e);3103Result visitBlockExpr(const BlockExpr *e);3104Result visitBinaryOperator(const BinaryOperator *e);3105Result visitBinAssign(const BinaryOperator *e);3106Result visitBinAssignUnsafeUnretained(const BinaryOperator *e);3107Result visitBinAssignAutoreleasing(const BinaryOperator *e);3108Result visitBinAssignWeak(const BinaryOperator *e);3109Result visitBinAssignStrong(const BinaryOperator *e);31103111// Minimal implementation:3112// Result visitLValueToRValue(const Expr *e)3113// Result visitConsumeObject(const Expr *e)3114// Result visitExtendBlockObject(const Expr *e)3115// Result visitReclaimReturnedObject(const Expr *e)3116// Result visitCall(const Expr *e)3117// Result visitExpr(const Expr *e)3118//3119// Result emitBitCast(Result result, llvm::Type *resultType)3120// llvm::Value *getValueOfResult(Result result)3121};3122}31233124/// Try to emit a PseudoObjectExpr under special ARC rules.3125///3126/// This massively duplicates emitPseudoObjectRValue.3127template <typename Impl, typename Result>3128Result3129ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {3130SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;31313132// Find the result expression.3133const Expr *resultExpr = E->getResultExpr();3134assert(resultExpr);3135Result result;31363137for (PseudoObjectExpr::const_semantics_iterator3138i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {3139const Expr *semantic = *i;31403141// If this semantic expression is an opaque value, bind it3142// to the result of its source expression.3143if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {3144typedef CodeGenFunction::OpaqueValueMappingData OVMA;3145OVMA opaqueData;31463147// If this semantic is the result of the pseudo-object3148// expression, try to evaluate the source as +1.3149if (ov == resultExpr) {3150assert(!OVMA::shouldBindAsLValue(ov));3151result = asImpl().visit(ov->getSourceExpr());3152opaqueData = OVMA::bind(CGF, ov,3153RValue::get(asImpl().getValueOfResult(result)));31543155// Otherwise, just bind it.3156} else {3157opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());3158}3159opaques.push_back(opaqueData);31603161// Otherwise, if the expression is the result, evaluate it3162// and remember the result.3163} else if (semantic == resultExpr) {3164result = asImpl().visit(semantic);31653166// Otherwise, evaluate the expression in an ignored context.3167} else {3168CGF.EmitIgnoredExpr(semantic);3169}3170}31713172// Unbind all the opaques now.3173for (unsigned i = 0, e = opaques.size(); i != e; ++i)3174opaques[i].unbind(CGF);31753176return result;3177}31783179template <typename Impl, typename Result>3180Result ARCExprEmitter<Impl, Result>::visitBlockExpr(const BlockExpr *e) {3181// The default implementation just forwards the expression to visitExpr.3182return asImpl().visitExpr(e);3183}31843185template <typename Impl, typename Result>3186Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {3187switch (e->getCastKind()) {31883189// No-op casts don't change the type, so we just ignore them.3190case CK_NoOp:3191return asImpl().visit(e->getSubExpr());31923193// These casts can change the type.3194case CK_CPointerToObjCPointerCast:3195case CK_BlockPointerToObjCPointerCast:3196case CK_AnyPointerToBlockPointerCast:3197case CK_BitCast: {3198llvm::Type *resultType = CGF.ConvertType(e->getType());3199assert(e->getSubExpr()->getType()->hasPointerRepresentation());3200Result result = asImpl().visit(e->getSubExpr());3201return asImpl().emitBitCast(result, resultType);3202}32033204// Handle some casts specially.3205case CK_LValueToRValue:3206return asImpl().visitLValueToRValue(e->getSubExpr());3207case CK_ARCConsumeObject:3208return asImpl().visitConsumeObject(e->getSubExpr());3209case CK_ARCExtendBlockObject:3210return asImpl().visitExtendBlockObject(e->getSubExpr());3211case CK_ARCReclaimReturnedObject:3212return asImpl().visitReclaimReturnedObject(e->getSubExpr());32133214// Otherwise, use the default logic.3215default:3216return asImpl().visitExpr(e);3217}3218}32193220template <typename Impl, typename Result>3221Result3222ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {3223switch (e->getOpcode()) {3224case BO_Comma:3225CGF.EmitIgnoredExpr(e->getLHS());3226CGF.EnsureInsertPoint();3227return asImpl().visit(e->getRHS());32283229case BO_Assign:3230return asImpl().visitBinAssign(e);32313232default:3233return asImpl().visitExpr(e);3234}3235}32363237template <typename Impl, typename Result>3238Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {3239switch (e->getLHS()->getType().getObjCLifetime()) {3240case Qualifiers::OCL_ExplicitNone:3241return asImpl().visitBinAssignUnsafeUnretained(e);32423243case Qualifiers::OCL_Weak:3244return asImpl().visitBinAssignWeak(e);32453246case Qualifiers::OCL_Autoreleasing:3247return asImpl().visitBinAssignAutoreleasing(e);32483249case Qualifiers::OCL_Strong:3250return asImpl().visitBinAssignStrong(e);32513252case Qualifiers::OCL_None:3253return asImpl().visitExpr(e);3254}3255llvm_unreachable("bad ObjC ownership qualifier");3256}32573258/// The default rule for __unsafe_unretained emits the RHS recursively,3259/// stores into the unsafe variable, and propagates the result outward.3260template <typename Impl, typename Result>3261Result ARCExprEmitter<Impl,Result>::3262visitBinAssignUnsafeUnretained(const BinaryOperator *e) {3263// Recursively emit the RHS.3264// For __block safety, do this before emitting the LHS.3265Result result = asImpl().visit(e->getRHS());32663267// Perform the store.3268LValue lvalue =3269CGF.EmitCheckedLValue(e->getLHS(), CodeGenFunction::TCK_Store);3270CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),3271lvalue);32723273return result;3274}32753276template <typename Impl, typename Result>3277Result3278ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {3279return asImpl().visitExpr(e);3280}32813282template <typename Impl, typename Result>3283Result3284ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {3285return asImpl().visitExpr(e);3286}32873288template <typename Impl, typename Result>3289Result3290ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {3291return asImpl().visitExpr(e);3292}32933294/// The general expression-emission logic.3295template <typename Impl, typename Result>3296Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {3297// We should *never* see a nested full-expression here, because if3298// we fail to emit at +1, our caller must not retain after we close3299// out the full-expression. This isn't as important in the unsafe3300// emitter.3301assert(!isa<ExprWithCleanups>(e));33023303// Look through parens, __extension__, generic selection, etc.3304e = e->IgnoreParens();33053306// Handle certain kinds of casts.3307if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {3308return asImpl().visitCastExpr(ce);33093310// Handle the comma operator.3311} else if (auto op = dyn_cast<BinaryOperator>(e)) {3312return asImpl().visitBinaryOperator(op);33133314// TODO: handle conditional operators here33153316// For calls and message sends, use the retained-call logic.3317// Delegate inits are a special case in that they're the only3318// returns-retained expression that *isn't* surrounded by3319// a consume.3320} else if (isa<CallExpr>(e) ||3321(isa<ObjCMessageExpr>(e) &&3322!cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {3323return asImpl().visitCall(e);33243325// Look through pseudo-object expressions.3326} else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {3327return asImpl().visitPseudoObjectExpr(pseudo);3328} else if (auto *be = dyn_cast<BlockExpr>(e))3329return asImpl().visitBlockExpr(be);33303331return asImpl().visitExpr(e);3332}33333334namespace {33353336/// An emitter for +1 results.3337struct ARCRetainExprEmitter :3338public ARCExprEmitter<ARCRetainExprEmitter, TryEmitResult> {33393340ARCRetainExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}33413342llvm::Value *getValueOfResult(TryEmitResult result) {3343return result.getPointer();3344}33453346TryEmitResult emitBitCast(TryEmitResult result, llvm::Type *resultType) {3347llvm::Value *value = result.getPointer();3348value = CGF.Builder.CreateBitCast(value, resultType);3349result.setPointer(value);3350return result;3351}33523353TryEmitResult visitLValueToRValue(const Expr *e) {3354return tryEmitARCRetainLoadOfScalar(CGF, e);3355}33563357/// For consumptions, just emit the subexpression and thus elide3358/// the retain/release pair.3359TryEmitResult visitConsumeObject(const Expr *e) {3360llvm::Value *result = CGF.EmitScalarExpr(e);3361return TryEmitResult(result, true);3362}33633364TryEmitResult visitBlockExpr(const BlockExpr *e) {3365TryEmitResult result = visitExpr(e);3366// Avoid the block-retain if this is a block literal that doesn't need to be3367// copied to the heap.3368if (CGF.CGM.getCodeGenOpts().ObjCAvoidHeapifyLocalBlocks &&3369e->getBlockDecl()->canAvoidCopyToHeap())3370result.setInt(true);3371return result;3372}33733374/// Block extends are net +0. Naively, we could just recurse on3375/// the subexpression, but actually we need to ensure that the3376/// value is copied as a block, so there's a little filter here.3377TryEmitResult visitExtendBlockObject(const Expr *e) {3378llvm::Value *result; // will be a +0 value33793380// If we can't safely assume the sub-expression will produce a3381// block-copied value, emit the sub-expression at +0.3382if (shouldEmitSeparateBlockRetain(e)) {3383result = CGF.EmitScalarExpr(e);33843385// Otherwise, try to emit the sub-expression at +1 recursively.3386} else {3387TryEmitResult subresult = asImpl().visit(e);33883389// If that produced a retained value, just use that.3390if (subresult.getInt()) {3391return subresult;3392}33933394// Otherwise it's +0.3395result = subresult.getPointer();3396}33973398// Retain the object as a block.3399result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);3400return TryEmitResult(result, true);3401}34023403/// For reclaims, emit the subexpression as a retained call and3404/// skip the consumption.3405TryEmitResult visitReclaimReturnedObject(const Expr *e) {3406llvm::Value *result = emitARCRetainCallResult(CGF, e);3407return TryEmitResult(result, true);3408}34093410/// When we have an undecorated call, retroactively do a claim.3411TryEmitResult visitCall(const Expr *e) {3412llvm::Value *result = emitARCRetainCallResult(CGF, e);3413return TryEmitResult(result, true);3414}34153416// TODO: maybe special-case visitBinAssignWeak?34173418TryEmitResult visitExpr(const Expr *e) {3419// We didn't find an obvious production, so emit what we've got and3420// tell the caller that we didn't manage to retain.3421llvm::Value *result = CGF.EmitScalarExpr(e);3422return TryEmitResult(result, false);3423}3424};3425}34263427static TryEmitResult3428tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {3429return ARCRetainExprEmitter(CGF).visit(e);3430}34313432static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,3433LValue lvalue,3434QualType type) {3435TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);3436llvm::Value *value = result.getPointer();3437if (!result.getInt())3438value = CGF.EmitARCRetain(type, value);3439return value;3440}34413442/// EmitARCRetainScalarExpr - Semantically equivalent to3443/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a3444/// best-effort attempt to peephole expressions that naturally produce3445/// retained objects.3446llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {3447// The retain needs to happen within the full-expression.3448if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {3449RunCleanupsScope scope(*this);3450return EmitARCRetainScalarExpr(cleanups->getSubExpr());3451}34523453TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);3454llvm::Value *value = result.getPointer();3455if (!result.getInt())3456value = EmitARCRetain(e->getType(), value);3457return value;3458}34593460llvm::Value *3461CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {3462// The retain needs to happen within the full-expression.3463if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {3464RunCleanupsScope scope(*this);3465return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());3466}34673468TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);3469llvm::Value *value = result.getPointer();3470if (result.getInt())3471value = EmitARCAutorelease(value);3472else3473value = EmitARCRetainAutorelease(e->getType(), value);3474return value;3475}34763477llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {3478llvm::Value *result;3479bool doRetain;34803481if (shouldEmitSeparateBlockRetain(e)) {3482result = EmitScalarExpr(e);3483doRetain = true;3484} else {3485TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);3486result = subresult.getPointer();3487doRetain = !subresult.getInt();3488}34893490if (doRetain)3491result = EmitARCRetainBlock(result, /*mandatory*/ true);3492return EmitObjCConsumeObject(e->getType(), result);3493}34943495llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {3496// In ARC, retain and autorelease the expression.3497if (getLangOpts().ObjCAutoRefCount) {3498// Do so before running any cleanups for the full-expression.3499// EmitARCRetainAutoreleaseScalarExpr does this for us.3500return EmitARCRetainAutoreleaseScalarExpr(expr);3501}35023503// Otherwise, use the normal scalar-expression emission. The3504// exception machinery doesn't do anything special with the3505// exception like retaining it, so there's no safety associated with3506// only running cleanups after the throw has started, and when it3507// matters it tends to be substantially inferior code.3508return EmitScalarExpr(expr);3509}35103511namespace {35123513/// An emitter for assigning into an __unsafe_unretained context.3514struct ARCUnsafeUnretainedExprEmitter :3515public ARCExprEmitter<ARCUnsafeUnretainedExprEmitter, llvm::Value*> {35163517ARCUnsafeUnretainedExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}35183519llvm::Value *getValueOfResult(llvm::Value *value) {3520return value;3521}35223523llvm::Value *emitBitCast(llvm::Value *value, llvm::Type *resultType) {3524return CGF.Builder.CreateBitCast(value, resultType);3525}35263527llvm::Value *visitLValueToRValue(const Expr *e) {3528return CGF.EmitScalarExpr(e);3529}35303531/// For consumptions, just emit the subexpression and perform the3532/// consumption like normal.3533llvm::Value *visitConsumeObject(const Expr *e) {3534llvm::Value *value = CGF.EmitScalarExpr(e);3535return CGF.EmitObjCConsumeObject(e->getType(), value);3536}35373538/// No special logic for block extensions. (This probably can't3539/// actually happen in this emitter, though.)3540llvm::Value *visitExtendBlockObject(const Expr *e) {3541return CGF.EmitARCExtendBlockObject(e);3542}35433544/// For reclaims, perform an unsafeClaim if that's enabled.3545llvm::Value *visitReclaimReturnedObject(const Expr *e) {3546return CGF.EmitARCReclaimReturnedObject(e, /*unsafe*/ true);3547}35483549/// When we have an undecorated call, just emit it without adding3550/// the unsafeClaim.3551llvm::Value *visitCall(const Expr *e) {3552return CGF.EmitScalarExpr(e);3553}35543555/// Just do normal scalar emission in the default case.3556llvm::Value *visitExpr(const Expr *e) {3557return CGF.EmitScalarExpr(e);3558}3559};3560}35613562static llvm::Value *emitARCUnsafeUnretainedScalarExpr(CodeGenFunction &CGF,3563const Expr *e) {3564return ARCUnsafeUnretainedExprEmitter(CGF).visit(e);3565}35663567/// EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to3568/// immediately releasing the resut of EmitARCRetainScalarExpr, but3569/// avoiding any spurious retains, including by performing reclaims3570/// with objc_unsafeClaimAutoreleasedReturnValue.3571llvm::Value *CodeGenFunction::EmitARCUnsafeUnretainedScalarExpr(const Expr *e) {3572// Look through full-expressions.3573if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {3574RunCleanupsScope scope(*this);3575return emitARCUnsafeUnretainedScalarExpr(*this, cleanups->getSubExpr());3576}35773578return emitARCUnsafeUnretainedScalarExpr(*this, e);3579}35803581std::pair<LValue,llvm::Value*>3582CodeGenFunction::EmitARCStoreUnsafeUnretained(const BinaryOperator *e,3583bool ignored) {3584// Evaluate the RHS first. If we're ignoring the result, assume3585// that we can emit at an unsafe +0.3586llvm::Value *value;3587if (ignored) {3588value = EmitARCUnsafeUnretainedScalarExpr(e->getRHS());3589} else {3590value = EmitScalarExpr(e->getRHS());3591}35923593// Emit the LHS and perform the store.3594LValue lvalue = EmitLValue(e->getLHS());3595EmitStoreOfScalar(value, lvalue);35963597return std::pair<LValue,llvm::Value*>(std::move(lvalue), value);3598}35993600std::pair<LValue,llvm::Value*>3601CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,3602bool ignored) {3603// Evaluate the RHS first.3604TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());3605llvm::Value *value = result.getPointer();36063607bool hasImmediateRetain = result.getInt();36083609// If we didn't emit a retained object, and the l-value is of block3610// type, then we need to emit the block-retain immediately in case3611// it invalidates the l-value.3612if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {3613value = EmitARCRetainBlock(value, /*mandatory*/ false);3614hasImmediateRetain = true;3615}36163617LValue lvalue = EmitLValue(e->getLHS());36183619// If the RHS was emitted retained, expand this.3620if (hasImmediateRetain) {3621llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());3622EmitStoreOfScalar(value, lvalue);3623EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());3624} else {3625value = EmitARCStoreStrong(lvalue, value, ignored);3626}36273628return std::pair<LValue,llvm::Value*>(lvalue, value);3629}36303631std::pair<LValue,llvm::Value*>3632CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {3633llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());3634LValue lvalue = EmitLValue(e->getLHS());36353636EmitStoreOfScalar(value, lvalue);36373638return std::pair<LValue,llvm::Value*>(lvalue, value);3639}36403641void CodeGenFunction::EmitObjCAutoreleasePoolStmt(3642const ObjCAutoreleasePoolStmt &ARPS) {3643const Stmt *subStmt = ARPS.getSubStmt();3644const CompoundStmt &S = cast<CompoundStmt>(*subStmt);36453646CGDebugInfo *DI = getDebugInfo();3647if (DI)3648DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());36493650// Keep track of the current cleanup stack depth.3651RunCleanupsScope Scope(*this);3652if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {3653llvm::Value *token = EmitObjCAutoreleasePoolPush();3654EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);3655} else {3656llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();3657EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);3658}36593660for (const auto *I : S.body())3661EmitStmt(I);36623663if (DI)3664DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());3665}36663667/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,3668/// make sure it survives garbage collection until this point.3669void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {3670// We just use an inline assembly.3671llvm::FunctionType *extenderType3672= llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);3673llvm::InlineAsm *extender = llvm::InlineAsm::get(extenderType,3674/* assembly */ "",3675/* constraints */ "r",3676/* side effects */ true);36773678EmitNounwindRuntimeCall(extender, object);3679}36803681/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with3682/// non-trivial copy assignment function, produce following helper function.3683/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }3684///3685llvm::Constant *3686CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(3687const ObjCPropertyImplDecl *PID) {3688const ObjCPropertyDecl *PD = PID->getPropertyDecl();3689if ((!(PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_atomic)))3690return nullptr;36913692QualType Ty = PID->getPropertyIvarDecl()->getType();3693ASTContext &C = getContext();36943695if (Ty.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct) {3696// Call the move assignment operator instead of calling the copy assignment3697// operator and destructor.3698CharUnits Alignment = C.getTypeAlignInChars(Ty);3699llvm::Constant *Fn = getNonTrivialCStructMoveAssignmentOperator(3700CGM, Alignment, Alignment, Ty.isVolatileQualified(), Ty);3701return Fn;3702}37033704if (!getLangOpts().CPlusPlus ||3705!getLangOpts().ObjCRuntime.hasAtomicCopyHelper())3706return nullptr;3707if (!Ty->isRecordType())3708return nullptr;3709llvm::Constant *HelperFn = nullptr;3710if (hasTrivialSetExpr(PID))3711return nullptr;3712assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");3713if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))3714return HelperFn;37153716const IdentifierInfo *II =3717&CGM.getContext().Idents.get("__assign_helper_atomic_property_");37183719QualType ReturnTy = C.VoidTy;3720QualType DestTy = C.getPointerType(Ty);3721QualType SrcTy = Ty;3722SrcTy.addConst();3723SrcTy = C.getPointerType(SrcTy);37243725SmallVector<QualType, 2> ArgTys;3726ArgTys.push_back(DestTy);3727ArgTys.push_back(SrcTy);3728QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});37293730FunctionDecl *FD = FunctionDecl::Create(3731C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,3732FunctionTy, nullptr, SC_Static, false, false, false);37333734FunctionArgList args;3735ParmVarDecl *Params[2];3736ParmVarDecl *DstDecl = ParmVarDecl::Create(3737C, FD, SourceLocation(), SourceLocation(), nullptr, DestTy,3738C.getTrivialTypeSourceInfo(DestTy, SourceLocation()), SC_None,3739/*DefArg=*/nullptr);3740args.push_back(Params[0] = DstDecl);3741ParmVarDecl *SrcDecl = ParmVarDecl::Create(3742C, FD, SourceLocation(), SourceLocation(), nullptr, SrcTy,3743C.getTrivialTypeSourceInfo(SrcTy, SourceLocation()), SC_None,3744/*DefArg=*/nullptr);3745args.push_back(Params[1] = SrcDecl);3746FD->setParams(Params);37473748const CGFunctionInfo &FI =3749CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);37503751llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);37523753llvm::Function *Fn =3754llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,3755"__assign_helper_atomic_property_",3756&CGM.getModule());37573758CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);37593760StartFunction(FD, ReturnTy, Fn, FI, args);37613762DeclRefExpr DstExpr(C, DstDecl, false, DestTy, VK_PRValue, SourceLocation());3763UnaryOperator *DST = UnaryOperator::Create(3764C, &DstExpr, UO_Deref, DestTy->getPointeeType(), VK_LValue, OK_Ordinary,3765SourceLocation(), false, FPOptionsOverride());37663767DeclRefExpr SrcExpr(C, SrcDecl, false, SrcTy, VK_PRValue, SourceLocation());3768UnaryOperator *SRC = UnaryOperator::Create(3769C, &SrcExpr, UO_Deref, SrcTy->getPointeeType(), VK_LValue, OK_Ordinary,3770SourceLocation(), false, FPOptionsOverride());37713772Expr *Args[2] = {DST, SRC};3773CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());3774CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(3775C, OO_Equal, CalleeExp->getCallee(), Args, DestTy->getPointeeType(),3776VK_LValue, SourceLocation(), FPOptionsOverride());37773778EmitStmt(TheCall);37793780FinishFunction();3781HelperFn = Fn;3782CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);3783return HelperFn;3784}37853786llvm::Constant *CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(3787const ObjCPropertyImplDecl *PID) {3788const ObjCPropertyDecl *PD = PID->getPropertyDecl();3789if ((!(PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_atomic)))3790return nullptr;37913792QualType Ty = PD->getType();3793ASTContext &C = getContext();37943795if (Ty.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct) {3796CharUnits Alignment = C.getTypeAlignInChars(Ty);3797llvm::Constant *Fn = getNonTrivialCStructCopyConstructor(3798CGM, Alignment, Alignment, Ty.isVolatileQualified(), Ty);3799return Fn;3800}38013802if (!getLangOpts().CPlusPlus ||3803!getLangOpts().ObjCRuntime.hasAtomicCopyHelper())3804return nullptr;3805if (!Ty->isRecordType())3806return nullptr;3807llvm::Constant *HelperFn = nullptr;3808if (hasTrivialGetExpr(PID))3809return nullptr;3810assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");3811if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))3812return HelperFn;38133814const IdentifierInfo *II =3815&CGM.getContext().Idents.get("__copy_helper_atomic_property_");38163817QualType ReturnTy = C.VoidTy;3818QualType DestTy = C.getPointerType(Ty);3819QualType SrcTy = Ty;3820SrcTy.addConst();3821SrcTy = C.getPointerType(SrcTy);38223823SmallVector<QualType, 2> ArgTys;3824ArgTys.push_back(DestTy);3825ArgTys.push_back(SrcTy);3826QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});38273828FunctionDecl *FD = FunctionDecl::Create(3829C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,3830FunctionTy, nullptr, SC_Static, false, false, false);38313832FunctionArgList args;3833ParmVarDecl *Params[2];3834ParmVarDecl *DstDecl = ParmVarDecl::Create(3835C, FD, SourceLocation(), SourceLocation(), nullptr, DestTy,3836C.getTrivialTypeSourceInfo(DestTy, SourceLocation()), SC_None,3837/*DefArg=*/nullptr);3838args.push_back(Params[0] = DstDecl);3839ParmVarDecl *SrcDecl = ParmVarDecl::Create(3840C, FD, SourceLocation(), SourceLocation(), nullptr, SrcTy,3841C.getTrivialTypeSourceInfo(SrcTy, SourceLocation()), SC_None,3842/*DefArg=*/nullptr);3843args.push_back(Params[1] = SrcDecl);3844FD->setParams(Params);38453846const CGFunctionInfo &FI =3847CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);38483849llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);38503851llvm::Function *Fn = llvm::Function::Create(3852LTy, llvm::GlobalValue::InternalLinkage, "__copy_helper_atomic_property_",3853&CGM.getModule());38543855CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);38563857StartFunction(FD, ReturnTy, Fn, FI, args);38583859DeclRefExpr SrcExpr(getContext(), SrcDecl, false, SrcTy, VK_PRValue,3860SourceLocation());38613862UnaryOperator *SRC = UnaryOperator::Create(3863C, &SrcExpr, UO_Deref, SrcTy->getPointeeType(), VK_LValue, OK_Ordinary,3864SourceLocation(), false, FPOptionsOverride());38653866CXXConstructExpr *CXXConstExpr =3867cast<CXXConstructExpr>(PID->getGetterCXXConstructor());38683869SmallVector<Expr*, 4> ConstructorArgs;3870ConstructorArgs.push_back(SRC);3871ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),3872CXXConstExpr->arg_end());38733874CXXConstructExpr *TheCXXConstructExpr =3875CXXConstructExpr::Create(C, Ty, SourceLocation(),3876CXXConstExpr->getConstructor(),3877CXXConstExpr->isElidable(),3878ConstructorArgs,3879CXXConstExpr->hadMultipleCandidates(),3880CXXConstExpr->isListInitialization(),3881CXXConstExpr->isStdInitListInitialization(),3882CXXConstExpr->requiresZeroInitialization(),3883CXXConstExpr->getConstructionKind(),3884SourceRange());38853886DeclRefExpr DstExpr(getContext(), DstDecl, false, DestTy, VK_PRValue,3887SourceLocation());38883889RValue DV = EmitAnyExpr(&DstExpr);3890CharUnits Alignment =3891getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());3892EmitAggExpr(TheCXXConstructExpr,3893AggValueSlot::forAddr(3894Address(DV.getScalarVal(), ConvertTypeForMem(Ty), Alignment),3895Qualifiers(), AggValueSlot::IsDestructed,3896AggValueSlot::DoesNotNeedGCBarriers,3897AggValueSlot::IsNotAliased, AggValueSlot::DoesNotOverlap));38983899FinishFunction();3900HelperFn = Fn;3901CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);3902return HelperFn;3903}39043905llvm::Value *3906CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {3907// Get selectors for retain/autorelease.3908const IdentifierInfo *CopyID = &getContext().Idents.get("copy");3909Selector CopySelector =3910getContext().Selectors.getNullarySelector(CopyID);3911const IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");3912Selector AutoreleaseSelector =3913getContext().Selectors.getNullarySelector(AutoreleaseID);39143915// Emit calls to retain/autorelease.3916CGObjCRuntime &Runtime = CGM.getObjCRuntime();3917llvm::Value *Val = Block;3918RValue Result;3919Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),3920Ty, CopySelector,3921Val, CallArgList(), nullptr, nullptr);3922Val = Result.getScalarVal();3923Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),3924Ty, AutoreleaseSelector,3925Val, CallArgList(), nullptr, nullptr);3926Val = Result.getScalarVal();3927return Val;3928}39293930static unsigned getBaseMachOPlatformID(const llvm::Triple &TT) {3931switch (TT.getOS()) {3932case llvm::Triple::Darwin:3933case llvm::Triple::MacOSX:3934return llvm::MachO::PLATFORM_MACOS;3935case llvm::Triple::IOS:3936return llvm::MachO::PLATFORM_IOS;3937case llvm::Triple::TvOS:3938return llvm::MachO::PLATFORM_TVOS;3939case llvm::Triple::WatchOS:3940return llvm::MachO::PLATFORM_WATCHOS;3941case llvm::Triple::XROS:3942return llvm::MachO::PLATFORM_XROS;3943case llvm::Triple::DriverKit:3944return llvm::MachO::PLATFORM_DRIVERKIT;3945default:3946return llvm::MachO::PLATFORM_UNKNOWN;3947}3948}39493950static llvm::Value *emitIsPlatformVersionAtLeast(CodeGenFunction &CGF,3951const VersionTuple &Version) {3952CodeGenModule &CGM = CGF.CGM;3953// Note: we intend to support multi-platform version checks, so reserve3954// the room for a dual platform checking invocation that will be3955// implemented in the future.3956llvm::SmallVector<llvm::Value *, 8> Args;39573958auto EmitArgs = [&](const VersionTuple &Version, const llvm::Triple &TT) {3959std::optional<unsigned> Min = Version.getMinor(),3960SMin = Version.getSubminor();3961Args.push_back(3962llvm::ConstantInt::get(CGM.Int32Ty, getBaseMachOPlatformID(TT)));3963Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, Version.getMajor()));3964Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, Min.value_or(0)));3965Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, SMin.value_or(0)));3966};39673968assert(!Version.empty() && "unexpected empty version");3969EmitArgs(Version, CGM.getTarget().getTriple());39703971if (!CGM.IsPlatformVersionAtLeastFn) {3972llvm::FunctionType *FTy = llvm::FunctionType::get(3973CGM.Int32Ty, {CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty},3974false);3975CGM.IsPlatformVersionAtLeastFn =3976CGM.CreateRuntimeFunction(FTy, "__isPlatformVersionAtLeast");3977}39783979llvm::Value *Check =3980CGF.EmitNounwindRuntimeCall(CGM.IsPlatformVersionAtLeastFn, Args);3981return CGF.Builder.CreateICmpNE(Check,3982llvm::Constant::getNullValue(CGM.Int32Ty));3983}39843985llvm::Value *3986CodeGenFunction::EmitBuiltinAvailable(const VersionTuple &Version) {3987// Darwin uses the new __isPlatformVersionAtLeast family of routines.3988if (CGM.getTarget().getTriple().isOSDarwin())3989return emitIsPlatformVersionAtLeast(*this, Version);39903991if (!CGM.IsOSVersionAtLeastFn) {3992llvm::FunctionType *FTy =3993llvm::FunctionType::get(Int32Ty, {Int32Ty, Int32Ty, Int32Ty}, false);3994CGM.IsOSVersionAtLeastFn =3995CGM.CreateRuntimeFunction(FTy, "__isOSVersionAtLeast");3996}39973998std::optional<unsigned> Min = Version.getMinor(),3999SMin = Version.getSubminor();4000llvm::Value *Args[] = {4001llvm::ConstantInt::get(CGM.Int32Ty, Version.getMajor()),4002llvm::ConstantInt::get(CGM.Int32Ty, Min.value_or(0)),4003llvm::ConstantInt::get(CGM.Int32Ty, SMin.value_or(0))};40044005llvm::Value *CallRes =4006EmitNounwindRuntimeCall(CGM.IsOSVersionAtLeastFn, Args);40074008return Builder.CreateICmpNE(CallRes, llvm::Constant::getNullValue(Int32Ty));4009}40104011static bool isFoundationNeededForDarwinAvailabilityCheck(4012const llvm::Triple &TT, const VersionTuple &TargetVersion) {4013VersionTuple FoundationDroppedInVersion;4014switch (TT.getOS()) {4015case llvm::Triple::IOS:4016case llvm::Triple::TvOS:4017FoundationDroppedInVersion = VersionTuple(/*Major=*/13);4018break;4019case llvm::Triple::WatchOS:4020FoundationDroppedInVersion = VersionTuple(/*Major=*/6);4021break;4022case llvm::Triple::Darwin:4023case llvm::Triple::MacOSX:4024FoundationDroppedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/15);4025break;4026case llvm::Triple::XROS:4027// XROS doesn't need Foundation.4028return false;4029case llvm::Triple::DriverKit:4030// DriverKit doesn't need Foundation.4031return false;4032default:4033llvm_unreachable("Unexpected OS");4034}4035return TargetVersion < FoundationDroppedInVersion;4036}40374038void CodeGenModule::emitAtAvailableLinkGuard() {4039if (!IsPlatformVersionAtLeastFn)4040return;4041// @available requires CoreFoundation only on Darwin.4042if (!Target.getTriple().isOSDarwin())4043return;4044// @available doesn't need Foundation on macOS 10.15+, iOS/tvOS 13+, or4045// watchOS 6+.4046if (!isFoundationNeededForDarwinAvailabilityCheck(4047Target.getTriple(), Target.getPlatformMinVersion()))4048return;4049// Add -framework CoreFoundation to the linker commands. We still want to4050// emit the core foundation reference down below because otherwise if4051// CoreFoundation is not used in the code, the linker won't link the4052// framework.4053auto &Context = getLLVMContext();4054llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),4055llvm::MDString::get(Context, "CoreFoundation")};4056LinkerOptionsMetadata.push_back(llvm::MDNode::get(Context, Args));4057// Emit a reference to a symbol from CoreFoundation to ensure that4058// CoreFoundation is linked into the final binary.4059llvm::FunctionType *FTy =4060llvm::FunctionType::get(Int32Ty, {VoidPtrTy}, false);4061llvm::FunctionCallee CFFunc =4062CreateRuntimeFunction(FTy, "CFBundleGetVersionNumber");40634064llvm::FunctionType *CheckFTy = llvm::FunctionType::get(VoidTy, {}, false);4065llvm::FunctionCallee CFLinkCheckFuncRef = CreateRuntimeFunction(4066CheckFTy, "__clang_at_available_requires_core_foundation_framework",4067llvm::AttributeList(), /*Local=*/true);4068llvm::Function *CFLinkCheckFunc =4069cast<llvm::Function>(CFLinkCheckFuncRef.getCallee()->stripPointerCasts());4070if (CFLinkCheckFunc->empty()) {4071CFLinkCheckFunc->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);4072CFLinkCheckFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);4073CodeGenFunction CGF(*this);4074CGF.Builder.SetInsertPoint(CGF.createBasicBlock("", CFLinkCheckFunc));4075CGF.EmitNounwindRuntimeCall(CFFunc,4076llvm::Constant::getNullValue(VoidPtrTy));4077CGF.Builder.CreateUnreachable();4078addCompilerUsedGlobal(CFLinkCheckFunc);4079}4080}40814082CGObjCRuntime::~CGObjCRuntime() {}408340844085