106f32e7eSjoerg //===--- CGCall.cpp - Encapsulate calling convention details --------------===//
206f32e7eSjoerg //
306f32e7eSjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
406f32e7eSjoerg // See https://llvm.org/LICENSE.txt for license information.
506f32e7eSjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
606f32e7eSjoerg //
706f32e7eSjoerg //===----------------------------------------------------------------------===//
806f32e7eSjoerg //
906f32e7eSjoerg // These classes wrap the information about a call or function
1006f32e7eSjoerg // definition used to handle ABI compliancy.
1106f32e7eSjoerg //
1206f32e7eSjoerg //===----------------------------------------------------------------------===//
1306f32e7eSjoerg
1406f32e7eSjoerg #include "CGCall.h"
1506f32e7eSjoerg #include "ABIInfo.h"
1606f32e7eSjoerg #include "CGBlocks.h"
1706f32e7eSjoerg #include "CGCXXABI.h"
1806f32e7eSjoerg #include "CGCleanup.h"
19*13fbcb42Sjoerg #include "CGRecordLayout.h"
2006f32e7eSjoerg #include "CodeGenFunction.h"
2106f32e7eSjoerg #include "CodeGenModule.h"
2206f32e7eSjoerg #include "TargetInfo.h"
23*13fbcb42Sjoerg #include "clang/AST/Attr.h"
2406f32e7eSjoerg #include "clang/AST/Decl.h"
2506f32e7eSjoerg #include "clang/AST/DeclCXX.h"
2606f32e7eSjoerg #include "clang/AST/DeclObjC.h"
2706f32e7eSjoerg #include "clang/Basic/CodeGenOptions.h"
2806f32e7eSjoerg #include "clang/Basic/TargetBuiltins.h"
2906f32e7eSjoerg #include "clang/Basic/TargetInfo.h"
3006f32e7eSjoerg #include "clang/CodeGen/CGFunctionInfo.h"
3106f32e7eSjoerg #include "clang/CodeGen/SwiftCallingConv.h"
3206f32e7eSjoerg #include "llvm/ADT/StringExtras.h"
3306f32e7eSjoerg #include "llvm/Analysis/ValueTracking.h"
34*13fbcb42Sjoerg #include "llvm/IR/Assumptions.h"
3506f32e7eSjoerg #include "llvm/IR/Attributes.h"
3606f32e7eSjoerg #include "llvm/IR/CallingConv.h"
3706f32e7eSjoerg #include "llvm/IR/DataLayout.h"
3806f32e7eSjoerg #include "llvm/IR/InlineAsm.h"
3906f32e7eSjoerg #include "llvm/IR/IntrinsicInst.h"
4006f32e7eSjoerg #include "llvm/IR/Intrinsics.h"
41*13fbcb42Sjoerg #include "llvm/Transforms/Utils/Local.h"
4206f32e7eSjoerg using namespace clang;
4306f32e7eSjoerg using namespace CodeGen;
4406f32e7eSjoerg
4506f32e7eSjoerg /***/
4606f32e7eSjoerg
ClangCallConvToLLVMCallConv(CallingConv CC)4706f32e7eSjoerg unsigned CodeGenTypes::ClangCallConvToLLVMCallConv(CallingConv CC) {
4806f32e7eSjoerg switch (CC) {
4906f32e7eSjoerg default: return llvm::CallingConv::C;
5006f32e7eSjoerg case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
5106f32e7eSjoerg case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
5206f32e7eSjoerg case CC_X86RegCall: return llvm::CallingConv::X86_RegCall;
5306f32e7eSjoerg case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
5406f32e7eSjoerg case CC_Win64: return llvm::CallingConv::Win64;
5506f32e7eSjoerg case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
5606f32e7eSjoerg case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
5706f32e7eSjoerg case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
5806f32e7eSjoerg case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
5906f32e7eSjoerg // TODO: Add support for __pascal to LLVM.
6006f32e7eSjoerg case CC_X86Pascal: return llvm::CallingConv::C;
6106f32e7eSjoerg // TODO: Add support for __vectorcall to LLVM.
6206f32e7eSjoerg case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
6306f32e7eSjoerg case CC_AArch64VectorCall: return llvm::CallingConv::AArch64_VectorCall;
6406f32e7eSjoerg case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
6506f32e7eSjoerg case CC_OpenCLKernel: return CGM.getTargetCodeGenInfo().getOpenCLKernelCallingConv();
6606f32e7eSjoerg case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
6706f32e7eSjoerg case CC_PreserveAll: return llvm::CallingConv::PreserveAll;
6806f32e7eSjoerg case CC_Swift: return llvm::CallingConv::Swift;
6906f32e7eSjoerg }
7006f32e7eSjoerg }
7106f32e7eSjoerg
7206f32e7eSjoerg /// Derives the 'this' type for codegen purposes, i.e. ignoring method CVR
7306f32e7eSjoerg /// qualification. Either or both of RD and MD may be null. A null RD indicates
7406f32e7eSjoerg /// that there is no meaningful 'this' type, and a null MD can occur when
7506f32e7eSjoerg /// calling a method pointer.
DeriveThisType(const CXXRecordDecl * RD,const CXXMethodDecl * MD)7606f32e7eSjoerg CanQualType CodeGenTypes::DeriveThisType(const CXXRecordDecl *RD,
7706f32e7eSjoerg const CXXMethodDecl *MD) {
7806f32e7eSjoerg QualType RecTy;
7906f32e7eSjoerg if (RD)
8006f32e7eSjoerg RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
8106f32e7eSjoerg else
8206f32e7eSjoerg RecTy = Context.VoidTy;
8306f32e7eSjoerg
8406f32e7eSjoerg if (MD)
8506f32e7eSjoerg RecTy = Context.getAddrSpaceQualType(RecTy, MD->getMethodQualifiers().getAddressSpace());
8606f32e7eSjoerg return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
8706f32e7eSjoerg }
8806f32e7eSjoerg
8906f32e7eSjoerg /// Returns the canonical formal type of the given C++ method.
GetFormalType(const CXXMethodDecl * MD)9006f32e7eSjoerg static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
9106f32e7eSjoerg return MD->getType()->getCanonicalTypeUnqualified()
9206f32e7eSjoerg .getAs<FunctionProtoType>();
9306f32e7eSjoerg }
9406f32e7eSjoerg
9506f32e7eSjoerg /// Returns the "extra-canonicalized" return type, which discards
9606f32e7eSjoerg /// qualifiers on the return type. Codegen doesn't care about them,
9706f32e7eSjoerg /// and it makes ABI code a little easier to be able to assume that
9806f32e7eSjoerg /// all parameter and return types are top-level unqualified.
GetReturnType(QualType RetTy)9906f32e7eSjoerg static CanQualType GetReturnType(QualType RetTy) {
10006f32e7eSjoerg return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
10106f32e7eSjoerg }
10206f32e7eSjoerg
10306f32e7eSjoerg /// Arrange the argument and result information for a value of the given
10406f32e7eSjoerg /// unprototyped freestanding function type.
10506f32e7eSjoerg const CGFunctionInfo &
arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP)10606f32e7eSjoerg CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
10706f32e7eSjoerg // When translating an unprototyped function type, always use a
10806f32e7eSjoerg // variadic type.
10906f32e7eSjoerg return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
11006f32e7eSjoerg /*instanceMethod=*/false,
11106f32e7eSjoerg /*chainCall=*/false, None,
11206f32e7eSjoerg FTNP->getExtInfo(), {}, RequiredArgs(0));
11306f32e7eSjoerg }
11406f32e7eSjoerg
addExtParameterInfosForCall(llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> & paramInfos,const FunctionProtoType * proto,unsigned prefixArgs,unsigned totalArgs)11506f32e7eSjoerg static void addExtParameterInfosForCall(
11606f32e7eSjoerg llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> ¶mInfos,
11706f32e7eSjoerg const FunctionProtoType *proto,
11806f32e7eSjoerg unsigned prefixArgs,
11906f32e7eSjoerg unsigned totalArgs) {
12006f32e7eSjoerg assert(proto->hasExtParameterInfos());
12106f32e7eSjoerg assert(paramInfos.size() <= prefixArgs);
12206f32e7eSjoerg assert(proto->getNumParams() + prefixArgs <= totalArgs);
12306f32e7eSjoerg
12406f32e7eSjoerg paramInfos.reserve(totalArgs);
12506f32e7eSjoerg
12606f32e7eSjoerg // Add default infos for any prefix args that don't already have infos.
12706f32e7eSjoerg paramInfos.resize(prefixArgs);
12806f32e7eSjoerg
12906f32e7eSjoerg // Add infos for the prototype.
13006f32e7eSjoerg for (const auto &ParamInfo : proto->getExtParameterInfos()) {
13106f32e7eSjoerg paramInfos.push_back(ParamInfo);
13206f32e7eSjoerg // pass_object_size params have no parameter info.
13306f32e7eSjoerg if (ParamInfo.hasPassObjectSize())
13406f32e7eSjoerg paramInfos.emplace_back();
13506f32e7eSjoerg }
13606f32e7eSjoerg
13706f32e7eSjoerg assert(paramInfos.size() <= totalArgs &&
13806f32e7eSjoerg "Did we forget to insert pass_object_size args?");
13906f32e7eSjoerg // Add default infos for the variadic and/or suffix arguments.
14006f32e7eSjoerg paramInfos.resize(totalArgs);
14106f32e7eSjoerg }
14206f32e7eSjoerg
14306f32e7eSjoerg /// Adds the formal parameters in FPT to the given prefix. If any parameter in
14406f32e7eSjoerg /// FPT has pass_object_size attrs, then we'll add parameters for those, too.
appendParameterTypes(const CodeGenTypes & CGT,SmallVectorImpl<CanQualType> & prefix,SmallVectorImpl<FunctionProtoType::ExtParameterInfo> & paramInfos,CanQual<FunctionProtoType> FPT)14506f32e7eSjoerg static void appendParameterTypes(const CodeGenTypes &CGT,
14606f32e7eSjoerg SmallVectorImpl<CanQualType> &prefix,
14706f32e7eSjoerg SmallVectorImpl<FunctionProtoType::ExtParameterInfo> ¶mInfos,
14806f32e7eSjoerg CanQual<FunctionProtoType> FPT) {
14906f32e7eSjoerg // Fast path: don't touch param info if we don't need to.
15006f32e7eSjoerg if (!FPT->hasExtParameterInfos()) {
15106f32e7eSjoerg assert(paramInfos.empty() &&
15206f32e7eSjoerg "We have paramInfos, but the prototype doesn't?");
15306f32e7eSjoerg prefix.append(FPT->param_type_begin(), FPT->param_type_end());
15406f32e7eSjoerg return;
15506f32e7eSjoerg }
15606f32e7eSjoerg
15706f32e7eSjoerg unsigned PrefixSize = prefix.size();
15806f32e7eSjoerg // In the vast majority of cases, we'll have precisely FPT->getNumParams()
15906f32e7eSjoerg // parameters; the only thing that can change this is the presence of
16006f32e7eSjoerg // pass_object_size. So, we preallocate for the common case.
16106f32e7eSjoerg prefix.reserve(prefix.size() + FPT->getNumParams());
16206f32e7eSjoerg
16306f32e7eSjoerg auto ExtInfos = FPT->getExtParameterInfos();
16406f32e7eSjoerg assert(ExtInfos.size() == FPT->getNumParams());
16506f32e7eSjoerg for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
16606f32e7eSjoerg prefix.push_back(FPT->getParamType(I));
16706f32e7eSjoerg if (ExtInfos[I].hasPassObjectSize())
16806f32e7eSjoerg prefix.push_back(CGT.getContext().getSizeType());
16906f32e7eSjoerg }
17006f32e7eSjoerg
17106f32e7eSjoerg addExtParameterInfosForCall(paramInfos, FPT.getTypePtr(), PrefixSize,
17206f32e7eSjoerg prefix.size());
17306f32e7eSjoerg }
17406f32e7eSjoerg
17506f32e7eSjoerg /// Arrange the LLVM function layout for a value of the given function
17606f32e7eSjoerg /// type, on top of any implicit parameters already stored.
17706f32e7eSjoerg static const CGFunctionInfo &
arrangeLLVMFunctionInfo(CodeGenTypes & CGT,bool instanceMethod,SmallVectorImpl<CanQualType> & prefix,CanQual<FunctionProtoType> FTP)17806f32e7eSjoerg arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
17906f32e7eSjoerg SmallVectorImpl<CanQualType> &prefix,
18006f32e7eSjoerg CanQual<FunctionProtoType> FTP) {
18106f32e7eSjoerg SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
18206f32e7eSjoerg RequiredArgs Required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
18306f32e7eSjoerg // FIXME: Kill copy.
18406f32e7eSjoerg appendParameterTypes(CGT, prefix, paramInfos, FTP);
18506f32e7eSjoerg CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
18606f32e7eSjoerg
18706f32e7eSjoerg return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
18806f32e7eSjoerg /*chainCall=*/false, prefix,
18906f32e7eSjoerg FTP->getExtInfo(), paramInfos,
19006f32e7eSjoerg Required);
19106f32e7eSjoerg }
19206f32e7eSjoerg
19306f32e7eSjoerg /// Arrange the argument and result information for a value of the
19406f32e7eSjoerg /// given freestanding function type.
19506f32e7eSjoerg const CGFunctionInfo &
arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP)19606f32e7eSjoerg CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
19706f32e7eSjoerg SmallVector<CanQualType, 16> argTypes;
19806f32e7eSjoerg return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
19906f32e7eSjoerg FTP);
20006f32e7eSjoerg }
20106f32e7eSjoerg
getCallingConventionForDecl(const ObjCMethodDecl * D,bool IsWindows)202*13fbcb42Sjoerg static CallingConv getCallingConventionForDecl(const ObjCMethodDecl *D,
203*13fbcb42Sjoerg bool IsWindows) {
20406f32e7eSjoerg // Set the appropriate calling convention for the Function.
20506f32e7eSjoerg if (D->hasAttr<StdCallAttr>())
20606f32e7eSjoerg return CC_X86StdCall;
20706f32e7eSjoerg
20806f32e7eSjoerg if (D->hasAttr<FastCallAttr>())
20906f32e7eSjoerg return CC_X86FastCall;
21006f32e7eSjoerg
21106f32e7eSjoerg if (D->hasAttr<RegCallAttr>())
21206f32e7eSjoerg return CC_X86RegCall;
21306f32e7eSjoerg
21406f32e7eSjoerg if (D->hasAttr<ThisCallAttr>())
21506f32e7eSjoerg return CC_X86ThisCall;
21606f32e7eSjoerg
21706f32e7eSjoerg if (D->hasAttr<VectorCallAttr>())
21806f32e7eSjoerg return CC_X86VectorCall;
21906f32e7eSjoerg
22006f32e7eSjoerg if (D->hasAttr<PascalAttr>())
22106f32e7eSjoerg return CC_X86Pascal;
22206f32e7eSjoerg
22306f32e7eSjoerg if (PcsAttr *PCS = D->getAttr<PcsAttr>())
22406f32e7eSjoerg return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
22506f32e7eSjoerg
22606f32e7eSjoerg if (D->hasAttr<AArch64VectorPcsAttr>())
22706f32e7eSjoerg return CC_AArch64VectorCall;
22806f32e7eSjoerg
22906f32e7eSjoerg if (D->hasAttr<IntelOclBiccAttr>())
23006f32e7eSjoerg return CC_IntelOclBicc;
23106f32e7eSjoerg
23206f32e7eSjoerg if (D->hasAttr<MSABIAttr>())
23306f32e7eSjoerg return IsWindows ? CC_C : CC_Win64;
23406f32e7eSjoerg
23506f32e7eSjoerg if (D->hasAttr<SysVABIAttr>())
23606f32e7eSjoerg return IsWindows ? CC_X86_64SysV : CC_C;
23706f32e7eSjoerg
23806f32e7eSjoerg if (D->hasAttr<PreserveMostAttr>())
23906f32e7eSjoerg return CC_PreserveMost;
24006f32e7eSjoerg
24106f32e7eSjoerg if (D->hasAttr<PreserveAllAttr>())
24206f32e7eSjoerg return CC_PreserveAll;
24306f32e7eSjoerg
24406f32e7eSjoerg return CC_C;
24506f32e7eSjoerg }
24606f32e7eSjoerg
24706f32e7eSjoerg /// Arrange the argument and result information for a call to an
24806f32e7eSjoerg /// unknown C++ non-static member function of the given abstract type.
24906f32e7eSjoerg /// (A null RD means we don't have any meaningful "this" argument type,
25006f32e7eSjoerg /// so fall back to a generic pointer type).
25106f32e7eSjoerg /// The member function must be an ordinary function, i.e. not a
25206f32e7eSjoerg /// constructor or destructor.
25306f32e7eSjoerg const CGFunctionInfo &
arrangeCXXMethodType(const CXXRecordDecl * RD,const FunctionProtoType * FTP,const CXXMethodDecl * MD)25406f32e7eSjoerg CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
25506f32e7eSjoerg const FunctionProtoType *FTP,
25606f32e7eSjoerg const CXXMethodDecl *MD) {
25706f32e7eSjoerg SmallVector<CanQualType, 16> argTypes;
25806f32e7eSjoerg
25906f32e7eSjoerg // Add the 'this' pointer.
26006f32e7eSjoerg argTypes.push_back(DeriveThisType(RD, MD));
26106f32e7eSjoerg
26206f32e7eSjoerg return ::arrangeLLVMFunctionInfo(
26306f32e7eSjoerg *this, true, argTypes,
26406f32e7eSjoerg FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
26506f32e7eSjoerg }
26606f32e7eSjoerg
26706f32e7eSjoerg /// Set calling convention for CUDA/HIP kernel.
setCUDAKernelCallingConvention(CanQualType & FTy,CodeGenModule & CGM,const FunctionDecl * FD)26806f32e7eSjoerg static void setCUDAKernelCallingConvention(CanQualType &FTy, CodeGenModule &CGM,
26906f32e7eSjoerg const FunctionDecl *FD) {
27006f32e7eSjoerg if (FD->hasAttr<CUDAGlobalAttr>()) {
27106f32e7eSjoerg const FunctionType *FT = FTy->getAs<FunctionType>();
27206f32e7eSjoerg CGM.getTargetCodeGenInfo().setCUDAKernelCallingConvention(FT);
27306f32e7eSjoerg FTy = FT->getCanonicalTypeUnqualified();
27406f32e7eSjoerg }
27506f32e7eSjoerg }
27606f32e7eSjoerg
27706f32e7eSjoerg /// Arrange the argument and result information for a declaration or
27806f32e7eSjoerg /// definition of the given C++ non-static member function. The
27906f32e7eSjoerg /// member function must be an ordinary function, i.e. not a
28006f32e7eSjoerg /// constructor or destructor.
28106f32e7eSjoerg const CGFunctionInfo &
arrangeCXXMethodDeclaration(const CXXMethodDecl * MD)28206f32e7eSjoerg CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
28306f32e7eSjoerg assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
28406f32e7eSjoerg assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
28506f32e7eSjoerg
28606f32e7eSjoerg CanQualType FT = GetFormalType(MD).getAs<Type>();
28706f32e7eSjoerg setCUDAKernelCallingConvention(FT, CGM, MD);
28806f32e7eSjoerg auto prototype = FT.getAs<FunctionProtoType>();
28906f32e7eSjoerg
29006f32e7eSjoerg if (MD->isInstance()) {
29106f32e7eSjoerg // The abstract case is perfectly fine.
29206f32e7eSjoerg const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
29306f32e7eSjoerg return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
29406f32e7eSjoerg }
29506f32e7eSjoerg
29606f32e7eSjoerg return arrangeFreeFunctionType(prototype);
29706f32e7eSjoerg }
29806f32e7eSjoerg
inheritingCtorHasParams(const InheritedConstructor & Inherited,CXXCtorType Type)29906f32e7eSjoerg bool CodeGenTypes::inheritingCtorHasParams(
30006f32e7eSjoerg const InheritedConstructor &Inherited, CXXCtorType Type) {
30106f32e7eSjoerg // Parameters are unnecessary if we're constructing a base class subobject
30206f32e7eSjoerg // and the inherited constructor lives in a virtual base.
30306f32e7eSjoerg return Type == Ctor_Complete ||
30406f32e7eSjoerg !Inherited.getShadowDecl()->constructsVirtualBase() ||
30506f32e7eSjoerg !Target.getCXXABI().hasConstructorVariants();
30606f32e7eSjoerg }
30706f32e7eSjoerg
30806f32e7eSjoerg const CGFunctionInfo &
arrangeCXXStructorDeclaration(GlobalDecl GD)30906f32e7eSjoerg CodeGenTypes::arrangeCXXStructorDeclaration(GlobalDecl GD) {
31006f32e7eSjoerg auto *MD = cast<CXXMethodDecl>(GD.getDecl());
31106f32e7eSjoerg
31206f32e7eSjoerg SmallVector<CanQualType, 16> argTypes;
31306f32e7eSjoerg SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
31406f32e7eSjoerg argTypes.push_back(DeriveThisType(MD->getParent(), MD));
31506f32e7eSjoerg
31606f32e7eSjoerg bool PassParams = true;
31706f32e7eSjoerg
31806f32e7eSjoerg if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
31906f32e7eSjoerg // A base class inheriting constructor doesn't get forwarded arguments
32006f32e7eSjoerg // needed to construct a virtual base (or base class thereof).
32106f32e7eSjoerg if (auto Inherited = CD->getInheritedConstructor())
32206f32e7eSjoerg PassParams = inheritingCtorHasParams(Inherited, GD.getCtorType());
32306f32e7eSjoerg }
32406f32e7eSjoerg
32506f32e7eSjoerg CanQual<FunctionProtoType> FTP = GetFormalType(MD);
32606f32e7eSjoerg
32706f32e7eSjoerg // Add the formal parameters.
32806f32e7eSjoerg if (PassParams)
32906f32e7eSjoerg appendParameterTypes(*this, argTypes, paramInfos, FTP);
33006f32e7eSjoerg
331*13fbcb42Sjoerg CGCXXABI::AddedStructorArgCounts AddedArgs =
33206f32e7eSjoerg TheCXXABI.buildStructorSignature(GD, argTypes);
33306f32e7eSjoerg if (!paramInfos.empty()) {
33406f32e7eSjoerg // Note: prefix implies after the first param.
33506f32e7eSjoerg if (AddedArgs.Prefix)
33606f32e7eSjoerg paramInfos.insert(paramInfos.begin() + 1, AddedArgs.Prefix,
33706f32e7eSjoerg FunctionProtoType::ExtParameterInfo{});
33806f32e7eSjoerg if (AddedArgs.Suffix)
33906f32e7eSjoerg paramInfos.append(AddedArgs.Suffix,
34006f32e7eSjoerg FunctionProtoType::ExtParameterInfo{});
34106f32e7eSjoerg }
34206f32e7eSjoerg
34306f32e7eSjoerg RequiredArgs required =
34406f32e7eSjoerg (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size())
34506f32e7eSjoerg : RequiredArgs::All);
34606f32e7eSjoerg
34706f32e7eSjoerg FunctionType::ExtInfo extInfo = FTP->getExtInfo();
34806f32e7eSjoerg CanQualType resultType = TheCXXABI.HasThisReturn(GD)
34906f32e7eSjoerg ? argTypes.front()
35006f32e7eSjoerg : TheCXXABI.hasMostDerivedReturn(GD)
35106f32e7eSjoerg ? CGM.getContext().VoidPtrTy
35206f32e7eSjoerg : Context.VoidTy;
35306f32e7eSjoerg return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
35406f32e7eSjoerg /*chainCall=*/false, argTypes, extInfo,
35506f32e7eSjoerg paramInfos, required);
35606f32e7eSjoerg }
35706f32e7eSjoerg
35806f32e7eSjoerg static SmallVector<CanQualType, 16>
getArgTypesForCall(ASTContext & ctx,const CallArgList & args)35906f32e7eSjoerg getArgTypesForCall(ASTContext &ctx, const CallArgList &args) {
36006f32e7eSjoerg SmallVector<CanQualType, 16> argTypes;
36106f32e7eSjoerg for (auto &arg : args)
36206f32e7eSjoerg argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
36306f32e7eSjoerg return argTypes;
36406f32e7eSjoerg }
36506f32e7eSjoerg
36606f32e7eSjoerg static SmallVector<CanQualType, 16>
getArgTypesForDeclaration(ASTContext & ctx,const FunctionArgList & args)36706f32e7eSjoerg getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) {
36806f32e7eSjoerg SmallVector<CanQualType, 16> argTypes;
36906f32e7eSjoerg for (auto &arg : args)
37006f32e7eSjoerg argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
37106f32e7eSjoerg return argTypes;
37206f32e7eSjoerg }
37306f32e7eSjoerg
37406f32e7eSjoerg static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16>
getExtParameterInfosForCall(const FunctionProtoType * proto,unsigned prefixArgs,unsigned totalArgs)37506f32e7eSjoerg getExtParameterInfosForCall(const FunctionProtoType *proto,
37606f32e7eSjoerg unsigned prefixArgs, unsigned totalArgs) {
37706f32e7eSjoerg llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result;
37806f32e7eSjoerg if (proto->hasExtParameterInfos()) {
37906f32e7eSjoerg addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
38006f32e7eSjoerg }
38106f32e7eSjoerg return result;
38206f32e7eSjoerg }
38306f32e7eSjoerg
38406f32e7eSjoerg /// Arrange a call to a C++ method, passing the given arguments.
38506f32e7eSjoerg ///
38606f32e7eSjoerg /// ExtraPrefixArgs is the number of ABI-specific args passed after the `this`
38706f32e7eSjoerg /// parameter.
38806f32e7eSjoerg /// ExtraSuffixArgs is the number of ABI-specific args passed at the end of
38906f32e7eSjoerg /// args.
39006f32e7eSjoerg /// PassProtoArgs indicates whether `args` has args for the parameters in the
39106f32e7eSjoerg /// given CXXConstructorDecl.
39206f32e7eSjoerg const CGFunctionInfo &
arrangeCXXConstructorCall(const CallArgList & args,const CXXConstructorDecl * D,CXXCtorType CtorKind,unsigned ExtraPrefixArgs,unsigned ExtraSuffixArgs,bool PassProtoArgs)39306f32e7eSjoerg CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
39406f32e7eSjoerg const CXXConstructorDecl *D,
39506f32e7eSjoerg CXXCtorType CtorKind,
39606f32e7eSjoerg unsigned ExtraPrefixArgs,
39706f32e7eSjoerg unsigned ExtraSuffixArgs,
39806f32e7eSjoerg bool PassProtoArgs) {
39906f32e7eSjoerg // FIXME: Kill copy.
40006f32e7eSjoerg SmallVector<CanQualType, 16> ArgTypes;
40106f32e7eSjoerg for (const auto &Arg : args)
40206f32e7eSjoerg ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
40306f32e7eSjoerg
40406f32e7eSjoerg // +1 for implicit this, which should always be args[0].
40506f32e7eSjoerg unsigned TotalPrefixArgs = 1 + ExtraPrefixArgs;
40606f32e7eSjoerg
40706f32e7eSjoerg CanQual<FunctionProtoType> FPT = GetFormalType(D);
40806f32e7eSjoerg RequiredArgs Required = PassProtoArgs
40906f32e7eSjoerg ? RequiredArgs::forPrototypePlus(
41006f32e7eSjoerg FPT, TotalPrefixArgs + ExtraSuffixArgs)
41106f32e7eSjoerg : RequiredArgs::All;
41206f32e7eSjoerg
41306f32e7eSjoerg GlobalDecl GD(D, CtorKind);
41406f32e7eSjoerg CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
41506f32e7eSjoerg ? ArgTypes.front()
41606f32e7eSjoerg : TheCXXABI.hasMostDerivedReturn(GD)
41706f32e7eSjoerg ? CGM.getContext().VoidPtrTy
41806f32e7eSjoerg : Context.VoidTy;
41906f32e7eSjoerg
42006f32e7eSjoerg FunctionType::ExtInfo Info = FPT->getExtInfo();
42106f32e7eSjoerg llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> ParamInfos;
42206f32e7eSjoerg // If the prototype args are elided, we should only have ABI-specific args,
42306f32e7eSjoerg // which never have param info.
42406f32e7eSjoerg if (PassProtoArgs && FPT->hasExtParameterInfos()) {
42506f32e7eSjoerg // ABI-specific suffix arguments are treated the same as variadic arguments.
42606f32e7eSjoerg addExtParameterInfosForCall(ParamInfos, FPT.getTypePtr(), TotalPrefixArgs,
42706f32e7eSjoerg ArgTypes.size());
42806f32e7eSjoerg }
42906f32e7eSjoerg return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
43006f32e7eSjoerg /*chainCall=*/false, ArgTypes, Info,
43106f32e7eSjoerg ParamInfos, Required);
43206f32e7eSjoerg }
43306f32e7eSjoerg
43406f32e7eSjoerg /// Arrange the argument and result information for the declaration or
43506f32e7eSjoerg /// definition of the given function.
43606f32e7eSjoerg const CGFunctionInfo &
arrangeFunctionDeclaration(const FunctionDecl * FD)43706f32e7eSjoerg CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
43806f32e7eSjoerg if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
43906f32e7eSjoerg if (MD->isInstance())
44006f32e7eSjoerg return arrangeCXXMethodDeclaration(MD);
44106f32e7eSjoerg
44206f32e7eSjoerg CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
44306f32e7eSjoerg
44406f32e7eSjoerg assert(isa<FunctionType>(FTy));
44506f32e7eSjoerg setCUDAKernelCallingConvention(FTy, CGM, FD);
44606f32e7eSjoerg
44706f32e7eSjoerg // When declaring a function without a prototype, always use a
44806f32e7eSjoerg // non-variadic type.
44906f32e7eSjoerg if (CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>()) {
45006f32e7eSjoerg return arrangeLLVMFunctionInfo(
45106f32e7eSjoerg noProto->getReturnType(), /*instanceMethod=*/false,
45206f32e7eSjoerg /*chainCall=*/false, None, noProto->getExtInfo(), {},RequiredArgs::All);
45306f32e7eSjoerg }
45406f32e7eSjoerg
45506f32e7eSjoerg return arrangeFreeFunctionType(FTy.castAs<FunctionProtoType>());
45606f32e7eSjoerg }
45706f32e7eSjoerg
45806f32e7eSjoerg /// Arrange the argument and result information for the declaration or
45906f32e7eSjoerg /// definition of an Objective-C method.
46006f32e7eSjoerg const CGFunctionInfo &
arrangeObjCMethodDeclaration(const ObjCMethodDecl * MD)46106f32e7eSjoerg CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
46206f32e7eSjoerg // It happens that this is the same as a call with no optional
46306f32e7eSjoerg // arguments, except also using the formal 'self' type.
46406f32e7eSjoerg return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
46506f32e7eSjoerg }
46606f32e7eSjoerg
46706f32e7eSjoerg /// Arrange the argument and result information for the function type
46806f32e7eSjoerg /// through which to perform a send to the given Objective-C method,
46906f32e7eSjoerg /// using the given receiver type. The receiver type is not always
47006f32e7eSjoerg /// the 'self' type of the method or even an Objective-C pointer type.
47106f32e7eSjoerg /// This is *not* the right method for actually performing such a
47206f32e7eSjoerg /// message send, due to the possibility of optional arguments.
47306f32e7eSjoerg const CGFunctionInfo &
arrangeObjCMessageSendSignature(const ObjCMethodDecl * MD,QualType receiverType)47406f32e7eSjoerg CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
47506f32e7eSjoerg QualType receiverType) {
47606f32e7eSjoerg SmallVector<CanQualType, 16> argTys;
47706f32e7eSjoerg SmallVector<FunctionProtoType::ExtParameterInfo, 4> extParamInfos(2);
47806f32e7eSjoerg argTys.push_back(Context.getCanonicalParamType(receiverType));
47906f32e7eSjoerg argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
48006f32e7eSjoerg // FIXME: Kill copy?
48106f32e7eSjoerg for (const auto *I : MD->parameters()) {
48206f32e7eSjoerg argTys.push_back(Context.getCanonicalParamType(I->getType()));
48306f32e7eSjoerg auto extParamInfo = FunctionProtoType::ExtParameterInfo().withIsNoEscape(
48406f32e7eSjoerg I->hasAttr<NoEscapeAttr>());
48506f32e7eSjoerg extParamInfos.push_back(extParamInfo);
48606f32e7eSjoerg }
48706f32e7eSjoerg
48806f32e7eSjoerg FunctionType::ExtInfo einfo;
48906f32e7eSjoerg bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
49006f32e7eSjoerg einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
49106f32e7eSjoerg
49206f32e7eSjoerg if (getContext().getLangOpts().ObjCAutoRefCount &&
49306f32e7eSjoerg MD->hasAttr<NSReturnsRetainedAttr>())
49406f32e7eSjoerg einfo = einfo.withProducesResult(true);
49506f32e7eSjoerg
49606f32e7eSjoerg RequiredArgs required =
49706f32e7eSjoerg (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
49806f32e7eSjoerg
49906f32e7eSjoerg return arrangeLLVMFunctionInfo(
50006f32e7eSjoerg GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
50106f32e7eSjoerg /*chainCall=*/false, argTys, einfo, extParamInfos, required);
50206f32e7eSjoerg }
50306f32e7eSjoerg
50406f32e7eSjoerg const CGFunctionInfo &
arrangeUnprototypedObjCMessageSend(QualType returnType,const CallArgList & args)50506f32e7eSjoerg CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType,
50606f32e7eSjoerg const CallArgList &args) {
50706f32e7eSjoerg auto argTypes = getArgTypesForCall(Context, args);
50806f32e7eSjoerg FunctionType::ExtInfo einfo;
50906f32e7eSjoerg
51006f32e7eSjoerg return arrangeLLVMFunctionInfo(
51106f32e7eSjoerg GetReturnType(returnType), /*instanceMethod=*/false,
51206f32e7eSjoerg /*chainCall=*/false, argTypes, einfo, {}, RequiredArgs::All);
51306f32e7eSjoerg }
51406f32e7eSjoerg
51506f32e7eSjoerg const CGFunctionInfo &
arrangeGlobalDeclaration(GlobalDecl GD)51606f32e7eSjoerg CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
51706f32e7eSjoerg // FIXME: Do we need to handle ObjCMethodDecl?
51806f32e7eSjoerg const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
51906f32e7eSjoerg
52006f32e7eSjoerg if (isa<CXXConstructorDecl>(GD.getDecl()) ||
52106f32e7eSjoerg isa<CXXDestructorDecl>(GD.getDecl()))
52206f32e7eSjoerg return arrangeCXXStructorDeclaration(GD);
52306f32e7eSjoerg
52406f32e7eSjoerg return arrangeFunctionDeclaration(FD);
52506f32e7eSjoerg }
52606f32e7eSjoerg
52706f32e7eSjoerg /// Arrange a thunk that takes 'this' as the first parameter followed by
52806f32e7eSjoerg /// varargs. Return a void pointer, regardless of the actual return type.
52906f32e7eSjoerg /// The body of the thunk will end in a musttail call to a function of the
53006f32e7eSjoerg /// correct type, and the caller will bitcast the function to the correct
53106f32e7eSjoerg /// prototype.
53206f32e7eSjoerg const CGFunctionInfo &
arrangeUnprototypedMustTailThunk(const CXXMethodDecl * MD)53306f32e7eSjoerg CodeGenTypes::arrangeUnprototypedMustTailThunk(const CXXMethodDecl *MD) {
53406f32e7eSjoerg assert(MD->isVirtual() && "only methods have thunks");
53506f32e7eSjoerg CanQual<FunctionProtoType> FTP = GetFormalType(MD);
53606f32e7eSjoerg CanQualType ArgTys[] = {DeriveThisType(MD->getParent(), MD)};
53706f32e7eSjoerg return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
53806f32e7eSjoerg /*chainCall=*/false, ArgTys,
53906f32e7eSjoerg FTP->getExtInfo(), {}, RequiredArgs(1));
54006f32e7eSjoerg }
54106f32e7eSjoerg
54206f32e7eSjoerg const CGFunctionInfo &
arrangeMSCtorClosure(const CXXConstructorDecl * CD,CXXCtorType CT)54306f32e7eSjoerg CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
54406f32e7eSjoerg CXXCtorType CT) {
54506f32e7eSjoerg assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
54606f32e7eSjoerg
54706f32e7eSjoerg CanQual<FunctionProtoType> FTP = GetFormalType(CD);
54806f32e7eSjoerg SmallVector<CanQualType, 2> ArgTys;
54906f32e7eSjoerg const CXXRecordDecl *RD = CD->getParent();
55006f32e7eSjoerg ArgTys.push_back(DeriveThisType(RD, CD));
55106f32e7eSjoerg if (CT == Ctor_CopyingClosure)
55206f32e7eSjoerg ArgTys.push_back(*FTP->param_type_begin());
55306f32e7eSjoerg if (RD->getNumVBases() > 0)
55406f32e7eSjoerg ArgTys.push_back(Context.IntTy);
55506f32e7eSjoerg CallingConv CC = Context.getDefaultCallingConvention(
55606f32e7eSjoerg /*IsVariadic=*/false, /*IsCXXMethod=*/true);
55706f32e7eSjoerg return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
55806f32e7eSjoerg /*chainCall=*/false, ArgTys,
55906f32e7eSjoerg FunctionType::ExtInfo(CC), {},
56006f32e7eSjoerg RequiredArgs::All);
56106f32e7eSjoerg }
56206f32e7eSjoerg
56306f32e7eSjoerg /// Arrange a call as unto a free function, except possibly with an
56406f32e7eSjoerg /// additional number of formal parameters considered required.
56506f32e7eSjoerg static const CGFunctionInfo &
arrangeFreeFunctionLikeCall(CodeGenTypes & CGT,CodeGenModule & CGM,const CallArgList & args,const FunctionType * fnType,unsigned numExtraRequiredArgs,bool chainCall)56606f32e7eSjoerg arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
56706f32e7eSjoerg CodeGenModule &CGM,
56806f32e7eSjoerg const CallArgList &args,
56906f32e7eSjoerg const FunctionType *fnType,
57006f32e7eSjoerg unsigned numExtraRequiredArgs,
57106f32e7eSjoerg bool chainCall) {
57206f32e7eSjoerg assert(args.size() >= numExtraRequiredArgs);
57306f32e7eSjoerg
57406f32e7eSjoerg llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
57506f32e7eSjoerg
57606f32e7eSjoerg // In most cases, there are no optional arguments.
57706f32e7eSjoerg RequiredArgs required = RequiredArgs::All;
57806f32e7eSjoerg
57906f32e7eSjoerg // If we have a variadic prototype, the required arguments are the
58006f32e7eSjoerg // extra prefix plus the arguments in the prototype.
58106f32e7eSjoerg if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
58206f32e7eSjoerg if (proto->isVariadic())
58306f32e7eSjoerg required = RequiredArgs::forPrototypePlus(proto, numExtraRequiredArgs);
58406f32e7eSjoerg
58506f32e7eSjoerg if (proto->hasExtParameterInfos())
58606f32e7eSjoerg addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
58706f32e7eSjoerg args.size());
58806f32e7eSjoerg
58906f32e7eSjoerg // If we don't have a prototype at all, but we're supposed to
59006f32e7eSjoerg // explicitly use the variadic convention for unprototyped calls,
59106f32e7eSjoerg // treat all of the arguments as required but preserve the nominal
59206f32e7eSjoerg // possibility of variadics.
59306f32e7eSjoerg } else if (CGM.getTargetCodeGenInfo()
59406f32e7eSjoerg .isNoProtoCallVariadic(args,
59506f32e7eSjoerg cast<FunctionNoProtoType>(fnType))) {
59606f32e7eSjoerg required = RequiredArgs(args.size());
59706f32e7eSjoerg }
59806f32e7eSjoerg
59906f32e7eSjoerg // FIXME: Kill copy.
60006f32e7eSjoerg SmallVector<CanQualType, 16> argTypes;
60106f32e7eSjoerg for (const auto &arg : args)
60206f32e7eSjoerg argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
60306f32e7eSjoerg return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
60406f32e7eSjoerg /*instanceMethod=*/false, chainCall,
60506f32e7eSjoerg argTypes, fnType->getExtInfo(), paramInfos,
60606f32e7eSjoerg required);
60706f32e7eSjoerg }
60806f32e7eSjoerg
60906f32e7eSjoerg /// Figure out the rules for calling a function with the given formal
61006f32e7eSjoerg /// type using the given arguments. The arguments are necessary
61106f32e7eSjoerg /// because the function might be unprototyped, in which case it's
61206f32e7eSjoerg /// target-dependent in crazy ways.
61306f32e7eSjoerg const CGFunctionInfo &
arrangeFreeFunctionCall(const CallArgList & args,const FunctionType * fnType,bool chainCall)61406f32e7eSjoerg CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
61506f32e7eSjoerg const FunctionType *fnType,
61606f32e7eSjoerg bool chainCall) {
61706f32e7eSjoerg return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
61806f32e7eSjoerg chainCall ? 1 : 0, chainCall);
61906f32e7eSjoerg }
62006f32e7eSjoerg
62106f32e7eSjoerg /// A block function is essentially a free function with an
62206f32e7eSjoerg /// extra implicit argument.
62306f32e7eSjoerg const CGFunctionInfo &
arrangeBlockFunctionCall(const CallArgList & args,const FunctionType * fnType)62406f32e7eSjoerg CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
62506f32e7eSjoerg const FunctionType *fnType) {
62606f32e7eSjoerg return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
62706f32e7eSjoerg /*chainCall=*/false);
62806f32e7eSjoerg }
62906f32e7eSjoerg
63006f32e7eSjoerg const CGFunctionInfo &
arrangeBlockFunctionDeclaration(const FunctionProtoType * proto,const FunctionArgList & params)63106f32e7eSjoerg CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto,
63206f32e7eSjoerg const FunctionArgList ¶ms) {
63306f32e7eSjoerg auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
63406f32e7eSjoerg auto argTypes = getArgTypesForDeclaration(Context, params);
63506f32e7eSjoerg
63606f32e7eSjoerg return arrangeLLVMFunctionInfo(GetReturnType(proto->getReturnType()),
63706f32e7eSjoerg /*instanceMethod*/ false, /*chainCall*/ false,
63806f32e7eSjoerg argTypes, proto->getExtInfo(), paramInfos,
63906f32e7eSjoerg RequiredArgs::forPrototypePlus(proto, 1));
64006f32e7eSjoerg }
64106f32e7eSjoerg
64206f32e7eSjoerg const CGFunctionInfo &
arrangeBuiltinFunctionCall(QualType resultType,const CallArgList & args)64306f32e7eSjoerg CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType,
64406f32e7eSjoerg const CallArgList &args) {
64506f32e7eSjoerg // FIXME: Kill copy.
64606f32e7eSjoerg SmallVector<CanQualType, 16> argTypes;
64706f32e7eSjoerg for (const auto &Arg : args)
64806f32e7eSjoerg argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
64906f32e7eSjoerg return arrangeLLVMFunctionInfo(
65006f32e7eSjoerg GetReturnType(resultType), /*instanceMethod=*/false,
65106f32e7eSjoerg /*chainCall=*/false, argTypes, FunctionType::ExtInfo(),
65206f32e7eSjoerg /*paramInfos=*/ {}, RequiredArgs::All);
65306f32e7eSjoerg }
65406f32e7eSjoerg
65506f32e7eSjoerg const CGFunctionInfo &
arrangeBuiltinFunctionDeclaration(QualType resultType,const FunctionArgList & args)65606f32e7eSjoerg CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType,
65706f32e7eSjoerg const FunctionArgList &args) {
65806f32e7eSjoerg auto argTypes = getArgTypesForDeclaration(Context, args);
65906f32e7eSjoerg
66006f32e7eSjoerg return arrangeLLVMFunctionInfo(
66106f32e7eSjoerg GetReturnType(resultType), /*instanceMethod=*/false, /*chainCall=*/false,
66206f32e7eSjoerg argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
66306f32e7eSjoerg }
66406f32e7eSjoerg
66506f32e7eSjoerg const CGFunctionInfo &
arrangeBuiltinFunctionDeclaration(CanQualType resultType,ArrayRef<CanQualType> argTypes)66606f32e7eSjoerg CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType,
66706f32e7eSjoerg ArrayRef<CanQualType> argTypes) {
66806f32e7eSjoerg return arrangeLLVMFunctionInfo(
66906f32e7eSjoerg resultType, /*instanceMethod=*/false, /*chainCall=*/false,
67006f32e7eSjoerg argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
67106f32e7eSjoerg }
67206f32e7eSjoerg
67306f32e7eSjoerg /// Arrange a call to a C++ method, passing the given arguments.
67406f32e7eSjoerg ///
67506f32e7eSjoerg /// numPrefixArgs is the number of ABI-specific prefix arguments we have. It
67606f32e7eSjoerg /// does not count `this`.
67706f32e7eSjoerg const CGFunctionInfo &
arrangeCXXMethodCall(const CallArgList & args,const FunctionProtoType * proto,RequiredArgs required,unsigned numPrefixArgs)67806f32e7eSjoerg CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
67906f32e7eSjoerg const FunctionProtoType *proto,
68006f32e7eSjoerg RequiredArgs required,
68106f32e7eSjoerg unsigned numPrefixArgs) {
68206f32e7eSjoerg assert(numPrefixArgs + 1 <= args.size() &&
68306f32e7eSjoerg "Emitting a call with less args than the required prefix?");
68406f32e7eSjoerg // Add one to account for `this`. It's a bit awkward here, but we don't count
68506f32e7eSjoerg // `this` in similar places elsewhere.
68606f32e7eSjoerg auto paramInfos =
68706f32e7eSjoerg getExtParameterInfosForCall(proto, numPrefixArgs + 1, args.size());
68806f32e7eSjoerg
68906f32e7eSjoerg // FIXME: Kill copy.
69006f32e7eSjoerg auto argTypes = getArgTypesForCall(Context, args);
69106f32e7eSjoerg
69206f32e7eSjoerg FunctionType::ExtInfo info = proto->getExtInfo();
69306f32e7eSjoerg return arrangeLLVMFunctionInfo(
69406f32e7eSjoerg GetReturnType(proto->getReturnType()), /*instanceMethod=*/true,
69506f32e7eSjoerg /*chainCall=*/false, argTypes, info, paramInfos, required);
69606f32e7eSjoerg }
69706f32e7eSjoerg
arrangeNullaryFunction()69806f32e7eSjoerg const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
69906f32e7eSjoerg return arrangeLLVMFunctionInfo(
70006f32e7eSjoerg getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
70106f32e7eSjoerg None, FunctionType::ExtInfo(), {}, RequiredArgs::All);
70206f32e7eSjoerg }
70306f32e7eSjoerg
70406f32e7eSjoerg const CGFunctionInfo &
arrangeCall(const CGFunctionInfo & signature,const CallArgList & args)70506f32e7eSjoerg CodeGenTypes::arrangeCall(const CGFunctionInfo &signature,
70606f32e7eSjoerg const CallArgList &args) {
70706f32e7eSjoerg assert(signature.arg_size() <= args.size());
70806f32e7eSjoerg if (signature.arg_size() == args.size())
70906f32e7eSjoerg return signature;
71006f32e7eSjoerg
71106f32e7eSjoerg SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
71206f32e7eSjoerg auto sigParamInfos = signature.getExtParameterInfos();
71306f32e7eSjoerg if (!sigParamInfos.empty()) {
71406f32e7eSjoerg paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
71506f32e7eSjoerg paramInfos.resize(args.size());
71606f32e7eSjoerg }
71706f32e7eSjoerg
71806f32e7eSjoerg auto argTypes = getArgTypesForCall(Context, args);
71906f32e7eSjoerg
72006f32e7eSjoerg assert(signature.getRequiredArgs().allowsOptionalArgs());
72106f32e7eSjoerg return arrangeLLVMFunctionInfo(signature.getReturnType(),
72206f32e7eSjoerg signature.isInstanceMethod(),
72306f32e7eSjoerg signature.isChainCall(),
72406f32e7eSjoerg argTypes,
72506f32e7eSjoerg signature.getExtInfo(),
72606f32e7eSjoerg paramInfos,
72706f32e7eSjoerg signature.getRequiredArgs());
72806f32e7eSjoerg }
72906f32e7eSjoerg
73006f32e7eSjoerg namespace clang {
73106f32e7eSjoerg namespace CodeGen {
73206f32e7eSjoerg void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI);
73306f32e7eSjoerg }
73406f32e7eSjoerg }
73506f32e7eSjoerg
73606f32e7eSjoerg /// Arrange the argument and result information for an abstract value
73706f32e7eSjoerg /// of a given function type. This is the method which all of the
73806f32e7eSjoerg /// above functions ultimately defer to.
73906f32e7eSjoerg const CGFunctionInfo &
arrangeLLVMFunctionInfo(CanQualType resultType,bool instanceMethod,bool chainCall,ArrayRef<CanQualType> argTypes,FunctionType::ExtInfo info,ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,RequiredArgs required)74006f32e7eSjoerg CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
74106f32e7eSjoerg bool instanceMethod,
74206f32e7eSjoerg bool chainCall,
74306f32e7eSjoerg ArrayRef<CanQualType> argTypes,
74406f32e7eSjoerg FunctionType::ExtInfo info,
74506f32e7eSjoerg ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
74606f32e7eSjoerg RequiredArgs required) {
74706f32e7eSjoerg assert(llvm::all_of(argTypes,
74806f32e7eSjoerg [](CanQualType T) { return T.isCanonicalAsParam(); }));
74906f32e7eSjoerg
75006f32e7eSjoerg // Lookup or create unique function info.
75106f32e7eSjoerg llvm::FoldingSetNodeID ID;
75206f32e7eSjoerg CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos,
75306f32e7eSjoerg required, resultType, argTypes);
75406f32e7eSjoerg
75506f32e7eSjoerg void *insertPos = nullptr;
75606f32e7eSjoerg CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
75706f32e7eSjoerg if (FI)
75806f32e7eSjoerg return *FI;
75906f32e7eSjoerg
76006f32e7eSjoerg unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
76106f32e7eSjoerg
76206f32e7eSjoerg // Construct the function info. We co-allocate the ArgInfos.
76306f32e7eSjoerg FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
76406f32e7eSjoerg paramInfos, resultType, argTypes, required);
76506f32e7eSjoerg FunctionInfos.InsertNode(FI, insertPos);
76606f32e7eSjoerg
76706f32e7eSjoerg bool inserted = FunctionsBeingProcessed.insert(FI).second;
76806f32e7eSjoerg (void)inserted;
76906f32e7eSjoerg assert(inserted && "Recursively being processed?");
77006f32e7eSjoerg
77106f32e7eSjoerg // Compute ABI information.
77206f32e7eSjoerg if (CC == llvm::CallingConv::SPIR_KERNEL) {
77306f32e7eSjoerg // Force target independent argument handling for the host visible
77406f32e7eSjoerg // kernel functions.
77506f32e7eSjoerg computeSPIRKernelABIInfo(CGM, *FI);
77606f32e7eSjoerg } else if (info.getCC() == CC_Swift) {
77706f32e7eSjoerg swiftcall::computeABIInfo(CGM, *FI);
77806f32e7eSjoerg } else {
77906f32e7eSjoerg getABIInfo().computeInfo(*FI);
78006f32e7eSjoerg }
78106f32e7eSjoerg
78206f32e7eSjoerg // Loop over all of the computed argument and return value info. If any of
78306f32e7eSjoerg // them are direct or extend without a specified coerce type, specify the
78406f32e7eSjoerg // default now.
78506f32e7eSjoerg ABIArgInfo &retInfo = FI->getReturnInfo();
78606f32e7eSjoerg if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
78706f32e7eSjoerg retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
78806f32e7eSjoerg
78906f32e7eSjoerg for (auto &I : FI->arguments())
79006f32e7eSjoerg if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
79106f32e7eSjoerg I.info.setCoerceToType(ConvertType(I.type));
79206f32e7eSjoerg
79306f32e7eSjoerg bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
79406f32e7eSjoerg assert(erased && "Not in set?");
79506f32e7eSjoerg
79606f32e7eSjoerg return *FI;
79706f32e7eSjoerg }
79806f32e7eSjoerg
create(unsigned llvmCC,bool instanceMethod,bool chainCall,const FunctionType::ExtInfo & info,ArrayRef<ExtParameterInfo> paramInfos,CanQualType resultType,ArrayRef<CanQualType> argTypes,RequiredArgs required)79906f32e7eSjoerg CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
80006f32e7eSjoerg bool instanceMethod,
80106f32e7eSjoerg bool chainCall,
80206f32e7eSjoerg const FunctionType::ExtInfo &info,
80306f32e7eSjoerg ArrayRef<ExtParameterInfo> paramInfos,
80406f32e7eSjoerg CanQualType resultType,
80506f32e7eSjoerg ArrayRef<CanQualType> argTypes,
80606f32e7eSjoerg RequiredArgs required) {
80706f32e7eSjoerg assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
80806f32e7eSjoerg assert(!required.allowsOptionalArgs() ||
80906f32e7eSjoerg required.getNumRequiredArgs() <= argTypes.size());
81006f32e7eSjoerg
81106f32e7eSjoerg void *buffer =
81206f32e7eSjoerg operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
81306f32e7eSjoerg argTypes.size() + 1, paramInfos.size()));
81406f32e7eSjoerg
81506f32e7eSjoerg CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
81606f32e7eSjoerg FI->CallingConvention = llvmCC;
81706f32e7eSjoerg FI->EffectiveCallingConvention = llvmCC;
81806f32e7eSjoerg FI->ASTCallingConvention = info.getCC();
81906f32e7eSjoerg FI->InstanceMethod = instanceMethod;
82006f32e7eSjoerg FI->ChainCall = chainCall;
821*13fbcb42Sjoerg FI->CmseNSCall = info.getCmseNSCall();
82206f32e7eSjoerg FI->NoReturn = info.getNoReturn();
82306f32e7eSjoerg FI->ReturnsRetained = info.getProducesResult();
82406f32e7eSjoerg FI->NoCallerSavedRegs = info.getNoCallerSavedRegs();
82506f32e7eSjoerg FI->NoCfCheck = info.getNoCfCheck();
82606f32e7eSjoerg FI->Required = required;
82706f32e7eSjoerg FI->HasRegParm = info.getHasRegParm();
82806f32e7eSjoerg FI->RegParm = info.getRegParm();
82906f32e7eSjoerg FI->ArgStruct = nullptr;
83006f32e7eSjoerg FI->ArgStructAlign = 0;
83106f32e7eSjoerg FI->NumArgs = argTypes.size();
83206f32e7eSjoerg FI->HasExtParameterInfos = !paramInfos.empty();
83306f32e7eSjoerg FI->getArgsBuffer()[0].type = resultType;
83406f32e7eSjoerg for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
83506f32e7eSjoerg FI->getArgsBuffer()[i + 1].type = argTypes[i];
83606f32e7eSjoerg for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
83706f32e7eSjoerg FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
83806f32e7eSjoerg return FI;
83906f32e7eSjoerg }
84006f32e7eSjoerg
84106f32e7eSjoerg /***/
84206f32e7eSjoerg
84306f32e7eSjoerg namespace {
84406f32e7eSjoerg // ABIArgInfo::Expand implementation.
84506f32e7eSjoerg
84606f32e7eSjoerg // Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
84706f32e7eSjoerg struct TypeExpansion {
84806f32e7eSjoerg enum TypeExpansionKind {
84906f32e7eSjoerg // Elements of constant arrays are expanded recursively.
85006f32e7eSjoerg TEK_ConstantArray,
85106f32e7eSjoerg // Record fields are expanded recursively (but if record is a union, only
85206f32e7eSjoerg // the field with the largest size is expanded).
85306f32e7eSjoerg TEK_Record,
85406f32e7eSjoerg // For complex types, real and imaginary parts are expanded recursively.
85506f32e7eSjoerg TEK_Complex,
85606f32e7eSjoerg // All other types are not expandable.
85706f32e7eSjoerg TEK_None
85806f32e7eSjoerg };
85906f32e7eSjoerg
86006f32e7eSjoerg const TypeExpansionKind Kind;
86106f32e7eSjoerg
TypeExpansion__anon2a3770250211::TypeExpansion86206f32e7eSjoerg TypeExpansion(TypeExpansionKind K) : Kind(K) {}
~TypeExpansion__anon2a3770250211::TypeExpansion86306f32e7eSjoerg virtual ~TypeExpansion() {}
86406f32e7eSjoerg };
86506f32e7eSjoerg
86606f32e7eSjoerg struct ConstantArrayExpansion : TypeExpansion {
86706f32e7eSjoerg QualType EltTy;
86806f32e7eSjoerg uint64_t NumElts;
86906f32e7eSjoerg
ConstantArrayExpansion__anon2a3770250211::ConstantArrayExpansion87006f32e7eSjoerg ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
87106f32e7eSjoerg : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
classof__anon2a3770250211::ConstantArrayExpansion87206f32e7eSjoerg static bool classof(const TypeExpansion *TE) {
87306f32e7eSjoerg return TE->Kind == TEK_ConstantArray;
87406f32e7eSjoerg }
87506f32e7eSjoerg };
87606f32e7eSjoerg
87706f32e7eSjoerg struct RecordExpansion : TypeExpansion {
87806f32e7eSjoerg SmallVector<const CXXBaseSpecifier *, 1> Bases;
87906f32e7eSjoerg
88006f32e7eSjoerg SmallVector<const FieldDecl *, 1> Fields;
88106f32e7eSjoerg
RecordExpansion__anon2a3770250211::RecordExpansion88206f32e7eSjoerg RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
88306f32e7eSjoerg SmallVector<const FieldDecl *, 1> &&Fields)
88406f32e7eSjoerg : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
88506f32e7eSjoerg Fields(std::move(Fields)) {}
classof__anon2a3770250211::RecordExpansion88606f32e7eSjoerg static bool classof(const TypeExpansion *TE) {
88706f32e7eSjoerg return TE->Kind == TEK_Record;
88806f32e7eSjoerg }
88906f32e7eSjoerg };
89006f32e7eSjoerg
89106f32e7eSjoerg struct ComplexExpansion : TypeExpansion {
89206f32e7eSjoerg QualType EltTy;
89306f32e7eSjoerg
ComplexExpansion__anon2a3770250211::ComplexExpansion89406f32e7eSjoerg ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
classof__anon2a3770250211::ComplexExpansion89506f32e7eSjoerg static bool classof(const TypeExpansion *TE) {
89606f32e7eSjoerg return TE->Kind == TEK_Complex;
89706f32e7eSjoerg }
89806f32e7eSjoerg };
89906f32e7eSjoerg
90006f32e7eSjoerg struct NoExpansion : TypeExpansion {
NoExpansion__anon2a3770250211::NoExpansion90106f32e7eSjoerg NoExpansion() : TypeExpansion(TEK_None) {}
classof__anon2a3770250211::NoExpansion90206f32e7eSjoerg static bool classof(const TypeExpansion *TE) {
90306f32e7eSjoerg return TE->Kind == TEK_None;
90406f32e7eSjoerg }
90506f32e7eSjoerg };
90606f32e7eSjoerg } // namespace
90706f32e7eSjoerg
90806f32e7eSjoerg static std::unique_ptr<TypeExpansion>
getTypeExpansion(QualType Ty,const ASTContext & Context)90906f32e7eSjoerg getTypeExpansion(QualType Ty, const ASTContext &Context) {
91006f32e7eSjoerg if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
91106f32e7eSjoerg return std::make_unique<ConstantArrayExpansion>(
91206f32e7eSjoerg AT->getElementType(), AT->getSize().getZExtValue());
91306f32e7eSjoerg }
91406f32e7eSjoerg if (const RecordType *RT = Ty->getAs<RecordType>()) {
91506f32e7eSjoerg SmallVector<const CXXBaseSpecifier *, 1> Bases;
91606f32e7eSjoerg SmallVector<const FieldDecl *, 1> Fields;
91706f32e7eSjoerg const RecordDecl *RD = RT->getDecl();
91806f32e7eSjoerg assert(!RD->hasFlexibleArrayMember() &&
91906f32e7eSjoerg "Cannot expand structure with flexible array.");
92006f32e7eSjoerg if (RD->isUnion()) {
92106f32e7eSjoerg // Unions can be here only in degenerative cases - all the fields are same
92206f32e7eSjoerg // after flattening. Thus we have to use the "largest" field.
92306f32e7eSjoerg const FieldDecl *LargestFD = nullptr;
92406f32e7eSjoerg CharUnits UnionSize = CharUnits::Zero();
92506f32e7eSjoerg
92606f32e7eSjoerg for (const auto *FD : RD->fields()) {
92706f32e7eSjoerg if (FD->isZeroLengthBitField(Context))
92806f32e7eSjoerg continue;
92906f32e7eSjoerg assert(!FD->isBitField() &&
93006f32e7eSjoerg "Cannot expand structure with bit-field members.");
93106f32e7eSjoerg CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
93206f32e7eSjoerg if (UnionSize < FieldSize) {
93306f32e7eSjoerg UnionSize = FieldSize;
93406f32e7eSjoerg LargestFD = FD;
93506f32e7eSjoerg }
93606f32e7eSjoerg }
93706f32e7eSjoerg if (LargestFD)
93806f32e7eSjoerg Fields.push_back(LargestFD);
93906f32e7eSjoerg } else {
94006f32e7eSjoerg if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
94106f32e7eSjoerg assert(!CXXRD->isDynamicClass() &&
94206f32e7eSjoerg "cannot expand vtable pointers in dynamic classes");
94306f32e7eSjoerg for (const CXXBaseSpecifier &BS : CXXRD->bases())
94406f32e7eSjoerg Bases.push_back(&BS);
94506f32e7eSjoerg }
94606f32e7eSjoerg
94706f32e7eSjoerg for (const auto *FD : RD->fields()) {
94806f32e7eSjoerg if (FD->isZeroLengthBitField(Context))
94906f32e7eSjoerg continue;
95006f32e7eSjoerg assert(!FD->isBitField() &&
95106f32e7eSjoerg "Cannot expand structure with bit-field members.");
95206f32e7eSjoerg Fields.push_back(FD);
95306f32e7eSjoerg }
95406f32e7eSjoerg }
95506f32e7eSjoerg return std::make_unique<RecordExpansion>(std::move(Bases),
95606f32e7eSjoerg std::move(Fields));
95706f32e7eSjoerg }
95806f32e7eSjoerg if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
95906f32e7eSjoerg return std::make_unique<ComplexExpansion>(CT->getElementType());
96006f32e7eSjoerg }
96106f32e7eSjoerg return std::make_unique<NoExpansion>();
96206f32e7eSjoerg }
96306f32e7eSjoerg
getExpansionSize(QualType Ty,const ASTContext & Context)96406f32e7eSjoerg static int getExpansionSize(QualType Ty, const ASTContext &Context) {
96506f32e7eSjoerg auto Exp = getTypeExpansion(Ty, Context);
96606f32e7eSjoerg if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
96706f32e7eSjoerg return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
96806f32e7eSjoerg }
96906f32e7eSjoerg if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
97006f32e7eSjoerg int Res = 0;
97106f32e7eSjoerg for (auto BS : RExp->Bases)
97206f32e7eSjoerg Res += getExpansionSize(BS->getType(), Context);
97306f32e7eSjoerg for (auto FD : RExp->Fields)
97406f32e7eSjoerg Res += getExpansionSize(FD->getType(), Context);
97506f32e7eSjoerg return Res;
97606f32e7eSjoerg }
97706f32e7eSjoerg if (isa<ComplexExpansion>(Exp.get()))
97806f32e7eSjoerg return 2;
97906f32e7eSjoerg assert(isa<NoExpansion>(Exp.get()));
98006f32e7eSjoerg return 1;
98106f32e7eSjoerg }
98206f32e7eSjoerg
98306f32e7eSjoerg void
getExpandedTypes(QualType Ty,SmallVectorImpl<llvm::Type * >::iterator & TI)98406f32e7eSjoerg CodeGenTypes::getExpandedTypes(QualType Ty,
98506f32e7eSjoerg SmallVectorImpl<llvm::Type *>::iterator &TI) {
98606f32e7eSjoerg auto Exp = getTypeExpansion(Ty, Context);
98706f32e7eSjoerg if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
98806f32e7eSjoerg for (int i = 0, n = CAExp->NumElts; i < n; i++) {
98906f32e7eSjoerg getExpandedTypes(CAExp->EltTy, TI);
99006f32e7eSjoerg }
99106f32e7eSjoerg } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
99206f32e7eSjoerg for (auto BS : RExp->Bases)
99306f32e7eSjoerg getExpandedTypes(BS->getType(), TI);
99406f32e7eSjoerg for (auto FD : RExp->Fields)
99506f32e7eSjoerg getExpandedTypes(FD->getType(), TI);
99606f32e7eSjoerg } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
99706f32e7eSjoerg llvm::Type *EltTy = ConvertType(CExp->EltTy);
99806f32e7eSjoerg *TI++ = EltTy;
99906f32e7eSjoerg *TI++ = EltTy;
100006f32e7eSjoerg } else {
100106f32e7eSjoerg assert(isa<NoExpansion>(Exp.get()));
100206f32e7eSjoerg *TI++ = ConvertType(Ty);
100306f32e7eSjoerg }
100406f32e7eSjoerg }
100506f32e7eSjoerg
forConstantArrayExpansion(CodeGenFunction & CGF,ConstantArrayExpansion * CAE,Address BaseAddr,llvm::function_ref<void (Address)> Fn)100606f32e7eSjoerg static void forConstantArrayExpansion(CodeGenFunction &CGF,
100706f32e7eSjoerg ConstantArrayExpansion *CAE,
100806f32e7eSjoerg Address BaseAddr,
100906f32e7eSjoerg llvm::function_ref<void(Address)> Fn) {
101006f32e7eSjoerg CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
101106f32e7eSjoerg CharUnits EltAlign =
101206f32e7eSjoerg BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
101306f32e7eSjoerg
101406f32e7eSjoerg for (int i = 0, n = CAE->NumElts; i < n; i++) {
101506f32e7eSjoerg llvm::Value *EltAddr =
101606f32e7eSjoerg CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i);
101706f32e7eSjoerg Fn(Address(EltAddr, EltAlign));
101806f32e7eSjoerg }
101906f32e7eSjoerg }
102006f32e7eSjoerg
ExpandTypeFromArgs(QualType Ty,LValue LV,llvm::Function::arg_iterator & AI)1021*13fbcb42Sjoerg void CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
1022*13fbcb42Sjoerg llvm::Function::arg_iterator &AI) {
102306f32e7eSjoerg assert(LV.isSimple() &&
102406f32e7eSjoerg "Unexpected non-simple lvalue during struct expansion.");
102506f32e7eSjoerg
102606f32e7eSjoerg auto Exp = getTypeExpansion(Ty, getContext());
102706f32e7eSjoerg if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1028*13fbcb42Sjoerg forConstantArrayExpansion(
1029*13fbcb42Sjoerg *this, CAExp, LV.getAddress(*this), [&](Address EltAddr) {
103006f32e7eSjoerg LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
103106f32e7eSjoerg ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
103206f32e7eSjoerg });
103306f32e7eSjoerg } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1034*13fbcb42Sjoerg Address This = LV.getAddress(*this);
103506f32e7eSjoerg for (const CXXBaseSpecifier *BS : RExp->Bases) {
103606f32e7eSjoerg // Perform a single step derived-to-base conversion.
103706f32e7eSjoerg Address Base =
103806f32e7eSjoerg GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
103906f32e7eSjoerg /*NullCheckValue=*/false, SourceLocation());
104006f32e7eSjoerg LValue SubLV = MakeAddrLValue(Base, BS->getType());
104106f32e7eSjoerg
104206f32e7eSjoerg // Recurse onto bases.
104306f32e7eSjoerg ExpandTypeFromArgs(BS->getType(), SubLV, AI);
104406f32e7eSjoerg }
104506f32e7eSjoerg for (auto FD : RExp->Fields) {
104606f32e7eSjoerg // FIXME: What are the right qualifiers here?
104706f32e7eSjoerg LValue SubLV = EmitLValueForFieldInitialization(LV, FD);
104806f32e7eSjoerg ExpandTypeFromArgs(FD->getType(), SubLV, AI);
104906f32e7eSjoerg }
105006f32e7eSjoerg } else if (isa<ComplexExpansion>(Exp.get())) {
1051*13fbcb42Sjoerg auto realValue = &*AI++;
1052*13fbcb42Sjoerg auto imagValue = &*AI++;
105306f32e7eSjoerg EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
105406f32e7eSjoerg } else {
1055*13fbcb42Sjoerg // Call EmitStoreOfScalar except when the lvalue is a bitfield to emit a
1056*13fbcb42Sjoerg // primitive store.
105706f32e7eSjoerg assert(isa<NoExpansion>(Exp.get()));
1058*13fbcb42Sjoerg if (LV.isBitField())
1059*13fbcb42Sjoerg EmitStoreThroughLValue(RValue::get(&*AI++), LV);
1060*13fbcb42Sjoerg else
1061*13fbcb42Sjoerg EmitStoreOfScalar(&*AI++, LV);
106206f32e7eSjoerg }
106306f32e7eSjoerg }
106406f32e7eSjoerg
ExpandTypeToArgs(QualType Ty,CallArg Arg,llvm::FunctionType * IRFuncTy,SmallVectorImpl<llvm::Value * > & IRCallArgs,unsigned & IRCallArgPos)106506f32e7eSjoerg void CodeGenFunction::ExpandTypeToArgs(
106606f32e7eSjoerg QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
106706f32e7eSjoerg SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
106806f32e7eSjoerg auto Exp = getTypeExpansion(Ty, getContext());
106906f32e7eSjoerg if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1070*13fbcb42Sjoerg Address Addr = Arg.hasLValue() ? Arg.getKnownLValue().getAddress(*this)
107106f32e7eSjoerg : Arg.getKnownRValue().getAggregateAddress();
107206f32e7eSjoerg forConstantArrayExpansion(
107306f32e7eSjoerg *this, CAExp, Addr, [&](Address EltAddr) {
107406f32e7eSjoerg CallArg EltArg = CallArg(
107506f32e7eSjoerg convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation()),
107606f32e7eSjoerg CAExp->EltTy);
107706f32e7eSjoerg ExpandTypeToArgs(CAExp->EltTy, EltArg, IRFuncTy, IRCallArgs,
107806f32e7eSjoerg IRCallArgPos);
107906f32e7eSjoerg });
108006f32e7eSjoerg } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1081*13fbcb42Sjoerg Address This = Arg.hasLValue() ? Arg.getKnownLValue().getAddress(*this)
108206f32e7eSjoerg : Arg.getKnownRValue().getAggregateAddress();
108306f32e7eSjoerg for (const CXXBaseSpecifier *BS : RExp->Bases) {
108406f32e7eSjoerg // Perform a single step derived-to-base conversion.
108506f32e7eSjoerg Address Base =
108606f32e7eSjoerg GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
108706f32e7eSjoerg /*NullCheckValue=*/false, SourceLocation());
108806f32e7eSjoerg CallArg BaseArg = CallArg(RValue::getAggregate(Base), BS->getType());
108906f32e7eSjoerg
109006f32e7eSjoerg // Recurse onto bases.
109106f32e7eSjoerg ExpandTypeToArgs(BS->getType(), BaseArg, IRFuncTy, IRCallArgs,
109206f32e7eSjoerg IRCallArgPos);
109306f32e7eSjoerg }
109406f32e7eSjoerg
109506f32e7eSjoerg LValue LV = MakeAddrLValue(This, Ty);
109606f32e7eSjoerg for (auto FD : RExp->Fields) {
109706f32e7eSjoerg CallArg FldArg =
109806f32e7eSjoerg CallArg(EmitRValueForField(LV, FD, SourceLocation()), FD->getType());
109906f32e7eSjoerg ExpandTypeToArgs(FD->getType(), FldArg, IRFuncTy, IRCallArgs,
110006f32e7eSjoerg IRCallArgPos);
110106f32e7eSjoerg }
110206f32e7eSjoerg } else if (isa<ComplexExpansion>(Exp.get())) {
110306f32e7eSjoerg ComplexPairTy CV = Arg.getKnownRValue().getComplexVal();
110406f32e7eSjoerg IRCallArgs[IRCallArgPos++] = CV.first;
110506f32e7eSjoerg IRCallArgs[IRCallArgPos++] = CV.second;
110606f32e7eSjoerg } else {
110706f32e7eSjoerg assert(isa<NoExpansion>(Exp.get()));
110806f32e7eSjoerg auto RV = Arg.getKnownRValue();
110906f32e7eSjoerg assert(RV.isScalar() &&
111006f32e7eSjoerg "Unexpected non-scalar rvalue during struct expansion.");
111106f32e7eSjoerg
111206f32e7eSjoerg // Insert a bitcast as needed.
111306f32e7eSjoerg llvm::Value *V = RV.getScalarVal();
111406f32e7eSjoerg if (IRCallArgPos < IRFuncTy->getNumParams() &&
111506f32e7eSjoerg V->getType() != IRFuncTy->getParamType(IRCallArgPos))
111606f32e7eSjoerg V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
111706f32e7eSjoerg
111806f32e7eSjoerg IRCallArgs[IRCallArgPos++] = V;
111906f32e7eSjoerg }
112006f32e7eSjoerg }
112106f32e7eSjoerg
112206f32e7eSjoerg /// Create a temporary allocation for the purposes of coercion.
CreateTempAllocaForCoercion(CodeGenFunction & CGF,llvm::Type * Ty,CharUnits MinAlign,const Twine & Name="tmp")112306f32e7eSjoerg static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
1124*13fbcb42Sjoerg CharUnits MinAlign,
1125*13fbcb42Sjoerg const Twine &Name = "tmp") {
112606f32e7eSjoerg // Don't use an alignment that's worse than what LLVM would prefer.
112706f32e7eSjoerg auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty);
112806f32e7eSjoerg CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
112906f32e7eSjoerg
1130*13fbcb42Sjoerg return CGF.CreateTempAlloca(Ty, Align, Name + ".coerce");
113106f32e7eSjoerg }
113206f32e7eSjoerg
113306f32e7eSjoerg /// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
113406f32e7eSjoerg /// accessing some number of bytes out of it, try to gep into the struct to get
113506f32e7eSjoerg /// at its inner goodness. Dive as deep as possible without entering an element
113606f32e7eSjoerg /// with an in-memory size smaller than DstSize.
113706f32e7eSjoerg static Address
EnterStructPointerForCoercedAccess(Address SrcPtr,llvm::StructType * SrcSTy,uint64_t DstSize,CodeGenFunction & CGF)113806f32e7eSjoerg EnterStructPointerForCoercedAccess(Address SrcPtr,
113906f32e7eSjoerg llvm::StructType *SrcSTy,
114006f32e7eSjoerg uint64_t DstSize, CodeGenFunction &CGF) {
114106f32e7eSjoerg // We can't dive into a zero-element struct.
114206f32e7eSjoerg if (SrcSTy->getNumElements() == 0) return SrcPtr;
114306f32e7eSjoerg
114406f32e7eSjoerg llvm::Type *FirstElt = SrcSTy->getElementType(0);
114506f32e7eSjoerg
114606f32e7eSjoerg // If the first elt is at least as large as what we're looking for, or if the
114706f32e7eSjoerg // first element is the same size as the whole struct, we can enter it. The
114806f32e7eSjoerg // comparison must be made on the store size and not the alloca size. Using
114906f32e7eSjoerg // the alloca size may overstate the size of the load.
115006f32e7eSjoerg uint64_t FirstEltSize =
115106f32e7eSjoerg CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
115206f32e7eSjoerg if (FirstEltSize < DstSize &&
115306f32e7eSjoerg FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
115406f32e7eSjoerg return SrcPtr;
115506f32e7eSjoerg
115606f32e7eSjoerg // GEP into the first element.
115706f32e7eSjoerg SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, "coerce.dive");
115806f32e7eSjoerg
115906f32e7eSjoerg // If the first element is a struct, recurse.
116006f32e7eSjoerg llvm::Type *SrcTy = SrcPtr.getElementType();
116106f32e7eSjoerg if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
116206f32e7eSjoerg return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
116306f32e7eSjoerg
116406f32e7eSjoerg return SrcPtr;
116506f32e7eSjoerg }
116606f32e7eSjoerg
116706f32e7eSjoerg /// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
116806f32e7eSjoerg /// are either integers or pointers. This does a truncation of the value if it
116906f32e7eSjoerg /// is too large or a zero extension if it is too small.
117006f32e7eSjoerg ///
117106f32e7eSjoerg /// This behaves as if the value were coerced through memory, so on big-endian
117206f32e7eSjoerg /// targets the high bits are preserved in a truncation, while little-endian
117306f32e7eSjoerg /// targets preserve the low bits.
CoerceIntOrPtrToIntOrPtr(llvm::Value * Val,llvm::Type * Ty,CodeGenFunction & CGF)117406f32e7eSjoerg static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
117506f32e7eSjoerg llvm::Type *Ty,
117606f32e7eSjoerg CodeGenFunction &CGF) {
117706f32e7eSjoerg if (Val->getType() == Ty)
117806f32e7eSjoerg return Val;
117906f32e7eSjoerg
118006f32e7eSjoerg if (isa<llvm::PointerType>(Val->getType())) {
118106f32e7eSjoerg // If this is Pointer->Pointer avoid conversion to and from int.
118206f32e7eSjoerg if (isa<llvm::PointerType>(Ty))
118306f32e7eSjoerg return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
118406f32e7eSjoerg
118506f32e7eSjoerg // Convert the pointer to an integer so we can play with its width.
118606f32e7eSjoerg Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
118706f32e7eSjoerg }
118806f32e7eSjoerg
118906f32e7eSjoerg llvm::Type *DestIntTy = Ty;
119006f32e7eSjoerg if (isa<llvm::PointerType>(DestIntTy))
119106f32e7eSjoerg DestIntTy = CGF.IntPtrTy;
119206f32e7eSjoerg
119306f32e7eSjoerg if (Val->getType() != DestIntTy) {
119406f32e7eSjoerg const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
119506f32e7eSjoerg if (DL.isBigEndian()) {
119606f32e7eSjoerg // Preserve the high bits on big-endian targets.
119706f32e7eSjoerg // That is what memory coercion does.
119806f32e7eSjoerg uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
119906f32e7eSjoerg uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
120006f32e7eSjoerg
120106f32e7eSjoerg if (SrcSize > DstSize) {
120206f32e7eSjoerg Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
120306f32e7eSjoerg Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
120406f32e7eSjoerg } else {
120506f32e7eSjoerg Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
120606f32e7eSjoerg Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
120706f32e7eSjoerg }
120806f32e7eSjoerg } else {
120906f32e7eSjoerg // Little-endian targets preserve the low bits. No shifts required.
121006f32e7eSjoerg Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
121106f32e7eSjoerg }
121206f32e7eSjoerg }
121306f32e7eSjoerg
121406f32e7eSjoerg if (isa<llvm::PointerType>(Ty))
121506f32e7eSjoerg Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
121606f32e7eSjoerg return Val;
121706f32e7eSjoerg }
121806f32e7eSjoerg
121906f32e7eSjoerg
122006f32e7eSjoerg
122106f32e7eSjoerg /// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
122206f32e7eSjoerg /// a pointer to an object of type \arg Ty, known to be aligned to
122306f32e7eSjoerg /// \arg SrcAlign bytes.
122406f32e7eSjoerg ///
122506f32e7eSjoerg /// This safely handles the case when the src type is smaller than the
122606f32e7eSjoerg /// destination type; in this situation the values of bits which not
122706f32e7eSjoerg /// present in the src are undefined.
CreateCoercedLoad(Address Src,llvm::Type * Ty,CodeGenFunction & CGF)122806f32e7eSjoerg static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
122906f32e7eSjoerg CodeGenFunction &CGF) {
123006f32e7eSjoerg llvm::Type *SrcTy = Src.getElementType();
123106f32e7eSjoerg
123206f32e7eSjoerg // If SrcTy and Ty are the same, just do a load.
123306f32e7eSjoerg if (SrcTy == Ty)
123406f32e7eSjoerg return CGF.Builder.CreateLoad(Src);
123506f32e7eSjoerg
1236*13fbcb42Sjoerg llvm::TypeSize DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
123706f32e7eSjoerg
123806f32e7eSjoerg if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
1239*13fbcb42Sjoerg Src = EnterStructPointerForCoercedAccess(Src, SrcSTy,
1240*13fbcb42Sjoerg DstSize.getFixedSize(), CGF);
1241*13fbcb42Sjoerg SrcTy = Src.getElementType();
124206f32e7eSjoerg }
124306f32e7eSjoerg
1244*13fbcb42Sjoerg llvm::TypeSize SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
124506f32e7eSjoerg
124606f32e7eSjoerg // If the source and destination are integer or pointer types, just do an
124706f32e7eSjoerg // extension or truncation to the desired type.
124806f32e7eSjoerg if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
124906f32e7eSjoerg (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
125006f32e7eSjoerg llvm::Value *Load = CGF.Builder.CreateLoad(Src);
125106f32e7eSjoerg return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
125206f32e7eSjoerg }
125306f32e7eSjoerg
125406f32e7eSjoerg // If load is legal, just bitcast the src pointer.
1255*13fbcb42Sjoerg if (!SrcSize.isScalable() && !DstSize.isScalable() &&
1256*13fbcb42Sjoerg SrcSize.getFixedSize() >= DstSize.getFixedSize()) {
125706f32e7eSjoerg // Generally SrcSize is never greater than DstSize, since this means we are
125806f32e7eSjoerg // losing bits. However, this can happen in cases where the structure has
125906f32e7eSjoerg // additional padding, for example due to a user specified alignment.
126006f32e7eSjoerg //
126106f32e7eSjoerg // FIXME: Assert that we aren't truncating non-padding bits when have access
126206f32e7eSjoerg // to that information.
126306f32e7eSjoerg Src = CGF.Builder.CreateBitCast(Src,
126406f32e7eSjoerg Ty->getPointerTo(Src.getAddressSpace()));
126506f32e7eSjoerg return CGF.Builder.CreateLoad(Src);
126606f32e7eSjoerg }
126706f32e7eSjoerg
1268*13fbcb42Sjoerg // If coercing a fixed vector to a scalable vector for ABI compatibility, and
1269*13fbcb42Sjoerg // the types match, use the llvm.experimental.vector.insert intrinsic to
1270*13fbcb42Sjoerg // perform the conversion.
1271*13fbcb42Sjoerg if (auto *ScalableDst = dyn_cast<llvm::ScalableVectorType>(Ty)) {
1272*13fbcb42Sjoerg if (auto *FixedSrc = dyn_cast<llvm::FixedVectorType>(SrcTy)) {
1273*13fbcb42Sjoerg if (ScalableDst->getElementType() == FixedSrc->getElementType()) {
1274*13fbcb42Sjoerg auto *Load = CGF.Builder.CreateLoad(Src);
1275*13fbcb42Sjoerg auto *UndefVec = llvm::UndefValue::get(ScalableDst);
1276*13fbcb42Sjoerg auto *Zero = llvm::Constant::getNullValue(CGF.CGM.Int64Ty);
1277*13fbcb42Sjoerg return CGF.Builder.CreateInsertVector(ScalableDst, UndefVec, Load, Zero,
1278*13fbcb42Sjoerg "castScalableSve");
1279*13fbcb42Sjoerg }
1280*13fbcb42Sjoerg }
1281*13fbcb42Sjoerg }
1282*13fbcb42Sjoerg
128306f32e7eSjoerg // Otherwise do coercion through memory. This is stupid, but simple.
1284*13fbcb42Sjoerg Address Tmp =
1285*13fbcb42Sjoerg CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment(), Src.getName());
1286*13fbcb42Sjoerg CGF.Builder.CreateMemCpy(
1287*13fbcb42Sjoerg Tmp.getPointer(), Tmp.getAlignment().getAsAlign(), Src.getPointer(),
1288*13fbcb42Sjoerg Src.getAlignment().getAsAlign(),
1289*13fbcb42Sjoerg llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize.getKnownMinSize()));
129006f32e7eSjoerg return CGF.Builder.CreateLoad(Tmp);
129106f32e7eSjoerg }
129206f32e7eSjoerg
129306f32e7eSjoerg // Function to store a first-class aggregate into memory. We prefer to
129406f32e7eSjoerg // store the elements rather than the aggregate to be more friendly to
129506f32e7eSjoerg // fast-isel.
129606f32e7eSjoerg // FIXME: Do we need to recurse here?
EmitAggregateStore(llvm::Value * Val,Address Dest,bool DestIsVolatile)1297*13fbcb42Sjoerg void CodeGenFunction::EmitAggregateStore(llvm::Value *Val, Address Dest,
1298*13fbcb42Sjoerg bool DestIsVolatile) {
129906f32e7eSjoerg // Prefer scalar stores to first-class aggregate stores.
1300*13fbcb42Sjoerg if (llvm::StructType *STy = dyn_cast<llvm::StructType>(Val->getType())) {
130106f32e7eSjoerg for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1302*13fbcb42Sjoerg Address EltPtr = Builder.CreateStructGEP(Dest, i);
1303*13fbcb42Sjoerg llvm::Value *Elt = Builder.CreateExtractValue(Val, i);
1304*13fbcb42Sjoerg Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
130506f32e7eSjoerg }
130606f32e7eSjoerg } else {
1307*13fbcb42Sjoerg Builder.CreateStore(Val, Dest, DestIsVolatile);
130806f32e7eSjoerg }
130906f32e7eSjoerg }
131006f32e7eSjoerg
131106f32e7eSjoerg /// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
131206f32e7eSjoerg /// where the source and destination may have different types. The
131306f32e7eSjoerg /// destination is known to be aligned to \arg DstAlign bytes.
131406f32e7eSjoerg ///
131506f32e7eSjoerg /// This safely handles the case when the src type is larger than the
131606f32e7eSjoerg /// destination type; the upper bits of the src will be lost.
CreateCoercedStore(llvm::Value * Src,Address Dst,bool DstIsVolatile,CodeGenFunction & CGF)131706f32e7eSjoerg static void CreateCoercedStore(llvm::Value *Src,
131806f32e7eSjoerg Address Dst,
131906f32e7eSjoerg bool DstIsVolatile,
132006f32e7eSjoerg CodeGenFunction &CGF) {
132106f32e7eSjoerg llvm::Type *SrcTy = Src->getType();
1322*13fbcb42Sjoerg llvm::Type *DstTy = Dst.getElementType();
132306f32e7eSjoerg if (SrcTy == DstTy) {
132406f32e7eSjoerg CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
132506f32e7eSjoerg return;
132606f32e7eSjoerg }
132706f32e7eSjoerg
1328*13fbcb42Sjoerg llvm::TypeSize SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
132906f32e7eSjoerg
133006f32e7eSjoerg if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
1331*13fbcb42Sjoerg Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy,
1332*13fbcb42Sjoerg SrcSize.getFixedSize(), CGF);
1333*13fbcb42Sjoerg DstTy = Dst.getElementType();
1334*13fbcb42Sjoerg }
1335*13fbcb42Sjoerg
1336*13fbcb42Sjoerg llvm::PointerType *SrcPtrTy = llvm::dyn_cast<llvm::PointerType>(SrcTy);
1337*13fbcb42Sjoerg llvm::PointerType *DstPtrTy = llvm::dyn_cast<llvm::PointerType>(DstTy);
1338*13fbcb42Sjoerg if (SrcPtrTy && DstPtrTy &&
1339*13fbcb42Sjoerg SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace()) {
1340*13fbcb42Sjoerg Src = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy);
1341*13fbcb42Sjoerg CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1342*13fbcb42Sjoerg return;
134306f32e7eSjoerg }
134406f32e7eSjoerg
134506f32e7eSjoerg // If the source and destination are integer or pointer types, just do an
134606f32e7eSjoerg // extension or truncation to the desired type.
134706f32e7eSjoerg if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
134806f32e7eSjoerg (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
134906f32e7eSjoerg Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
135006f32e7eSjoerg CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
135106f32e7eSjoerg return;
135206f32e7eSjoerg }
135306f32e7eSjoerg
1354*13fbcb42Sjoerg llvm::TypeSize DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
135506f32e7eSjoerg
135606f32e7eSjoerg // If store is legal, just bitcast the src pointer.
1357*13fbcb42Sjoerg if (isa<llvm::ScalableVectorType>(SrcTy) ||
1358*13fbcb42Sjoerg isa<llvm::ScalableVectorType>(DstTy) ||
1359*13fbcb42Sjoerg SrcSize.getFixedSize() <= DstSize.getFixedSize()) {
136006f32e7eSjoerg Dst = CGF.Builder.CreateElementBitCast(Dst, SrcTy);
1361*13fbcb42Sjoerg CGF.EmitAggregateStore(Src, Dst, DstIsVolatile);
136206f32e7eSjoerg } else {
136306f32e7eSjoerg // Otherwise do coercion through memory. This is stupid, but
136406f32e7eSjoerg // simple.
136506f32e7eSjoerg
136606f32e7eSjoerg // Generally SrcSize is never greater than DstSize, since this means we are
136706f32e7eSjoerg // losing bits. However, this can happen in cases where the structure has
136806f32e7eSjoerg // additional padding, for example due to a user specified alignment.
136906f32e7eSjoerg //
137006f32e7eSjoerg // FIXME: Assert that we aren't truncating non-padding bits when have access
137106f32e7eSjoerg // to that information.
137206f32e7eSjoerg Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
137306f32e7eSjoerg CGF.Builder.CreateStore(Src, Tmp);
1374*13fbcb42Sjoerg CGF.Builder.CreateMemCpy(
1375*13fbcb42Sjoerg Dst.getPointer(), Dst.getAlignment().getAsAlign(), Tmp.getPointer(),
1376*13fbcb42Sjoerg Tmp.getAlignment().getAsAlign(),
1377*13fbcb42Sjoerg llvm::ConstantInt::get(CGF.IntPtrTy, DstSize.getFixedSize()));
137806f32e7eSjoerg }
137906f32e7eSjoerg }
138006f32e7eSjoerg
emitAddressAtOffset(CodeGenFunction & CGF,Address addr,const ABIArgInfo & info)138106f32e7eSjoerg static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
138206f32e7eSjoerg const ABIArgInfo &info) {
138306f32e7eSjoerg if (unsigned offset = info.getDirectOffset()) {
138406f32e7eSjoerg addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
138506f32e7eSjoerg addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
138606f32e7eSjoerg CharUnits::fromQuantity(offset));
138706f32e7eSjoerg addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
138806f32e7eSjoerg }
138906f32e7eSjoerg return addr;
139006f32e7eSjoerg }
139106f32e7eSjoerg
139206f32e7eSjoerg namespace {
139306f32e7eSjoerg
139406f32e7eSjoerg /// Encapsulates information about the way function arguments from
139506f32e7eSjoerg /// CGFunctionInfo should be passed to actual LLVM IR function.
139606f32e7eSjoerg class ClangToLLVMArgMapping {
139706f32e7eSjoerg static const unsigned InvalidIndex = ~0U;
139806f32e7eSjoerg unsigned InallocaArgNo;
139906f32e7eSjoerg unsigned SRetArgNo;
140006f32e7eSjoerg unsigned TotalIRArgs;
140106f32e7eSjoerg
140206f32e7eSjoerg /// Arguments of LLVM IR function corresponding to single Clang argument.
140306f32e7eSjoerg struct IRArgs {
140406f32e7eSjoerg unsigned PaddingArgIndex;
140506f32e7eSjoerg // Argument is expanded to IR arguments at positions
140606f32e7eSjoerg // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
140706f32e7eSjoerg unsigned FirstArgIndex;
140806f32e7eSjoerg unsigned NumberOfArgs;
140906f32e7eSjoerg
IRArgs__anon2a3770250511::ClangToLLVMArgMapping::IRArgs141006f32e7eSjoerg IRArgs()
141106f32e7eSjoerg : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
141206f32e7eSjoerg NumberOfArgs(0) {}
141306f32e7eSjoerg };
141406f32e7eSjoerg
141506f32e7eSjoerg SmallVector<IRArgs, 8> ArgInfo;
141606f32e7eSjoerg
141706f32e7eSjoerg public:
ClangToLLVMArgMapping(const ASTContext & Context,const CGFunctionInfo & FI,bool OnlyRequiredArgs=false)141806f32e7eSjoerg ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
141906f32e7eSjoerg bool OnlyRequiredArgs = false)
142006f32e7eSjoerg : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
142106f32e7eSjoerg ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
142206f32e7eSjoerg construct(Context, FI, OnlyRequiredArgs);
142306f32e7eSjoerg }
142406f32e7eSjoerg
hasInallocaArg() const142506f32e7eSjoerg bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
getInallocaArgNo() const142606f32e7eSjoerg unsigned getInallocaArgNo() const {
142706f32e7eSjoerg assert(hasInallocaArg());
142806f32e7eSjoerg return InallocaArgNo;
142906f32e7eSjoerg }
143006f32e7eSjoerg
hasSRetArg() const143106f32e7eSjoerg bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
getSRetArgNo() const143206f32e7eSjoerg unsigned getSRetArgNo() const {
143306f32e7eSjoerg assert(hasSRetArg());
143406f32e7eSjoerg return SRetArgNo;
143506f32e7eSjoerg }
143606f32e7eSjoerg
totalIRArgs() const143706f32e7eSjoerg unsigned totalIRArgs() const { return TotalIRArgs; }
143806f32e7eSjoerg
hasPaddingArg(unsigned ArgNo) const143906f32e7eSjoerg bool hasPaddingArg(unsigned ArgNo) const {
144006f32e7eSjoerg assert(ArgNo < ArgInfo.size());
144106f32e7eSjoerg return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
144206f32e7eSjoerg }
getPaddingArgNo(unsigned ArgNo) const144306f32e7eSjoerg unsigned getPaddingArgNo(unsigned ArgNo) const {
144406f32e7eSjoerg assert(hasPaddingArg(ArgNo));
144506f32e7eSjoerg return ArgInfo[ArgNo].PaddingArgIndex;
144606f32e7eSjoerg }
144706f32e7eSjoerg
144806f32e7eSjoerg /// Returns index of first IR argument corresponding to ArgNo, and their
144906f32e7eSjoerg /// quantity.
getIRArgs(unsigned ArgNo) const145006f32e7eSjoerg std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
145106f32e7eSjoerg assert(ArgNo < ArgInfo.size());
145206f32e7eSjoerg return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
145306f32e7eSjoerg ArgInfo[ArgNo].NumberOfArgs);
145406f32e7eSjoerg }
145506f32e7eSjoerg
145606f32e7eSjoerg private:
145706f32e7eSjoerg void construct(const ASTContext &Context, const CGFunctionInfo &FI,
145806f32e7eSjoerg bool OnlyRequiredArgs);
145906f32e7eSjoerg };
146006f32e7eSjoerg
construct(const ASTContext & Context,const CGFunctionInfo & FI,bool OnlyRequiredArgs)146106f32e7eSjoerg void ClangToLLVMArgMapping::construct(const ASTContext &Context,
146206f32e7eSjoerg const CGFunctionInfo &FI,
146306f32e7eSjoerg bool OnlyRequiredArgs) {
146406f32e7eSjoerg unsigned IRArgNo = 0;
146506f32e7eSjoerg bool SwapThisWithSRet = false;
146606f32e7eSjoerg const ABIArgInfo &RetAI = FI.getReturnInfo();
146706f32e7eSjoerg
146806f32e7eSjoerg if (RetAI.getKind() == ABIArgInfo::Indirect) {
146906f32e7eSjoerg SwapThisWithSRet = RetAI.isSRetAfterThis();
147006f32e7eSjoerg SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
147106f32e7eSjoerg }
147206f32e7eSjoerg
147306f32e7eSjoerg unsigned ArgNo = 0;
147406f32e7eSjoerg unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
147506f32e7eSjoerg for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
147606f32e7eSjoerg ++I, ++ArgNo) {
147706f32e7eSjoerg assert(I != FI.arg_end());
147806f32e7eSjoerg QualType ArgType = I->type;
147906f32e7eSjoerg const ABIArgInfo &AI = I->info;
148006f32e7eSjoerg // Collect data about IR arguments corresponding to Clang argument ArgNo.
148106f32e7eSjoerg auto &IRArgs = ArgInfo[ArgNo];
148206f32e7eSjoerg
148306f32e7eSjoerg if (AI.getPaddingType())
148406f32e7eSjoerg IRArgs.PaddingArgIndex = IRArgNo++;
148506f32e7eSjoerg
148606f32e7eSjoerg switch (AI.getKind()) {
148706f32e7eSjoerg case ABIArgInfo::Extend:
148806f32e7eSjoerg case ABIArgInfo::Direct: {
148906f32e7eSjoerg // FIXME: handle sseregparm someday...
149006f32e7eSjoerg llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
149106f32e7eSjoerg if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
149206f32e7eSjoerg IRArgs.NumberOfArgs = STy->getNumElements();
149306f32e7eSjoerg } else {
149406f32e7eSjoerg IRArgs.NumberOfArgs = 1;
149506f32e7eSjoerg }
149606f32e7eSjoerg break;
149706f32e7eSjoerg }
149806f32e7eSjoerg case ABIArgInfo::Indirect:
1499*13fbcb42Sjoerg case ABIArgInfo::IndirectAliased:
150006f32e7eSjoerg IRArgs.NumberOfArgs = 1;
150106f32e7eSjoerg break;
150206f32e7eSjoerg case ABIArgInfo::Ignore:
150306f32e7eSjoerg case ABIArgInfo::InAlloca:
150406f32e7eSjoerg // ignore and inalloca doesn't have matching LLVM parameters.
150506f32e7eSjoerg IRArgs.NumberOfArgs = 0;
150606f32e7eSjoerg break;
150706f32e7eSjoerg case ABIArgInfo::CoerceAndExpand:
150806f32e7eSjoerg IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
150906f32e7eSjoerg break;
151006f32e7eSjoerg case ABIArgInfo::Expand:
151106f32e7eSjoerg IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
151206f32e7eSjoerg break;
151306f32e7eSjoerg }
151406f32e7eSjoerg
151506f32e7eSjoerg if (IRArgs.NumberOfArgs > 0) {
151606f32e7eSjoerg IRArgs.FirstArgIndex = IRArgNo;
151706f32e7eSjoerg IRArgNo += IRArgs.NumberOfArgs;
151806f32e7eSjoerg }
151906f32e7eSjoerg
152006f32e7eSjoerg // Skip over the sret parameter when it comes second. We already handled it
152106f32e7eSjoerg // above.
152206f32e7eSjoerg if (IRArgNo == 1 && SwapThisWithSRet)
152306f32e7eSjoerg IRArgNo++;
152406f32e7eSjoerg }
152506f32e7eSjoerg assert(ArgNo == ArgInfo.size());
152606f32e7eSjoerg
152706f32e7eSjoerg if (FI.usesInAlloca())
152806f32e7eSjoerg InallocaArgNo = IRArgNo++;
152906f32e7eSjoerg
153006f32e7eSjoerg TotalIRArgs = IRArgNo;
153106f32e7eSjoerg }
153206f32e7eSjoerg } // namespace
153306f32e7eSjoerg
153406f32e7eSjoerg /***/
153506f32e7eSjoerg
ReturnTypeUsesSRet(const CGFunctionInfo & FI)153606f32e7eSjoerg bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
153706f32e7eSjoerg const auto &RI = FI.getReturnInfo();
153806f32e7eSjoerg return RI.isIndirect() || (RI.isInAlloca() && RI.getInAllocaSRet());
153906f32e7eSjoerg }
154006f32e7eSjoerg
ReturnSlotInterferesWithArgs(const CGFunctionInfo & FI)154106f32e7eSjoerg bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
154206f32e7eSjoerg return ReturnTypeUsesSRet(FI) &&
154306f32e7eSjoerg getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
154406f32e7eSjoerg }
154506f32e7eSjoerg
ReturnTypeUsesFPRet(QualType ResultType)154606f32e7eSjoerg bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
154706f32e7eSjoerg if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
154806f32e7eSjoerg switch (BT->getKind()) {
154906f32e7eSjoerg default:
155006f32e7eSjoerg return false;
155106f32e7eSjoerg case BuiltinType::Float:
155206f32e7eSjoerg return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
155306f32e7eSjoerg case BuiltinType::Double:
155406f32e7eSjoerg return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
155506f32e7eSjoerg case BuiltinType::LongDouble:
155606f32e7eSjoerg return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
155706f32e7eSjoerg }
155806f32e7eSjoerg }
155906f32e7eSjoerg
156006f32e7eSjoerg return false;
156106f32e7eSjoerg }
156206f32e7eSjoerg
ReturnTypeUsesFP2Ret(QualType ResultType)156306f32e7eSjoerg bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
156406f32e7eSjoerg if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
156506f32e7eSjoerg if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
156606f32e7eSjoerg if (BT->getKind() == BuiltinType::LongDouble)
156706f32e7eSjoerg return getTarget().useObjCFP2RetForComplexLongDouble();
156806f32e7eSjoerg }
156906f32e7eSjoerg }
157006f32e7eSjoerg
157106f32e7eSjoerg return false;
157206f32e7eSjoerg }
157306f32e7eSjoerg
GetFunctionType(GlobalDecl GD)157406f32e7eSjoerg llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
157506f32e7eSjoerg const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
157606f32e7eSjoerg return GetFunctionType(FI);
157706f32e7eSjoerg }
157806f32e7eSjoerg
157906f32e7eSjoerg llvm::FunctionType *
GetFunctionType(const CGFunctionInfo & FI)158006f32e7eSjoerg CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
158106f32e7eSjoerg
158206f32e7eSjoerg bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
158306f32e7eSjoerg (void)Inserted;
158406f32e7eSjoerg assert(Inserted && "Recursively being processed?");
158506f32e7eSjoerg
158606f32e7eSjoerg llvm::Type *resultType = nullptr;
158706f32e7eSjoerg const ABIArgInfo &retAI = FI.getReturnInfo();
158806f32e7eSjoerg switch (retAI.getKind()) {
158906f32e7eSjoerg case ABIArgInfo::Expand:
1590*13fbcb42Sjoerg case ABIArgInfo::IndirectAliased:
159106f32e7eSjoerg llvm_unreachable("Invalid ABI kind for return argument");
159206f32e7eSjoerg
159306f32e7eSjoerg case ABIArgInfo::Extend:
159406f32e7eSjoerg case ABIArgInfo::Direct:
159506f32e7eSjoerg resultType = retAI.getCoerceToType();
159606f32e7eSjoerg break;
159706f32e7eSjoerg
159806f32e7eSjoerg case ABIArgInfo::InAlloca:
159906f32e7eSjoerg if (retAI.getInAllocaSRet()) {
160006f32e7eSjoerg // sret things on win32 aren't void, they return the sret pointer.
160106f32e7eSjoerg QualType ret = FI.getReturnType();
160206f32e7eSjoerg llvm::Type *ty = ConvertType(ret);
160306f32e7eSjoerg unsigned addressSpace = Context.getTargetAddressSpace(ret);
160406f32e7eSjoerg resultType = llvm::PointerType::get(ty, addressSpace);
160506f32e7eSjoerg } else {
160606f32e7eSjoerg resultType = llvm::Type::getVoidTy(getLLVMContext());
160706f32e7eSjoerg }
160806f32e7eSjoerg break;
160906f32e7eSjoerg
161006f32e7eSjoerg case ABIArgInfo::Indirect:
161106f32e7eSjoerg case ABIArgInfo::Ignore:
161206f32e7eSjoerg resultType = llvm::Type::getVoidTy(getLLVMContext());
161306f32e7eSjoerg break;
161406f32e7eSjoerg
161506f32e7eSjoerg case ABIArgInfo::CoerceAndExpand:
161606f32e7eSjoerg resultType = retAI.getUnpaddedCoerceAndExpandType();
161706f32e7eSjoerg break;
161806f32e7eSjoerg }
161906f32e7eSjoerg
162006f32e7eSjoerg ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
162106f32e7eSjoerg SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
162206f32e7eSjoerg
162306f32e7eSjoerg // Add type for sret argument.
162406f32e7eSjoerg if (IRFunctionArgs.hasSRetArg()) {
162506f32e7eSjoerg QualType Ret = FI.getReturnType();
162606f32e7eSjoerg llvm::Type *Ty = ConvertType(Ret);
162706f32e7eSjoerg unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
162806f32e7eSjoerg ArgTypes[IRFunctionArgs.getSRetArgNo()] =
162906f32e7eSjoerg llvm::PointerType::get(Ty, AddressSpace);
163006f32e7eSjoerg }
163106f32e7eSjoerg
163206f32e7eSjoerg // Add type for inalloca argument.
163306f32e7eSjoerg if (IRFunctionArgs.hasInallocaArg()) {
163406f32e7eSjoerg auto ArgStruct = FI.getArgStruct();
163506f32e7eSjoerg assert(ArgStruct);
163606f32e7eSjoerg ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
163706f32e7eSjoerg }
163806f32e7eSjoerg
163906f32e7eSjoerg // Add in all of the required arguments.
164006f32e7eSjoerg unsigned ArgNo = 0;
164106f32e7eSjoerg CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
164206f32e7eSjoerg ie = it + FI.getNumRequiredArgs();
164306f32e7eSjoerg for (; it != ie; ++it, ++ArgNo) {
164406f32e7eSjoerg const ABIArgInfo &ArgInfo = it->info;
164506f32e7eSjoerg
164606f32e7eSjoerg // Insert a padding type to ensure proper alignment.
164706f32e7eSjoerg if (IRFunctionArgs.hasPaddingArg(ArgNo))
164806f32e7eSjoerg ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
164906f32e7eSjoerg ArgInfo.getPaddingType();
165006f32e7eSjoerg
165106f32e7eSjoerg unsigned FirstIRArg, NumIRArgs;
165206f32e7eSjoerg std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
165306f32e7eSjoerg
165406f32e7eSjoerg switch (ArgInfo.getKind()) {
165506f32e7eSjoerg case ABIArgInfo::Ignore:
165606f32e7eSjoerg case ABIArgInfo::InAlloca:
165706f32e7eSjoerg assert(NumIRArgs == 0);
165806f32e7eSjoerg break;
165906f32e7eSjoerg
166006f32e7eSjoerg case ABIArgInfo::Indirect: {
166106f32e7eSjoerg assert(NumIRArgs == 1);
166206f32e7eSjoerg // indirect arguments are always on the stack, which is alloca addr space.
166306f32e7eSjoerg llvm::Type *LTy = ConvertTypeForMem(it->type);
166406f32e7eSjoerg ArgTypes[FirstIRArg] = LTy->getPointerTo(
166506f32e7eSjoerg CGM.getDataLayout().getAllocaAddrSpace());
166606f32e7eSjoerg break;
166706f32e7eSjoerg }
1668*13fbcb42Sjoerg case ABIArgInfo::IndirectAliased: {
1669*13fbcb42Sjoerg assert(NumIRArgs == 1);
1670*13fbcb42Sjoerg llvm::Type *LTy = ConvertTypeForMem(it->type);
1671*13fbcb42Sjoerg ArgTypes[FirstIRArg] = LTy->getPointerTo(ArgInfo.getIndirectAddrSpace());
1672*13fbcb42Sjoerg break;
1673*13fbcb42Sjoerg }
167406f32e7eSjoerg case ABIArgInfo::Extend:
167506f32e7eSjoerg case ABIArgInfo::Direct: {
167606f32e7eSjoerg // Fast-isel and the optimizer generally like scalar values better than
167706f32e7eSjoerg // FCAs, so we flatten them if this is safe to do for this argument.
167806f32e7eSjoerg llvm::Type *argType = ArgInfo.getCoerceToType();
167906f32e7eSjoerg llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
168006f32e7eSjoerg if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
168106f32e7eSjoerg assert(NumIRArgs == st->getNumElements());
168206f32e7eSjoerg for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
168306f32e7eSjoerg ArgTypes[FirstIRArg + i] = st->getElementType(i);
168406f32e7eSjoerg } else {
168506f32e7eSjoerg assert(NumIRArgs == 1);
168606f32e7eSjoerg ArgTypes[FirstIRArg] = argType;
168706f32e7eSjoerg }
168806f32e7eSjoerg break;
168906f32e7eSjoerg }
169006f32e7eSjoerg
169106f32e7eSjoerg case ABIArgInfo::CoerceAndExpand: {
169206f32e7eSjoerg auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
169306f32e7eSjoerg for (auto EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
169406f32e7eSjoerg *ArgTypesIter++ = EltTy;
169506f32e7eSjoerg }
169606f32e7eSjoerg assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
169706f32e7eSjoerg break;
169806f32e7eSjoerg }
169906f32e7eSjoerg
170006f32e7eSjoerg case ABIArgInfo::Expand:
170106f32e7eSjoerg auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
170206f32e7eSjoerg getExpandedTypes(it->type, ArgTypesIter);
170306f32e7eSjoerg assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
170406f32e7eSjoerg break;
170506f32e7eSjoerg }
170606f32e7eSjoerg }
170706f32e7eSjoerg
170806f32e7eSjoerg bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
170906f32e7eSjoerg assert(Erased && "Not in set?");
171006f32e7eSjoerg
171106f32e7eSjoerg return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
171206f32e7eSjoerg }
171306f32e7eSjoerg
GetFunctionTypeForVTable(GlobalDecl GD)171406f32e7eSjoerg llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
171506f32e7eSjoerg const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
171606f32e7eSjoerg const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
171706f32e7eSjoerg
171806f32e7eSjoerg if (!isFuncTypeConvertible(FPT))
171906f32e7eSjoerg return llvm::StructType::get(getLLVMContext());
172006f32e7eSjoerg
172106f32e7eSjoerg return GetFunctionType(GD);
172206f32e7eSjoerg }
172306f32e7eSjoerg
AddAttributesFromFunctionProtoType(ASTContext & Ctx,llvm::AttrBuilder & FuncAttrs,const FunctionProtoType * FPT)172406f32e7eSjoerg static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
172506f32e7eSjoerg llvm::AttrBuilder &FuncAttrs,
172606f32e7eSjoerg const FunctionProtoType *FPT) {
172706f32e7eSjoerg if (!FPT)
172806f32e7eSjoerg return;
172906f32e7eSjoerg
173006f32e7eSjoerg if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
173106f32e7eSjoerg FPT->isNothrow())
173206f32e7eSjoerg FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
173306f32e7eSjoerg }
173406f32e7eSjoerg
MayDropFunctionReturn(const ASTContext & Context,QualType ReturnType)1735*13fbcb42Sjoerg bool CodeGenModule::MayDropFunctionReturn(const ASTContext &Context,
1736*13fbcb42Sjoerg QualType ReturnType) {
1737*13fbcb42Sjoerg // We can't just discard the return value for a record type with a
1738*13fbcb42Sjoerg // complex destructor or a non-trivially copyable type.
1739*13fbcb42Sjoerg if (const RecordType *RT =
1740*13fbcb42Sjoerg ReturnType.getCanonicalType()->getAs<RecordType>()) {
1741*13fbcb42Sjoerg if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1742*13fbcb42Sjoerg return ClassDecl->hasTrivialDestructor();
1743*13fbcb42Sjoerg }
1744*13fbcb42Sjoerg return ReturnType.isTriviallyCopyableType(Context);
1745*13fbcb42Sjoerg }
1746*13fbcb42Sjoerg
getDefaultFunctionAttributes(StringRef Name,bool HasOptnone,bool AttrOnCallSite,llvm::AttrBuilder & FuncAttrs)1747*13fbcb42Sjoerg void CodeGenModule::getDefaultFunctionAttributes(StringRef Name,
1748*13fbcb42Sjoerg bool HasOptnone,
174906f32e7eSjoerg bool AttrOnCallSite,
175006f32e7eSjoerg llvm::AttrBuilder &FuncAttrs) {
175106f32e7eSjoerg // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
175206f32e7eSjoerg if (!HasOptnone) {
175306f32e7eSjoerg if (CodeGenOpts.OptimizeSize)
175406f32e7eSjoerg FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
175506f32e7eSjoerg if (CodeGenOpts.OptimizeSize == 2)
175606f32e7eSjoerg FuncAttrs.addAttribute(llvm::Attribute::MinSize);
175706f32e7eSjoerg }
175806f32e7eSjoerg
175906f32e7eSjoerg if (CodeGenOpts.DisableRedZone)
176006f32e7eSjoerg FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
176106f32e7eSjoerg if (CodeGenOpts.IndirectTlsSegRefs)
176206f32e7eSjoerg FuncAttrs.addAttribute("indirect-tls-seg-refs");
176306f32e7eSjoerg if (CodeGenOpts.NoImplicitFloat)
176406f32e7eSjoerg FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
176506f32e7eSjoerg
176606f32e7eSjoerg if (AttrOnCallSite) {
176706f32e7eSjoerg // Attributes that should go on the call site only.
1768*13fbcb42Sjoerg if (!CodeGenOpts.SimplifyLibCalls || LangOpts.isNoBuiltinFunc(Name))
176906f32e7eSjoerg FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
177006f32e7eSjoerg if (!CodeGenOpts.TrapFuncName.empty())
177106f32e7eSjoerg FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
177206f32e7eSjoerg } else {
177306f32e7eSjoerg StringRef FpKind;
177406f32e7eSjoerg switch (CodeGenOpts.getFramePointer()) {
177506f32e7eSjoerg case CodeGenOptions::FramePointerKind::None:
177606f32e7eSjoerg FpKind = "none";
177706f32e7eSjoerg break;
177806f32e7eSjoerg case CodeGenOptions::FramePointerKind::NonLeaf:
177906f32e7eSjoerg FpKind = "non-leaf";
178006f32e7eSjoerg break;
178106f32e7eSjoerg case CodeGenOptions::FramePointerKind::All:
178206f32e7eSjoerg FpKind = "all";
178306f32e7eSjoerg break;
178406f32e7eSjoerg }
178506f32e7eSjoerg FuncAttrs.addAttribute("frame-pointer", FpKind);
178606f32e7eSjoerg
1787*13fbcb42Sjoerg if (CodeGenOpts.LessPreciseFPMAD)
1788*13fbcb42Sjoerg FuncAttrs.addAttribute("less-precise-fpmad", "true");
178906f32e7eSjoerg
179006f32e7eSjoerg if (CodeGenOpts.NullPointerIsValid)
1791*13fbcb42Sjoerg FuncAttrs.addAttribute(llvm::Attribute::NullPointerIsValid);
179206f32e7eSjoerg
1793*13fbcb42Sjoerg if (CodeGenOpts.FPDenormalMode != llvm::DenormalMode::getIEEE())
1794*13fbcb42Sjoerg FuncAttrs.addAttribute("denormal-fp-math",
1795*13fbcb42Sjoerg CodeGenOpts.FPDenormalMode.str());
1796*13fbcb42Sjoerg if (CodeGenOpts.FP32DenormalMode != CodeGenOpts.FPDenormalMode) {
1797*13fbcb42Sjoerg FuncAttrs.addAttribute(
1798*13fbcb42Sjoerg "denormal-fp-math-f32",
1799*13fbcb42Sjoerg CodeGenOpts.FP32DenormalMode.str());
1800*13fbcb42Sjoerg }
1801*13fbcb42Sjoerg
1802*13fbcb42Sjoerg if (LangOpts.getFPExceptionMode() == LangOptions::FPE_Ignore)
1803*13fbcb42Sjoerg FuncAttrs.addAttribute("no-trapping-math", "true");
180406f32e7eSjoerg
180506f32e7eSjoerg // Strict (compliant) code is the default, so only add this attribute to
180606f32e7eSjoerg // indicate that we are trying to workaround a problem case.
180706f32e7eSjoerg if (!CodeGenOpts.StrictFloatCastOverflow)
180806f32e7eSjoerg FuncAttrs.addAttribute("strict-float-cast-overflow", "false");
180906f32e7eSjoerg
181006f32e7eSjoerg // TODO: Are these all needed?
181106f32e7eSjoerg // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags.
1812*13fbcb42Sjoerg if (LangOpts.NoHonorInfs)
1813*13fbcb42Sjoerg FuncAttrs.addAttribute("no-infs-fp-math", "true");
1814*13fbcb42Sjoerg if (LangOpts.NoHonorNaNs)
1815*13fbcb42Sjoerg FuncAttrs.addAttribute("no-nans-fp-math", "true");
1816*13fbcb42Sjoerg if (LangOpts.UnsafeFPMath)
1817*13fbcb42Sjoerg FuncAttrs.addAttribute("unsafe-fp-math", "true");
1818*13fbcb42Sjoerg if (CodeGenOpts.SoftFloat)
1819*13fbcb42Sjoerg FuncAttrs.addAttribute("use-soft-float", "true");
182006f32e7eSjoerg FuncAttrs.addAttribute("stack-protector-buffer-size",
182106f32e7eSjoerg llvm::utostr(CodeGenOpts.SSPBufferSize));
1822*13fbcb42Sjoerg if (LangOpts.NoSignedZero)
1823*13fbcb42Sjoerg FuncAttrs.addAttribute("no-signed-zeros-fp-math", "true");
182406f32e7eSjoerg
182506f32e7eSjoerg // TODO: Reciprocal estimate codegen options should apply to instructions?
182606f32e7eSjoerg const std::vector<std::string> &Recips = CodeGenOpts.Reciprocals;
182706f32e7eSjoerg if (!Recips.empty())
182806f32e7eSjoerg FuncAttrs.addAttribute("reciprocal-estimates",
182906f32e7eSjoerg llvm::join(Recips, ","));
183006f32e7eSjoerg
183106f32e7eSjoerg if (!CodeGenOpts.PreferVectorWidth.empty() &&
183206f32e7eSjoerg CodeGenOpts.PreferVectorWidth != "none")
183306f32e7eSjoerg FuncAttrs.addAttribute("prefer-vector-width",
183406f32e7eSjoerg CodeGenOpts.PreferVectorWidth);
183506f32e7eSjoerg
183606f32e7eSjoerg if (CodeGenOpts.StackRealignment)
183706f32e7eSjoerg FuncAttrs.addAttribute("stackrealign");
183806f32e7eSjoerg if (CodeGenOpts.Backchain)
183906f32e7eSjoerg FuncAttrs.addAttribute("backchain");
1840*13fbcb42Sjoerg if (CodeGenOpts.EnableSegmentedStacks)
1841*13fbcb42Sjoerg FuncAttrs.addAttribute("split-stack");
184206f32e7eSjoerg
184306f32e7eSjoerg if (CodeGenOpts.SpeculativeLoadHardening)
184406f32e7eSjoerg FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
184506f32e7eSjoerg }
184606f32e7eSjoerg
184706f32e7eSjoerg if (getLangOpts().assumeFunctionsAreConvergent()) {
184806f32e7eSjoerg // Conservatively, mark all functions and calls in CUDA and OpenCL as
184906f32e7eSjoerg // convergent (meaning, they may call an intrinsically convergent op, such
185006f32e7eSjoerg // as __syncthreads() / barrier(), and so can't have certain optimizations
185106f32e7eSjoerg // applied around them). LLVM will remove this attribute where it safely
185206f32e7eSjoerg // can.
185306f32e7eSjoerg FuncAttrs.addAttribute(llvm::Attribute::Convergent);
185406f32e7eSjoerg }
185506f32e7eSjoerg
185606f32e7eSjoerg if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
185706f32e7eSjoerg // Exceptions aren't supported in CUDA device code.
185806f32e7eSjoerg FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
185906f32e7eSjoerg }
186006f32e7eSjoerg
186106f32e7eSjoerg for (StringRef Attr : CodeGenOpts.DefaultFunctionAttrs) {
186206f32e7eSjoerg StringRef Var, Value;
186306f32e7eSjoerg std::tie(Var, Value) = Attr.split('=');
186406f32e7eSjoerg FuncAttrs.addAttribute(Var, Value);
186506f32e7eSjoerg }
186606f32e7eSjoerg }
186706f32e7eSjoerg
addDefaultFunctionDefinitionAttributes(llvm::Function & F)1868*13fbcb42Sjoerg void CodeGenModule::addDefaultFunctionDefinitionAttributes(llvm::Function &F) {
186906f32e7eSjoerg llvm::AttrBuilder FuncAttrs;
1870*13fbcb42Sjoerg getDefaultFunctionAttributes(F.getName(), F.hasOptNone(),
187106f32e7eSjoerg /* AttrOnCallSite = */ false, FuncAttrs);
1872*13fbcb42Sjoerg // TODO: call GetCPUAndFeaturesAttributes?
187306f32e7eSjoerg F.addAttributes(llvm::AttributeList::FunctionIndex, FuncAttrs);
187406f32e7eSjoerg }
187506f32e7eSjoerg
addDefaultFunctionDefinitionAttributes(llvm::AttrBuilder & attrs)1876*13fbcb42Sjoerg void CodeGenModule::addDefaultFunctionDefinitionAttributes(
1877*13fbcb42Sjoerg llvm::AttrBuilder &attrs) {
1878*13fbcb42Sjoerg getDefaultFunctionAttributes(/*function name*/ "", /*optnone*/ false,
1879*13fbcb42Sjoerg /*for call*/ false, attrs);
1880*13fbcb42Sjoerg GetCPUAndFeaturesAttributes(GlobalDecl(), attrs);
1881*13fbcb42Sjoerg }
1882*13fbcb42Sjoerg
addNoBuiltinAttributes(llvm::AttrBuilder & FuncAttrs,const LangOptions & LangOpts,const NoBuiltinAttr * NBA=nullptr)1883*13fbcb42Sjoerg static void addNoBuiltinAttributes(llvm::AttrBuilder &FuncAttrs,
1884*13fbcb42Sjoerg const LangOptions &LangOpts,
1885*13fbcb42Sjoerg const NoBuiltinAttr *NBA = nullptr) {
1886*13fbcb42Sjoerg auto AddNoBuiltinAttr = [&FuncAttrs](StringRef BuiltinName) {
1887*13fbcb42Sjoerg SmallString<32> AttributeName;
1888*13fbcb42Sjoerg AttributeName += "no-builtin-";
1889*13fbcb42Sjoerg AttributeName += BuiltinName;
1890*13fbcb42Sjoerg FuncAttrs.addAttribute(AttributeName);
1891*13fbcb42Sjoerg };
1892*13fbcb42Sjoerg
1893*13fbcb42Sjoerg // First, handle the language options passed through -fno-builtin.
1894*13fbcb42Sjoerg if (LangOpts.NoBuiltin) {
1895*13fbcb42Sjoerg // -fno-builtin disables them all.
1896*13fbcb42Sjoerg FuncAttrs.addAttribute("no-builtins");
1897*13fbcb42Sjoerg return;
1898*13fbcb42Sjoerg }
1899*13fbcb42Sjoerg
1900*13fbcb42Sjoerg // Then, add attributes for builtins specified through -fno-builtin-<name>.
1901*13fbcb42Sjoerg llvm::for_each(LangOpts.NoBuiltinFuncs, AddNoBuiltinAttr);
1902*13fbcb42Sjoerg
1903*13fbcb42Sjoerg // Now, let's check the __attribute__((no_builtin("...")) attribute added to
1904*13fbcb42Sjoerg // the source.
1905*13fbcb42Sjoerg if (!NBA)
1906*13fbcb42Sjoerg return;
1907*13fbcb42Sjoerg
1908*13fbcb42Sjoerg // If there is a wildcard in the builtin names specified through the
1909*13fbcb42Sjoerg // attribute, disable them all.
1910*13fbcb42Sjoerg if (llvm::is_contained(NBA->builtinNames(), "*")) {
1911*13fbcb42Sjoerg FuncAttrs.addAttribute("no-builtins");
1912*13fbcb42Sjoerg return;
1913*13fbcb42Sjoerg }
1914*13fbcb42Sjoerg
1915*13fbcb42Sjoerg // And last, add the rest of the builtin names.
1916*13fbcb42Sjoerg llvm::for_each(NBA->builtinNames(), AddNoBuiltinAttr);
1917*13fbcb42Sjoerg }
1918*13fbcb42Sjoerg
DetermineNoUndef(QualType QTy,CodeGenTypes & Types,const llvm::DataLayout & DL,const ABIArgInfo & AI,bool CheckCoerce=true)1919*13fbcb42Sjoerg static bool DetermineNoUndef(QualType QTy, CodeGenTypes &Types,
1920*13fbcb42Sjoerg const llvm::DataLayout &DL, const ABIArgInfo &AI,
1921*13fbcb42Sjoerg bool CheckCoerce = true) {
1922*13fbcb42Sjoerg llvm::Type *Ty = Types.ConvertTypeForMem(QTy);
1923*13fbcb42Sjoerg if (AI.getKind() == ABIArgInfo::Indirect)
1924*13fbcb42Sjoerg return true;
1925*13fbcb42Sjoerg if (AI.getKind() == ABIArgInfo::Extend)
1926*13fbcb42Sjoerg return true;
1927*13fbcb42Sjoerg if (!DL.typeSizeEqualsStoreSize(Ty))
1928*13fbcb42Sjoerg // TODO: This will result in a modest amount of values not marked noundef
1929*13fbcb42Sjoerg // when they could be. We care about values that *invisibly* contain undef
1930*13fbcb42Sjoerg // bits from the perspective of LLVM IR.
1931*13fbcb42Sjoerg return false;
1932*13fbcb42Sjoerg if (CheckCoerce && AI.canHaveCoerceToType()) {
1933*13fbcb42Sjoerg llvm::Type *CoerceTy = AI.getCoerceToType();
1934*13fbcb42Sjoerg if (llvm::TypeSize::isKnownGT(DL.getTypeSizeInBits(CoerceTy),
1935*13fbcb42Sjoerg DL.getTypeSizeInBits(Ty)))
1936*13fbcb42Sjoerg // If we're coercing to a type with a greater size than the canonical one,
1937*13fbcb42Sjoerg // we're introducing new undef bits.
1938*13fbcb42Sjoerg // Coercing to a type of smaller or equal size is ok, as we know that
1939*13fbcb42Sjoerg // there's no internal padding (typeSizeEqualsStoreSize).
1940*13fbcb42Sjoerg return false;
1941*13fbcb42Sjoerg }
1942*13fbcb42Sjoerg if (QTy->isExtIntType())
1943*13fbcb42Sjoerg return true;
1944*13fbcb42Sjoerg if (QTy->isReferenceType())
1945*13fbcb42Sjoerg return true;
1946*13fbcb42Sjoerg if (QTy->isNullPtrType())
1947*13fbcb42Sjoerg return false;
1948*13fbcb42Sjoerg if (QTy->isMemberPointerType())
1949*13fbcb42Sjoerg // TODO: Some member pointers are `noundef`, but it depends on the ABI. For
1950*13fbcb42Sjoerg // now, never mark them.
1951*13fbcb42Sjoerg return false;
1952*13fbcb42Sjoerg if (QTy->isScalarType()) {
1953*13fbcb42Sjoerg if (const ComplexType *Complex = dyn_cast<ComplexType>(QTy))
1954*13fbcb42Sjoerg return DetermineNoUndef(Complex->getElementType(), Types, DL, AI, false);
1955*13fbcb42Sjoerg return true;
1956*13fbcb42Sjoerg }
1957*13fbcb42Sjoerg if (const VectorType *Vector = dyn_cast<VectorType>(QTy))
1958*13fbcb42Sjoerg return DetermineNoUndef(Vector->getElementType(), Types, DL, AI, false);
1959*13fbcb42Sjoerg if (const MatrixType *Matrix = dyn_cast<MatrixType>(QTy))
1960*13fbcb42Sjoerg return DetermineNoUndef(Matrix->getElementType(), Types, DL, AI, false);
1961*13fbcb42Sjoerg if (const ArrayType *Array = dyn_cast<ArrayType>(QTy))
1962*13fbcb42Sjoerg return DetermineNoUndef(Array->getElementType(), Types, DL, AI, false);
1963*13fbcb42Sjoerg
1964*13fbcb42Sjoerg // TODO: Some structs may be `noundef`, in specific situations.
1965*13fbcb42Sjoerg return false;
1966*13fbcb42Sjoerg }
1967*13fbcb42Sjoerg
1968*13fbcb42Sjoerg /// Construct the IR attribute list of a function or call.
1969*13fbcb42Sjoerg ///
1970*13fbcb42Sjoerg /// When adding an attribute, please consider where it should be handled:
1971*13fbcb42Sjoerg ///
1972*13fbcb42Sjoerg /// - getDefaultFunctionAttributes is for attributes that are essentially
1973*13fbcb42Sjoerg /// part of the global target configuration (but perhaps can be
1974*13fbcb42Sjoerg /// overridden on a per-function basis). Adding attributes there
1975*13fbcb42Sjoerg /// will cause them to also be set in frontends that build on Clang's
1976*13fbcb42Sjoerg /// target-configuration logic, as well as for code defined in library
1977*13fbcb42Sjoerg /// modules such as CUDA's libdevice.
1978*13fbcb42Sjoerg ///
1979*13fbcb42Sjoerg /// - ConstructAttributeList builds on top of getDefaultFunctionAttributes
1980*13fbcb42Sjoerg /// and adds declaration-specific, convention-specific, and
1981*13fbcb42Sjoerg /// frontend-specific logic. The last is of particular importance:
1982*13fbcb42Sjoerg /// attributes that restrict how the frontend generates code must be
1983*13fbcb42Sjoerg /// added here rather than getDefaultFunctionAttributes.
1984*13fbcb42Sjoerg ///
ConstructAttributeList(StringRef Name,const CGFunctionInfo & FI,CGCalleeInfo CalleeInfo,llvm::AttributeList & AttrList,unsigned & CallingConv,bool AttrOnCallSite,bool IsThunk)1985*13fbcb42Sjoerg void CodeGenModule::ConstructAttributeList(StringRef Name,
1986*13fbcb42Sjoerg const CGFunctionInfo &FI,
1987*13fbcb42Sjoerg CGCalleeInfo CalleeInfo,
1988*13fbcb42Sjoerg llvm::AttributeList &AttrList,
1989*13fbcb42Sjoerg unsigned &CallingConv,
1990*13fbcb42Sjoerg bool AttrOnCallSite, bool IsThunk) {
199106f32e7eSjoerg llvm::AttrBuilder FuncAttrs;
199206f32e7eSjoerg llvm::AttrBuilder RetAttrs;
199306f32e7eSjoerg
1994*13fbcb42Sjoerg // Collect function IR attributes from the CC lowering.
1995*13fbcb42Sjoerg // We'll collect the paramete and result attributes later.
199606f32e7eSjoerg CallingConv = FI.getEffectiveCallingConvention();
199706f32e7eSjoerg if (FI.isNoReturn())
199806f32e7eSjoerg FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
1999*13fbcb42Sjoerg if (FI.isCmseNSCall())
2000*13fbcb42Sjoerg FuncAttrs.addAttribute("cmse_nonsecure_call");
200106f32e7eSjoerg
2002*13fbcb42Sjoerg // Collect function IR attributes from the callee prototype if we have one.
200306f32e7eSjoerg AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
200406f32e7eSjoerg CalleeInfo.getCalleeFunctionProtoType());
200506f32e7eSjoerg
200606f32e7eSjoerg const Decl *TargetDecl = CalleeInfo.getCalleeDecl().getDecl();
200706f32e7eSjoerg
200806f32e7eSjoerg bool HasOptnone = false;
2009*13fbcb42Sjoerg // The NoBuiltinAttr attached to the target FunctionDecl.
2010*13fbcb42Sjoerg const NoBuiltinAttr *NBA = nullptr;
2011*13fbcb42Sjoerg
2012*13fbcb42Sjoerg // Collect function IR attributes based on declaration-specific
2013*13fbcb42Sjoerg // information.
201406f32e7eSjoerg // FIXME: handle sseregparm someday...
201506f32e7eSjoerg if (TargetDecl) {
201606f32e7eSjoerg if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
201706f32e7eSjoerg FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
201806f32e7eSjoerg if (TargetDecl->hasAttr<NoThrowAttr>())
201906f32e7eSjoerg FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
202006f32e7eSjoerg if (TargetDecl->hasAttr<NoReturnAttr>())
202106f32e7eSjoerg FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
202206f32e7eSjoerg if (TargetDecl->hasAttr<ColdAttr>())
202306f32e7eSjoerg FuncAttrs.addAttribute(llvm::Attribute::Cold);
2024*13fbcb42Sjoerg if (TargetDecl->hasAttr<HotAttr>())
2025*13fbcb42Sjoerg FuncAttrs.addAttribute(llvm::Attribute::Hot);
202606f32e7eSjoerg if (TargetDecl->hasAttr<NoDuplicateAttr>())
202706f32e7eSjoerg FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
202806f32e7eSjoerg if (TargetDecl->hasAttr<ConvergentAttr>())
202906f32e7eSjoerg FuncAttrs.addAttribute(llvm::Attribute::Convergent);
203006f32e7eSjoerg
203106f32e7eSjoerg if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
203206f32e7eSjoerg AddAttributesFromFunctionProtoType(
203306f32e7eSjoerg getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
2034*13fbcb42Sjoerg if (AttrOnCallSite && Fn->isReplaceableGlobalAllocationFunction()) {
2035*13fbcb42Sjoerg // A sane operator new returns a non-aliasing pointer.
2036*13fbcb42Sjoerg auto Kind = Fn->getDeclName().getCXXOverloadedOperator();
2037*13fbcb42Sjoerg if (getCodeGenOpts().AssumeSaneOperatorNew &&
2038*13fbcb42Sjoerg (Kind == OO_New || Kind == OO_Array_New))
2039*13fbcb42Sjoerg RetAttrs.addAttribute(llvm::Attribute::NoAlias);
2040*13fbcb42Sjoerg }
204106f32e7eSjoerg const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
2042*13fbcb42Sjoerg const bool IsVirtualCall = MD && MD->isVirtual();
2043*13fbcb42Sjoerg // Don't use [[noreturn]], _Noreturn or [[no_builtin]] for a call to a
2044*13fbcb42Sjoerg // virtual function. These attributes are not inherited by overloads.
2045*13fbcb42Sjoerg if (!(AttrOnCallSite && IsVirtualCall)) {
2046*13fbcb42Sjoerg if (Fn->isNoReturn())
204706f32e7eSjoerg FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2048*13fbcb42Sjoerg NBA = Fn->getAttr<NoBuiltinAttr>();
2049*13fbcb42Sjoerg }
2050*13fbcb42Sjoerg // Only place nomerge attribute on call sites, never functions. This
2051*13fbcb42Sjoerg // allows it to work on indirect virtual function calls.
2052*13fbcb42Sjoerg if (AttrOnCallSite && TargetDecl->hasAttr<NoMergeAttr>())
2053*13fbcb42Sjoerg FuncAttrs.addAttribute(llvm::Attribute::NoMerge);
2054*13fbcb42Sjoerg
2055*13fbcb42Sjoerg // Add known guaranteed alignment for allocation functions.
2056*13fbcb42Sjoerg if (unsigned BuiltinID = Fn->getBuiltinID()) {
2057*13fbcb42Sjoerg switch (BuiltinID) {
2058*13fbcb42Sjoerg case Builtin::BIaligned_alloc:
2059*13fbcb42Sjoerg case Builtin::BIcalloc:
2060*13fbcb42Sjoerg case Builtin::BImalloc:
2061*13fbcb42Sjoerg case Builtin::BImemalign:
2062*13fbcb42Sjoerg case Builtin::BIrealloc:
2063*13fbcb42Sjoerg case Builtin::BIstrdup:
2064*13fbcb42Sjoerg case Builtin::BIstrndup:
2065*13fbcb42Sjoerg RetAttrs.addAlignmentAttr(Context.getTargetInfo().getNewAlign() /
2066*13fbcb42Sjoerg Context.getTargetInfo().getCharWidth());
2067*13fbcb42Sjoerg break;
2068*13fbcb42Sjoerg default:
2069*13fbcb42Sjoerg break;
2070*13fbcb42Sjoerg }
2071*13fbcb42Sjoerg }
207206f32e7eSjoerg }
207306f32e7eSjoerg
207406f32e7eSjoerg // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
207506f32e7eSjoerg if (TargetDecl->hasAttr<ConstAttr>()) {
207606f32e7eSjoerg FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
207706f32e7eSjoerg FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2078*13fbcb42Sjoerg // gcc specifies that 'const' functions have greater restrictions than
2079*13fbcb42Sjoerg // 'pure' functions, so they also cannot have infinite loops.
2080*13fbcb42Sjoerg FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
208106f32e7eSjoerg } else if (TargetDecl->hasAttr<PureAttr>()) {
208206f32e7eSjoerg FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
208306f32e7eSjoerg FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2084*13fbcb42Sjoerg // gcc specifies that 'pure' functions cannot have infinite loops.
2085*13fbcb42Sjoerg FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
208606f32e7eSjoerg } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
208706f32e7eSjoerg FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
208806f32e7eSjoerg FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
208906f32e7eSjoerg }
209006f32e7eSjoerg if (TargetDecl->hasAttr<RestrictAttr>())
209106f32e7eSjoerg RetAttrs.addAttribute(llvm::Attribute::NoAlias);
209206f32e7eSjoerg if (TargetDecl->hasAttr<ReturnsNonNullAttr>() &&
209306f32e7eSjoerg !CodeGenOpts.NullPointerIsValid)
209406f32e7eSjoerg RetAttrs.addAttribute(llvm::Attribute::NonNull);
209506f32e7eSjoerg if (TargetDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())
209606f32e7eSjoerg FuncAttrs.addAttribute("no_caller_saved_registers");
209706f32e7eSjoerg if (TargetDecl->hasAttr<AnyX86NoCfCheckAttr>())
209806f32e7eSjoerg FuncAttrs.addAttribute(llvm::Attribute::NoCfCheck);
2099*13fbcb42Sjoerg if (TargetDecl->hasAttr<LeafAttr>())
2100*13fbcb42Sjoerg FuncAttrs.addAttribute(llvm::Attribute::NoCallback);
210106f32e7eSjoerg
210206f32e7eSjoerg HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
210306f32e7eSjoerg if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) {
210406f32e7eSjoerg Optional<unsigned> NumElemsParam;
210506f32e7eSjoerg if (AllocSize->getNumElemsParam().isValid())
210606f32e7eSjoerg NumElemsParam = AllocSize->getNumElemsParam().getLLVMIndex();
210706f32e7eSjoerg FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam().getLLVMIndex(),
210806f32e7eSjoerg NumElemsParam);
210906f32e7eSjoerg }
211006f32e7eSjoerg
2111*13fbcb42Sjoerg if (TargetDecl->hasAttr<OpenCLKernelAttr>()) {
211206f32e7eSjoerg if (getLangOpts().OpenCLVersion <= 120) {
211306f32e7eSjoerg // OpenCL v1.2 Work groups are always uniform
211406f32e7eSjoerg FuncAttrs.addAttribute("uniform-work-group-size", "true");
211506f32e7eSjoerg } else {
211606f32e7eSjoerg // OpenCL v2.0 Work groups may be whether uniform or not.
211706f32e7eSjoerg // '-cl-uniform-work-group-size' compile option gets a hint
211806f32e7eSjoerg // to the compiler that the global work-size be a multiple of
211906f32e7eSjoerg // the work-group size specified to clEnqueueNDRangeKernel
212006f32e7eSjoerg // (i.e. work groups are uniform).
212106f32e7eSjoerg FuncAttrs.addAttribute("uniform-work-group-size",
212206f32e7eSjoerg llvm::toStringRef(CodeGenOpts.UniformWGSize));
212306f32e7eSjoerg }
212406f32e7eSjoerg }
212506f32e7eSjoerg
2126*13fbcb42Sjoerg std::string AssumptionValueStr;
2127*13fbcb42Sjoerg for (AssumptionAttr *AssumptionA :
2128*13fbcb42Sjoerg TargetDecl->specific_attrs<AssumptionAttr>()) {
2129*13fbcb42Sjoerg std::string AS = AssumptionA->getAssumption().str();
2130*13fbcb42Sjoerg if (!AS.empty() && !AssumptionValueStr.empty())
2131*13fbcb42Sjoerg AssumptionValueStr += ",";
2132*13fbcb42Sjoerg AssumptionValueStr += AS;
2133*13fbcb42Sjoerg }
213406f32e7eSjoerg
2135*13fbcb42Sjoerg if (!AssumptionValueStr.empty())
2136*13fbcb42Sjoerg FuncAttrs.addAttribute(llvm::AssumptionAttrKey, AssumptionValueStr);
2137*13fbcb42Sjoerg }
2138*13fbcb42Sjoerg
2139*13fbcb42Sjoerg // Attach "no-builtins" attributes to:
2140*13fbcb42Sjoerg // * call sites: both `nobuiltin` and "no-builtins" or "no-builtin-<name>".
2141*13fbcb42Sjoerg // * definitions: "no-builtins" or "no-builtin-<name>" only.
2142*13fbcb42Sjoerg // The attributes can come from:
2143*13fbcb42Sjoerg // * LangOpts: -ffreestanding, -fno-builtin, -fno-builtin-<name>
2144*13fbcb42Sjoerg // * FunctionDecl attributes: __attribute__((no_builtin(...)))
2145*13fbcb42Sjoerg addNoBuiltinAttributes(FuncAttrs, getLangOpts(), NBA);
2146*13fbcb42Sjoerg
2147*13fbcb42Sjoerg // Collect function IR attributes based on global settiings.
2148*13fbcb42Sjoerg getDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
2149*13fbcb42Sjoerg
2150*13fbcb42Sjoerg // Override some default IR attributes based on declaration-specific
2151*13fbcb42Sjoerg // information.
2152*13fbcb42Sjoerg if (TargetDecl) {
2153*13fbcb42Sjoerg if (TargetDecl->hasAttr<NoSpeculativeLoadHardeningAttr>())
2154*13fbcb42Sjoerg FuncAttrs.removeAttribute(llvm::Attribute::SpeculativeLoadHardening);
2155*13fbcb42Sjoerg if (TargetDecl->hasAttr<SpeculativeLoadHardeningAttr>())
2156*13fbcb42Sjoerg FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
2157*13fbcb42Sjoerg if (TargetDecl->hasAttr<NoSplitStackAttr>())
2158*13fbcb42Sjoerg FuncAttrs.removeAttribute("split-stack");
2159*13fbcb42Sjoerg
2160*13fbcb42Sjoerg // Add NonLazyBind attribute to function declarations when -fno-plt
2161*13fbcb42Sjoerg // is used.
2162*13fbcb42Sjoerg // FIXME: what if we just haven't processed the function definition
2163*13fbcb42Sjoerg // yet, or if it's an external definition like C99 inline?
2164*13fbcb42Sjoerg if (CodeGenOpts.NoPLT) {
2165*13fbcb42Sjoerg if (auto *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
2166*13fbcb42Sjoerg if (!Fn->isDefined() && !AttrOnCallSite) {
2167*13fbcb42Sjoerg FuncAttrs.addAttribute(llvm::Attribute::NonLazyBind);
2168*13fbcb42Sjoerg }
2169*13fbcb42Sjoerg }
2170*13fbcb42Sjoerg }
2171*13fbcb42Sjoerg }
2172*13fbcb42Sjoerg
2173*13fbcb42Sjoerg // Add "sample-profile-suffix-elision-policy" attribute for internal linkage
2174*13fbcb42Sjoerg // functions with -funique-internal-linkage-names.
2175*13fbcb42Sjoerg if (TargetDecl && CodeGenOpts.UniqueInternalLinkageNames) {
2176*13fbcb42Sjoerg if (auto *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
2177*13fbcb42Sjoerg if (this->getFunctionLinkage(Fn) == llvm::GlobalValue::InternalLinkage)
2178*13fbcb42Sjoerg FuncAttrs.addAttribute("sample-profile-suffix-elision-policy",
2179*13fbcb42Sjoerg "selected");
2180*13fbcb42Sjoerg }
2181*13fbcb42Sjoerg }
2182*13fbcb42Sjoerg
2183*13fbcb42Sjoerg // Collect non-call-site function IR attributes from declaration-specific
2184*13fbcb42Sjoerg // information.
2185*13fbcb42Sjoerg if (!AttrOnCallSite) {
2186*13fbcb42Sjoerg if (TargetDecl && TargetDecl->hasAttr<CmseNSEntryAttr>())
2187*13fbcb42Sjoerg FuncAttrs.addAttribute("cmse_nonsecure_entry");
2188*13fbcb42Sjoerg
2189*13fbcb42Sjoerg // Whether tail calls are enabled.
2190*13fbcb42Sjoerg auto shouldDisableTailCalls = [&] {
2191*13fbcb42Sjoerg // Should this be honored in getDefaultFunctionAttributes?
219206f32e7eSjoerg if (CodeGenOpts.DisableTailCalls)
2193*13fbcb42Sjoerg return true;
2194*13fbcb42Sjoerg
2195*13fbcb42Sjoerg if (!TargetDecl)
2196*13fbcb42Sjoerg return false;
2197*13fbcb42Sjoerg
219806f32e7eSjoerg if (TargetDecl->hasAttr<DisableTailCallsAttr>() ||
219906f32e7eSjoerg TargetDecl->hasAttr<AnyX86InterruptAttr>())
2200*13fbcb42Sjoerg return true;
2201*13fbcb42Sjoerg
2202*13fbcb42Sjoerg if (CodeGenOpts.NoEscapingBlockTailCalls) {
220306f32e7eSjoerg if (const auto *BD = dyn_cast<BlockDecl>(TargetDecl))
220406f32e7eSjoerg if (!BD->doesNotEscape())
2205*13fbcb42Sjoerg return true;
220606f32e7eSjoerg }
220706f32e7eSjoerg
2208*13fbcb42Sjoerg return false;
2209*13fbcb42Sjoerg };
2210*13fbcb42Sjoerg if (shouldDisableTailCalls())
2211*13fbcb42Sjoerg FuncAttrs.addAttribute("disable-tail-calls", "true");
2212*13fbcb42Sjoerg
2213*13fbcb42Sjoerg // CPU/feature overrides. addDefaultFunctionDefinitionAttributes
2214*13fbcb42Sjoerg // handles these separately to set them based on the global defaults.
221506f32e7eSjoerg GetCPUAndFeaturesAttributes(CalleeInfo.getCalleeDecl(), FuncAttrs);
221606f32e7eSjoerg }
221706f32e7eSjoerg
2218*13fbcb42Sjoerg // Collect attributes from arguments and return values.
221906f32e7eSjoerg ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
222006f32e7eSjoerg
222106f32e7eSjoerg QualType RetTy = FI.getReturnType();
222206f32e7eSjoerg const ABIArgInfo &RetAI = FI.getReturnInfo();
2223*13fbcb42Sjoerg const llvm::DataLayout &DL = getDataLayout();
2224*13fbcb42Sjoerg
2225*13fbcb42Sjoerg // C++ explicitly makes returning undefined values UB. C's rule only applies
2226*13fbcb42Sjoerg // to used values, so we never mark them noundef for now.
2227*13fbcb42Sjoerg bool HasStrictReturn = getLangOpts().CPlusPlus;
2228*13fbcb42Sjoerg if (TargetDecl) {
2229*13fbcb42Sjoerg if (const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(TargetDecl))
2230*13fbcb42Sjoerg HasStrictReturn &= !FDecl->isExternC();
2231*13fbcb42Sjoerg else if (const VarDecl *VDecl = dyn_cast<VarDecl>(TargetDecl))
2232*13fbcb42Sjoerg // Function pointer
2233*13fbcb42Sjoerg HasStrictReturn &= !VDecl->isExternC();
2234*13fbcb42Sjoerg }
2235*13fbcb42Sjoerg
2236*13fbcb42Sjoerg // We don't want to be too aggressive with the return checking, unless
2237*13fbcb42Sjoerg // it's explicit in the code opts or we're using an appropriate sanitizer.
2238*13fbcb42Sjoerg // Try to respect what the programmer intended.
2239*13fbcb42Sjoerg HasStrictReturn &= getCodeGenOpts().StrictReturn ||
2240*13fbcb42Sjoerg !MayDropFunctionReturn(getContext(), RetTy) ||
2241*13fbcb42Sjoerg getLangOpts().Sanitize.has(SanitizerKind::Memory) ||
2242*13fbcb42Sjoerg getLangOpts().Sanitize.has(SanitizerKind::Return);
2243*13fbcb42Sjoerg
2244*13fbcb42Sjoerg // Determine if the return type could be partially undef
2245*13fbcb42Sjoerg if (CodeGenOpts.EnableNoundefAttrs && HasStrictReturn) {
2246*13fbcb42Sjoerg if (!RetTy->isVoidType() && RetAI.getKind() != ABIArgInfo::Indirect &&
2247*13fbcb42Sjoerg DetermineNoUndef(RetTy, getTypes(), DL, RetAI))
2248*13fbcb42Sjoerg RetAttrs.addAttribute(llvm::Attribute::NoUndef);
2249*13fbcb42Sjoerg }
2250*13fbcb42Sjoerg
225106f32e7eSjoerg switch (RetAI.getKind()) {
225206f32e7eSjoerg case ABIArgInfo::Extend:
225306f32e7eSjoerg if (RetAI.isSignExt())
225406f32e7eSjoerg RetAttrs.addAttribute(llvm::Attribute::SExt);
225506f32e7eSjoerg else
225606f32e7eSjoerg RetAttrs.addAttribute(llvm::Attribute::ZExt);
225706f32e7eSjoerg LLVM_FALLTHROUGH;
225806f32e7eSjoerg case ABIArgInfo::Direct:
225906f32e7eSjoerg if (RetAI.getInReg())
226006f32e7eSjoerg RetAttrs.addAttribute(llvm::Attribute::InReg);
226106f32e7eSjoerg break;
226206f32e7eSjoerg case ABIArgInfo::Ignore:
226306f32e7eSjoerg break;
226406f32e7eSjoerg
226506f32e7eSjoerg case ABIArgInfo::InAlloca:
226606f32e7eSjoerg case ABIArgInfo::Indirect: {
226706f32e7eSjoerg // inalloca and sret disable readnone and readonly
226806f32e7eSjoerg FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
226906f32e7eSjoerg .removeAttribute(llvm::Attribute::ReadNone);
227006f32e7eSjoerg break;
227106f32e7eSjoerg }
227206f32e7eSjoerg
227306f32e7eSjoerg case ABIArgInfo::CoerceAndExpand:
227406f32e7eSjoerg break;
227506f32e7eSjoerg
227606f32e7eSjoerg case ABIArgInfo::Expand:
2277*13fbcb42Sjoerg case ABIArgInfo::IndirectAliased:
227806f32e7eSjoerg llvm_unreachable("Invalid ABI kind for return argument");
227906f32e7eSjoerg }
228006f32e7eSjoerg
2281*13fbcb42Sjoerg if (!IsThunk) {
2282*13fbcb42Sjoerg // FIXME: fix this properly, https://reviews.llvm.org/D100388
228306f32e7eSjoerg if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
228406f32e7eSjoerg QualType PTy = RefTy->getPointeeType();
228506f32e7eSjoerg if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2286*13fbcb42Sjoerg RetAttrs.addDereferenceableAttr(
2287*13fbcb42Sjoerg getMinimumObjectSize(PTy).getQuantity());
2288*13fbcb42Sjoerg if (getContext().getTargetAddressSpace(PTy) == 0 &&
228906f32e7eSjoerg !CodeGenOpts.NullPointerIsValid)
229006f32e7eSjoerg RetAttrs.addAttribute(llvm::Attribute::NonNull);
2291*13fbcb42Sjoerg if (PTy->isObjectType()) {
2292*13fbcb42Sjoerg llvm::Align Alignment =
2293*13fbcb42Sjoerg getNaturalPointeeTypeAlignment(RetTy).getAsAlign();
2294*13fbcb42Sjoerg RetAttrs.addAlignmentAttr(Alignment);
2295*13fbcb42Sjoerg }
2296*13fbcb42Sjoerg }
229706f32e7eSjoerg }
229806f32e7eSjoerg
229906f32e7eSjoerg bool hasUsedSRet = false;
230006f32e7eSjoerg SmallVector<llvm::AttributeSet, 4> ArgAttrs(IRFunctionArgs.totalIRArgs());
230106f32e7eSjoerg
230206f32e7eSjoerg // Attach attributes to sret.
230306f32e7eSjoerg if (IRFunctionArgs.hasSRetArg()) {
230406f32e7eSjoerg llvm::AttrBuilder SRETAttrs;
2305*13fbcb42Sjoerg SRETAttrs.addStructRetAttr(getTypes().ConvertTypeForMem(RetTy));
230606f32e7eSjoerg hasUsedSRet = true;
230706f32e7eSjoerg if (RetAI.getInReg())
230806f32e7eSjoerg SRETAttrs.addAttribute(llvm::Attribute::InReg);
2309*13fbcb42Sjoerg SRETAttrs.addAlignmentAttr(RetAI.getIndirectAlign().getQuantity());
231006f32e7eSjoerg ArgAttrs[IRFunctionArgs.getSRetArgNo()] =
231106f32e7eSjoerg llvm::AttributeSet::get(getLLVMContext(), SRETAttrs);
231206f32e7eSjoerg }
231306f32e7eSjoerg
231406f32e7eSjoerg // Attach attributes to inalloca argument.
231506f32e7eSjoerg if (IRFunctionArgs.hasInallocaArg()) {
231606f32e7eSjoerg llvm::AttrBuilder Attrs;
2317*13fbcb42Sjoerg Attrs.addInAllocaAttr(FI.getArgStruct());
231806f32e7eSjoerg ArgAttrs[IRFunctionArgs.getInallocaArgNo()] =
231906f32e7eSjoerg llvm::AttributeSet::get(getLLVMContext(), Attrs);
232006f32e7eSjoerg }
232106f32e7eSjoerg
2322*13fbcb42Sjoerg // Apply `nonnull`, `dereferencable(N)` and `align N` to the `this` argument,
2323*13fbcb42Sjoerg // unless this is a thunk function.
2324*13fbcb42Sjoerg // FIXME: fix this properly, https://reviews.llvm.org/D100388
2325*13fbcb42Sjoerg if (FI.isInstanceMethod() && !IRFunctionArgs.hasInallocaArg() &&
2326*13fbcb42Sjoerg !FI.arg_begin()->type->isVoidPointerType() && !IsThunk) {
2327*13fbcb42Sjoerg auto IRArgs = IRFunctionArgs.getIRArgs(0);
2328*13fbcb42Sjoerg
2329*13fbcb42Sjoerg assert(IRArgs.second == 1 && "Expected only a single `this` pointer.");
2330*13fbcb42Sjoerg
2331*13fbcb42Sjoerg llvm::AttrBuilder Attrs;
2332*13fbcb42Sjoerg
2333*13fbcb42Sjoerg QualType ThisTy =
2334*13fbcb42Sjoerg FI.arg_begin()->type.castAs<PointerType>()->getPointeeType();
2335*13fbcb42Sjoerg
2336*13fbcb42Sjoerg if (!CodeGenOpts.NullPointerIsValid &&
2337*13fbcb42Sjoerg getContext().getTargetAddressSpace(FI.arg_begin()->type) == 0) {
2338*13fbcb42Sjoerg Attrs.addAttribute(llvm::Attribute::NonNull);
2339*13fbcb42Sjoerg Attrs.addDereferenceableAttr(getMinimumObjectSize(ThisTy).getQuantity());
2340*13fbcb42Sjoerg } else {
2341*13fbcb42Sjoerg // FIXME dereferenceable should be correct here, regardless of
2342*13fbcb42Sjoerg // NullPointerIsValid. However, dereferenceable currently does not always
2343*13fbcb42Sjoerg // respect NullPointerIsValid and may imply nonnull and break the program.
2344*13fbcb42Sjoerg // See https://reviews.llvm.org/D66618 for discussions.
2345*13fbcb42Sjoerg Attrs.addDereferenceableOrNullAttr(
2346*13fbcb42Sjoerg getMinimumObjectSize(
2347*13fbcb42Sjoerg FI.arg_begin()->type.castAs<PointerType>()->getPointeeType())
2348*13fbcb42Sjoerg .getQuantity());
2349*13fbcb42Sjoerg }
2350*13fbcb42Sjoerg
2351*13fbcb42Sjoerg llvm::Align Alignment =
2352*13fbcb42Sjoerg getNaturalTypeAlignment(ThisTy, /*BaseInfo=*/nullptr,
2353*13fbcb42Sjoerg /*TBAAInfo=*/nullptr, /*forPointeeType=*/true)
2354*13fbcb42Sjoerg .getAsAlign();
2355*13fbcb42Sjoerg Attrs.addAlignmentAttr(Alignment);
2356*13fbcb42Sjoerg
2357*13fbcb42Sjoerg ArgAttrs[IRArgs.first] = llvm::AttributeSet::get(getLLVMContext(), Attrs);
2358*13fbcb42Sjoerg }
2359*13fbcb42Sjoerg
236006f32e7eSjoerg unsigned ArgNo = 0;
236106f32e7eSjoerg for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
236206f32e7eSjoerg E = FI.arg_end();
236306f32e7eSjoerg I != E; ++I, ++ArgNo) {
236406f32e7eSjoerg QualType ParamType = I->type;
236506f32e7eSjoerg const ABIArgInfo &AI = I->info;
236606f32e7eSjoerg llvm::AttrBuilder Attrs;
236706f32e7eSjoerg
236806f32e7eSjoerg // Add attribute for padding argument, if necessary.
236906f32e7eSjoerg if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
237006f32e7eSjoerg if (AI.getPaddingInReg()) {
237106f32e7eSjoerg ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
237206f32e7eSjoerg llvm::AttributeSet::get(
237306f32e7eSjoerg getLLVMContext(),
237406f32e7eSjoerg llvm::AttrBuilder().addAttribute(llvm::Attribute::InReg));
237506f32e7eSjoerg }
237606f32e7eSjoerg }
237706f32e7eSjoerg
2378*13fbcb42Sjoerg // Decide whether the argument we're handling could be partially undef
2379*13fbcb42Sjoerg bool ArgNoUndef = DetermineNoUndef(ParamType, getTypes(), DL, AI);
2380*13fbcb42Sjoerg if (CodeGenOpts.EnableNoundefAttrs && ArgNoUndef)
2381*13fbcb42Sjoerg Attrs.addAttribute(llvm::Attribute::NoUndef);
2382*13fbcb42Sjoerg
238306f32e7eSjoerg // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
238406f32e7eSjoerg // have the corresponding parameter variable. It doesn't make
238506f32e7eSjoerg // sense to do it here because parameters are so messed up.
238606f32e7eSjoerg switch (AI.getKind()) {
238706f32e7eSjoerg case ABIArgInfo::Extend:
238806f32e7eSjoerg if (AI.isSignExt())
238906f32e7eSjoerg Attrs.addAttribute(llvm::Attribute::SExt);
239006f32e7eSjoerg else
239106f32e7eSjoerg Attrs.addAttribute(llvm::Attribute::ZExt);
239206f32e7eSjoerg LLVM_FALLTHROUGH;
239306f32e7eSjoerg case ABIArgInfo::Direct:
239406f32e7eSjoerg if (ArgNo == 0 && FI.isChainCall())
239506f32e7eSjoerg Attrs.addAttribute(llvm::Attribute::Nest);
239606f32e7eSjoerg else if (AI.getInReg())
239706f32e7eSjoerg Attrs.addAttribute(llvm::Attribute::InReg);
2398*13fbcb42Sjoerg Attrs.addStackAlignmentAttr(llvm::MaybeAlign(AI.getDirectAlign()));
239906f32e7eSjoerg break;
240006f32e7eSjoerg
240106f32e7eSjoerg case ABIArgInfo::Indirect: {
240206f32e7eSjoerg if (AI.getInReg())
240306f32e7eSjoerg Attrs.addAttribute(llvm::Attribute::InReg);
240406f32e7eSjoerg
240506f32e7eSjoerg if (AI.getIndirectByVal())
240606f32e7eSjoerg Attrs.addByValAttr(getTypes().ConvertTypeForMem(ParamType));
240706f32e7eSjoerg
2408*13fbcb42Sjoerg auto *Decl = ParamType->getAsRecordDecl();
2409*13fbcb42Sjoerg if (CodeGenOpts.PassByValueIsNoAlias && Decl &&
2410*13fbcb42Sjoerg Decl->getArgPassingRestrictions() == RecordDecl::APK_CanPassInRegs)
2411*13fbcb42Sjoerg // When calling the function, the pointer passed in will be the only
2412*13fbcb42Sjoerg // reference to the underlying object. Mark it accordingly.
2413*13fbcb42Sjoerg Attrs.addAttribute(llvm::Attribute::NoAlias);
2414*13fbcb42Sjoerg
2415*13fbcb42Sjoerg // TODO: We could add the byref attribute if not byval, but it would
2416*13fbcb42Sjoerg // require updating many testcases.
2417*13fbcb42Sjoerg
241806f32e7eSjoerg CharUnits Align = AI.getIndirectAlign();
241906f32e7eSjoerg
242006f32e7eSjoerg // In a byval argument, it is important that the required
242106f32e7eSjoerg // alignment of the type is honored, as LLVM might be creating a
242206f32e7eSjoerg // *new* stack object, and needs to know what alignment to give
242306f32e7eSjoerg // it. (Sometimes it can deduce a sensible alignment on its own,
242406f32e7eSjoerg // but not if clang decides it must emit a packed struct, or the
242506f32e7eSjoerg // user specifies increased alignment requirements.)
242606f32e7eSjoerg //
242706f32e7eSjoerg // This is different from indirect *not* byval, where the object
242806f32e7eSjoerg // exists already, and the align attribute is purely
242906f32e7eSjoerg // informative.
243006f32e7eSjoerg assert(!Align.isZero());
243106f32e7eSjoerg
243206f32e7eSjoerg // For now, only add this when we have a byval argument.
243306f32e7eSjoerg // TODO: be less lazy about updating test cases.
243406f32e7eSjoerg if (AI.getIndirectByVal())
243506f32e7eSjoerg Attrs.addAlignmentAttr(Align.getQuantity());
243606f32e7eSjoerg
243706f32e7eSjoerg // byval disables readnone and readonly.
243806f32e7eSjoerg FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
243906f32e7eSjoerg .removeAttribute(llvm::Attribute::ReadNone);
2440*13fbcb42Sjoerg
2441*13fbcb42Sjoerg break;
2442*13fbcb42Sjoerg }
2443*13fbcb42Sjoerg case ABIArgInfo::IndirectAliased: {
2444*13fbcb42Sjoerg CharUnits Align = AI.getIndirectAlign();
2445*13fbcb42Sjoerg Attrs.addByRefAttr(getTypes().ConvertTypeForMem(ParamType));
2446*13fbcb42Sjoerg Attrs.addAlignmentAttr(Align.getQuantity());
244706f32e7eSjoerg break;
244806f32e7eSjoerg }
244906f32e7eSjoerg case ABIArgInfo::Ignore:
245006f32e7eSjoerg case ABIArgInfo::Expand:
245106f32e7eSjoerg case ABIArgInfo::CoerceAndExpand:
245206f32e7eSjoerg break;
245306f32e7eSjoerg
245406f32e7eSjoerg case ABIArgInfo::InAlloca:
245506f32e7eSjoerg // inalloca disables readnone and readonly.
245606f32e7eSjoerg FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
245706f32e7eSjoerg .removeAttribute(llvm::Attribute::ReadNone);
245806f32e7eSjoerg continue;
245906f32e7eSjoerg }
246006f32e7eSjoerg
246106f32e7eSjoerg if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
246206f32e7eSjoerg QualType PTy = RefTy->getPointeeType();
246306f32e7eSjoerg if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2464*13fbcb42Sjoerg Attrs.addDereferenceableAttr(
2465*13fbcb42Sjoerg getMinimumObjectSize(PTy).getQuantity());
2466*13fbcb42Sjoerg if (getContext().getTargetAddressSpace(PTy) == 0 &&
246706f32e7eSjoerg !CodeGenOpts.NullPointerIsValid)
246806f32e7eSjoerg Attrs.addAttribute(llvm::Attribute::NonNull);
2469*13fbcb42Sjoerg if (PTy->isObjectType()) {
2470*13fbcb42Sjoerg llvm::Align Alignment =
2471*13fbcb42Sjoerg getNaturalPointeeTypeAlignment(ParamType).getAsAlign();
2472*13fbcb42Sjoerg Attrs.addAlignmentAttr(Alignment);
2473*13fbcb42Sjoerg }
247406f32e7eSjoerg }
247506f32e7eSjoerg
247606f32e7eSjoerg switch (FI.getExtParameterInfo(ArgNo).getABI()) {
247706f32e7eSjoerg case ParameterABI::Ordinary:
247806f32e7eSjoerg break;
247906f32e7eSjoerg
248006f32e7eSjoerg case ParameterABI::SwiftIndirectResult: {
248106f32e7eSjoerg // Add 'sret' if we haven't already used it for something, but
248206f32e7eSjoerg // only if the result is void.
248306f32e7eSjoerg if (!hasUsedSRet && RetTy->isVoidType()) {
2484*13fbcb42Sjoerg Attrs.addStructRetAttr(getTypes().ConvertTypeForMem(ParamType));
248506f32e7eSjoerg hasUsedSRet = true;
248606f32e7eSjoerg }
248706f32e7eSjoerg
248806f32e7eSjoerg // Add 'noalias' in either case.
248906f32e7eSjoerg Attrs.addAttribute(llvm::Attribute::NoAlias);
249006f32e7eSjoerg
249106f32e7eSjoerg // Add 'dereferenceable' and 'alignment'.
249206f32e7eSjoerg auto PTy = ParamType->getPointeeType();
249306f32e7eSjoerg if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
249406f32e7eSjoerg auto info = getContext().getTypeInfoInChars(PTy);
2495*13fbcb42Sjoerg Attrs.addDereferenceableAttr(info.Width.getQuantity());
2496*13fbcb42Sjoerg Attrs.addAlignmentAttr(info.Align.getAsAlign());
249706f32e7eSjoerg }
249806f32e7eSjoerg break;
249906f32e7eSjoerg }
250006f32e7eSjoerg
250106f32e7eSjoerg case ParameterABI::SwiftErrorResult:
250206f32e7eSjoerg Attrs.addAttribute(llvm::Attribute::SwiftError);
250306f32e7eSjoerg break;
250406f32e7eSjoerg
250506f32e7eSjoerg case ParameterABI::SwiftContext:
250606f32e7eSjoerg Attrs.addAttribute(llvm::Attribute::SwiftSelf);
250706f32e7eSjoerg break;
250806f32e7eSjoerg }
250906f32e7eSjoerg
251006f32e7eSjoerg if (FI.getExtParameterInfo(ArgNo).isNoEscape())
251106f32e7eSjoerg Attrs.addAttribute(llvm::Attribute::NoCapture);
251206f32e7eSjoerg
251306f32e7eSjoerg if (Attrs.hasAttributes()) {
251406f32e7eSjoerg unsigned FirstIRArg, NumIRArgs;
251506f32e7eSjoerg std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
251606f32e7eSjoerg for (unsigned i = 0; i < NumIRArgs; i++)
251706f32e7eSjoerg ArgAttrs[FirstIRArg + i] =
251806f32e7eSjoerg llvm::AttributeSet::get(getLLVMContext(), Attrs);
251906f32e7eSjoerg }
252006f32e7eSjoerg }
252106f32e7eSjoerg assert(ArgNo == FI.arg_size());
252206f32e7eSjoerg
252306f32e7eSjoerg AttrList = llvm::AttributeList::get(
252406f32e7eSjoerg getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs),
252506f32e7eSjoerg llvm::AttributeSet::get(getLLVMContext(), RetAttrs), ArgAttrs);
252606f32e7eSjoerg }
252706f32e7eSjoerg
252806f32e7eSjoerg /// An argument came in as a promoted argument; demote it back to its
252906f32e7eSjoerg /// declared type.
emitArgumentDemotion(CodeGenFunction & CGF,const VarDecl * var,llvm::Value * value)253006f32e7eSjoerg static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
253106f32e7eSjoerg const VarDecl *var,
253206f32e7eSjoerg llvm::Value *value) {
253306f32e7eSjoerg llvm::Type *varType = CGF.ConvertType(var->getType());
253406f32e7eSjoerg
253506f32e7eSjoerg // This can happen with promotions that actually don't change the
253606f32e7eSjoerg // underlying type, like the enum promotions.
253706f32e7eSjoerg if (value->getType() == varType) return value;
253806f32e7eSjoerg
253906f32e7eSjoerg assert((varType->isIntegerTy() || varType->isFloatingPointTy())
254006f32e7eSjoerg && "unexpected promotion type");
254106f32e7eSjoerg
254206f32e7eSjoerg if (isa<llvm::IntegerType>(varType))
254306f32e7eSjoerg return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
254406f32e7eSjoerg
254506f32e7eSjoerg return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
254606f32e7eSjoerg }
254706f32e7eSjoerg
254806f32e7eSjoerg /// Returns the attribute (either parameter attribute, or function
254906f32e7eSjoerg /// attribute), which declares argument ArgNo to be non-null.
getNonNullAttr(const Decl * FD,const ParmVarDecl * PVD,QualType ArgType,unsigned ArgNo)255006f32e7eSjoerg static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
255106f32e7eSjoerg QualType ArgType, unsigned ArgNo) {
255206f32e7eSjoerg // FIXME: __attribute__((nonnull)) can also be applied to:
255306f32e7eSjoerg // - references to pointers, where the pointee is known to be
255406f32e7eSjoerg // nonnull (apparently a Clang extension)
255506f32e7eSjoerg // - transparent unions containing pointers
255606f32e7eSjoerg // In the former case, LLVM IR cannot represent the constraint. In
255706f32e7eSjoerg // the latter case, we have no guarantee that the transparent union
255806f32e7eSjoerg // is in fact passed as a pointer.
255906f32e7eSjoerg if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
256006f32e7eSjoerg return nullptr;
256106f32e7eSjoerg // First, check attribute on parameter itself.
256206f32e7eSjoerg if (PVD) {
256306f32e7eSjoerg if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
256406f32e7eSjoerg return ParmNNAttr;
256506f32e7eSjoerg }
256606f32e7eSjoerg // Check function attributes.
256706f32e7eSjoerg if (!FD)
256806f32e7eSjoerg return nullptr;
256906f32e7eSjoerg for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
257006f32e7eSjoerg if (NNAttr->isNonNull(ArgNo))
257106f32e7eSjoerg return NNAttr;
257206f32e7eSjoerg }
257306f32e7eSjoerg return nullptr;
257406f32e7eSjoerg }
257506f32e7eSjoerg
257606f32e7eSjoerg namespace {
257706f32e7eSjoerg struct CopyBackSwiftError final : EHScopeStack::Cleanup {
257806f32e7eSjoerg Address Temp;
257906f32e7eSjoerg Address Arg;
CopyBackSwiftError__anon2a3770250811::CopyBackSwiftError258006f32e7eSjoerg CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
Emit__anon2a3770250811::CopyBackSwiftError258106f32e7eSjoerg void Emit(CodeGenFunction &CGF, Flags flags) override {
258206f32e7eSjoerg llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
258306f32e7eSjoerg CGF.Builder.CreateStore(errorValue, Arg);
258406f32e7eSjoerg }
258506f32e7eSjoerg };
258606f32e7eSjoerg }
258706f32e7eSjoerg
EmitFunctionProlog(const CGFunctionInfo & FI,llvm::Function * Fn,const FunctionArgList & Args)258806f32e7eSjoerg void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
258906f32e7eSjoerg llvm::Function *Fn,
259006f32e7eSjoerg const FunctionArgList &Args) {
259106f32e7eSjoerg if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
259206f32e7eSjoerg // Naked functions don't have prologues.
259306f32e7eSjoerg return;
259406f32e7eSjoerg
259506f32e7eSjoerg // If this is an implicit-return-zero function, go ahead and
259606f32e7eSjoerg // initialize the return value. TODO: it might be nice to have
259706f32e7eSjoerg // a more general mechanism for this that didn't require synthesized
259806f32e7eSjoerg // return statements.
259906f32e7eSjoerg if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
260006f32e7eSjoerg if (FD->hasImplicitReturnZero()) {
260106f32e7eSjoerg QualType RetTy = FD->getReturnType().getUnqualifiedType();
260206f32e7eSjoerg llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
260306f32e7eSjoerg llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
260406f32e7eSjoerg Builder.CreateStore(Zero, ReturnValue);
260506f32e7eSjoerg }
260606f32e7eSjoerg }
260706f32e7eSjoerg
260806f32e7eSjoerg // FIXME: We no longer need the types from FunctionArgList; lift up and
260906f32e7eSjoerg // simplify.
261006f32e7eSjoerg
261106f32e7eSjoerg ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
2612*13fbcb42Sjoerg assert(Fn->arg_size() == IRFunctionArgs.totalIRArgs());
261306f32e7eSjoerg
261406f32e7eSjoerg // If we're using inalloca, all the memory arguments are GEPs off of the last
261506f32e7eSjoerg // parameter, which is a pointer to the complete memory area.
261606f32e7eSjoerg Address ArgStruct = Address::invalid();
261706f32e7eSjoerg if (IRFunctionArgs.hasInallocaArg()) {
2618*13fbcb42Sjoerg ArgStruct = Address(Fn->getArg(IRFunctionArgs.getInallocaArgNo()),
261906f32e7eSjoerg FI.getArgStructAlignment());
262006f32e7eSjoerg
262106f32e7eSjoerg assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
262206f32e7eSjoerg }
262306f32e7eSjoerg
262406f32e7eSjoerg // Name the struct return parameter.
262506f32e7eSjoerg if (IRFunctionArgs.hasSRetArg()) {
2626*13fbcb42Sjoerg auto AI = Fn->getArg(IRFunctionArgs.getSRetArgNo());
262706f32e7eSjoerg AI->setName("agg.result");
262806f32e7eSjoerg AI->addAttr(llvm::Attribute::NoAlias);
262906f32e7eSjoerg }
263006f32e7eSjoerg
263106f32e7eSjoerg // Track if we received the parameter as a pointer (indirect, byval, or
263206f32e7eSjoerg // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
263306f32e7eSjoerg // into a local alloca for us.
263406f32e7eSjoerg SmallVector<ParamValue, 16> ArgVals;
263506f32e7eSjoerg ArgVals.reserve(Args.size());
263606f32e7eSjoerg
263706f32e7eSjoerg // Create a pointer value for every parameter declaration. This usually
263806f32e7eSjoerg // entails copying one or more LLVM IR arguments into an alloca. Don't push
263906f32e7eSjoerg // any cleanups or do anything that might unwind. We do that separately, so
264006f32e7eSjoerg // we can push the cleanups in the correct order for the ABI.
264106f32e7eSjoerg assert(FI.arg_size() == Args.size() &&
264206f32e7eSjoerg "Mismatch between function signature & arguments.");
264306f32e7eSjoerg unsigned ArgNo = 0;
264406f32e7eSjoerg CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
264506f32e7eSjoerg for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
264606f32e7eSjoerg i != e; ++i, ++info_it, ++ArgNo) {
264706f32e7eSjoerg const VarDecl *Arg = *i;
264806f32e7eSjoerg const ABIArgInfo &ArgI = info_it->info;
264906f32e7eSjoerg
265006f32e7eSjoerg bool isPromoted =
265106f32e7eSjoerg isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
265206f32e7eSjoerg // We are converting from ABIArgInfo type to VarDecl type directly, unless
265306f32e7eSjoerg // the parameter is promoted. In this case we convert to
265406f32e7eSjoerg // CGFunctionInfo::ArgInfo type with subsequent argument demotion.
265506f32e7eSjoerg QualType Ty = isPromoted ? info_it->type : Arg->getType();
265606f32e7eSjoerg assert(hasScalarEvaluationKind(Ty) ==
265706f32e7eSjoerg hasScalarEvaluationKind(Arg->getType()));
265806f32e7eSjoerg
265906f32e7eSjoerg unsigned FirstIRArg, NumIRArgs;
266006f32e7eSjoerg std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
266106f32e7eSjoerg
266206f32e7eSjoerg switch (ArgI.getKind()) {
266306f32e7eSjoerg case ABIArgInfo::InAlloca: {
266406f32e7eSjoerg assert(NumIRArgs == 0);
266506f32e7eSjoerg auto FieldIndex = ArgI.getInAllocaFieldIndex();
266606f32e7eSjoerg Address V =
266706f32e7eSjoerg Builder.CreateStructGEP(ArgStruct, FieldIndex, Arg->getName());
2668*13fbcb42Sjoerg if (ArgI.getInAllocaIndirect())
2669*13fbcb42Sjoerg V = Address(Builder.CreateLoad(V),
2670*13fbcb42Sjoerg getContext().getTypeAlignInChars(Ty));
267106f32e7eSjoerg ArgVals.push_back(ParamValue::forIndirect(V));
267206f32e7eSjoerg break;
267306f32e7eSjoerg }
267406f32e7eSjoerg
2675*13fbcb42Sjoerg case ABIArgInfo::Indirect:
2676*13fbcb42Sjoerg case ABIArgInfo::IndirectAliased: {
267706f32e7eSjoerg assert(NumIRArgs == 1);
2678*13fbcb42Sjoerg Address ParamAddr =
2679*13fbcb42Sjoerg Address(Fn->getArg(FirstIRArg), ArgI.getIndirectAlign());
268006f32e7eSjoerg
268106f32e7eSjoerg if (!hasScalarEvaluationKind(Ty)) {
268206f32e7eSjoerg // Aggregates and complex variables are accessed by reference. All we
2683*13fbcb42Sjoerg // need to do is realign the value, if requested. Also, if the address
2684*13fbcb42Sjoerg // may be aliased, copy it to ensure that the parameter variable is
2685*13fbcb42Sjoerg // mutable and has a unique adress, as C requires.
268606f32e7eSjoerg Address V = ParamAddr;
2687*13fbcb42Sjoerg if (ArgI.getIndirectRealign() || ArgI.isIndirectAliased()) {
268806f32e7eSjoerg Address AlignedTemp = CreateMemTemp(Ty, "coerce");
268906f32e7eSjoerg
269006f32e7eSjoerg // Copy from the incoming argument pointer to the temporary with the
269106f32e7eSjoerg // appropriate alignment.
269206f32e7eSjoerg //
269306f32e7eSjoerg // FIXME: We should have a common utility for generating an aggregate
269406f32e7eSjoerg // copy.
269506f32e7eSjoerg CharUnits Size = getContext().getTypeSizeInChars(Ty);
2696*13fbcb42Sjoerg Builder.CreateMemCpy(
2697*13fbcb42Sjoerg AlignedTemp.getPointer(), AlignedTemp.getAlignment().getAsAlign(),
2698*13fbcb42Sjoerg ParamAddr.getPointer(), ParamAddr.getAlignment().getAsAlign(),
2699*13fbcb42Sjoerg llvm::ConstantInt::get(IntPtrTy, Size.getQuantity()));
270006f32e7eSjoerg V = AlignedTemp;
270106f32e7eSjoerg }
270206f32e7eSjoerg ArgVals.push_back(ParamValue::forIndirect(V));
270306f32e7eSjoerg } else {
270406f32e7eSjoerg // Load scalar value from indirect argument.
270506f32e7eSjoerg llvm::Value *V =
270606f32e7eSjoerg EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getBeginLoc());
270706f32e7eSjoerg
270806f32e7eSjoerg if (isPromoted)
270906f32e7eSjoerg V = emitArgumentDemotion(*this, Arg, V);
271006f32e7eSjoerg ArgVals.push_back(ParamValue::forDirect(V));
271106f32e7eSjoerg }
271206f32e7eSjoerg break;
271306f32e7eSjoerg }
271406f32e7eSjoerg
271506f32e7eSjoerg case ABIArgInfo::Extend:
271606f32e7eSjoerg case ABIArgInfo::Direct: {
2717*13fbcb42Sjoerg auto AI = Fn->getArg(FirstIRArg);
2718*13fbcb42Sjoerg llvm::Type *LTy = ConvertType(Arg->getType());
271906f32e7eSjoerg
2720*13fbcb42Sjoerg // Prepare parameter attributes. So far, only attributes for pointer
2721*13fbcb42Sjoerg // parameters are prepared. See
2722*13fbcb42Sjoerg // http://llvm.org/docs/LangRef.html#paramattrs.
2723*13fbcb42Sjoerg if (ArgI.getDirectOffset() == 0 && LTy->isPointerTy() &&
2724*13fbcb42Sjoerg ArgI.getCoerceToType()->isPointerTy()) {
272506f32e7eSjoerg assert(NumIRArgs == 1);
272606f32e7eSjoerg
272706f32e7eSjoerg if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
2728*13fbcb42Sjoerg // Set `nonnull` attribute if any.
272906f32e7eSjoerg if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
273006f32e7eSjoerg PVD->getFunctionScopeIndex()) &&
273106f32e7eSjoerg !CGM.getCodeGenOpts().NullPointerIsValid)
273206f32e7eSjoerg AI->addAttr(llvm::Attribute::NonNull);
273306f32e7eSjoerg
273406f32e7eSjoerg QualType OTy = PVD->getOriginalType();
273506f32e7eSjoerg if (const auto *ArrTy =
273606f32e7eSjoerg getContext().getAsConstantArrayType(OTy)) {
273706f32e7eSjoerg // A C99 array parameter declaration with the static keyword also
273806f32e7eSjoerg // indicates dereferenceability, and if the size is constant we can
273906f32e7eSjoerg // use the dereferenceable attribute (which requires the size in
274006f32e7eSjoerg // bytes).
274106f32e7eSjoerg if (ArrTy->getSizeModifier() == ArrayType::Static) {
274206f32e7eSjoerg QualType ETy = ArrTy->getElementType();
2743*13fbcb42Sjoerg llvm::Align Alignment =
2744*13fbcb42Sjoerg CGM.getNaturalTypeAlignment(ETy).getAsAlign();
2745*13fbcb42Sjoerg AI->addAttrs(llvm::AttrBuilder().addAlignmentAttr(Alignment));
274606f32e7eSjoerg uint64_t ArrSize = ArrTy->getSize().getZExtValue();
274706f32e7eSjoerg if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
274806f32e7eSjoerg ArrSize) {
274906f32e7eSjoerg llvm::AttrBuilder Attrs;
275006f32e7eSjoerg Attrs.addDereferenceableAttr(
2751*13fbcb42Sjoerg getContext().getTypeSizeInChars(ETy).getQuantity() *
2752*13fbcb42Sjoerg ArrSize);
275306f32e7eSjoerg AI->addAttrs(Attrs);
2754*13fbcb42Sjoerg } else if (getContext().getTargetInfo().getNullPointerValue(
2755*13fbcb42Sjoerg ETy.getAddressSpace()) == 0 &&
275606f32e7eSjoerg !CGM.getCodeGenOpts().NullPointerIsValid) {
275706f32e7eSjoerg AI->addAttr(llvm::Attribute::NonNull);
275806f32e7eSjoerg }
275906f32e7eSjoerg }
276006f32e7eSjoerg } else if (const auto *ArrTy =
276106f32e7eSjoerg getContext().getAsVariableArrayType(OTy)) {
276206f32e7eSjoerg // For C99 VLAs with the static keyword, we don't know the size so
276306f32e7eSjoerg // we can't use the dereferenceable attribute, but in addrspace(0)
276406f32e7eSjoerg // we know that it must be nonnull.
2765*13fbcb42Sjoerg if (ArrTy->getSizeModifier() == VariableArrayType::Static) {
2766*13fbcb42Sjoerg QualType ETy = ArrTy->getElementType();
2767*13fbcb42Sjoerg llvm::Align Alignment =
2768*13fbcb42Sjoerg CGM.getNaturalTypeAlignment(ETy).getAsAlign();
2769*13fbcb42Sjoerg AI->addAttrs(llvm::AttrBuilder().addAlignmentAttr(Alignment));
2770*13fbcb42Sjoerg if (!getContext().getTargetAddressSpace(ETy) &&
277106f32e7eSjoerg !CGM.getCodeGenOpts().NullPointerIsValid)
277206f32e7eSjoerg AI->addAttr(llvm::Attribute::NonNull);
277306f32e7eSjoerg }
2774*13fbcb42Sjoerg }
277506f32e7eSjoerg
2776*13fbcb42Sjoerg // Set `align` attribute if any.
277706f32e7eSjoerg const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
277806f32e7eSjoerg if (!AVAttr)
277906f32e7eSjoerg if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
278006f32e7eSjoerg AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
278106f32e7eSjoerg if (AVAttr && !SanOpts.has(SanitizerKind::Alignment)) {
278206f32e7eSjoerg // If alignment-assumption sanitizer is enabled, we do *not* add
278306f32e7eSjoerg // alignment attribute here, but emit normal alignment assumption,
278406f32e7eSjoerg // so the UBSAN check could function.
278506f32e7eSjoerg llvm::ConstantInt *AlignmentCI =
2786*13fbcb42Sjoerg cast<llvm::ConstantInt>(EmitScalarExpr(AVAttr->getAlignment()));
2787*13fbcb42Sjoerg unsigned AlignmentInt =
2788*13fbcb42Sjoerg AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment);
2789*13fbcb42Sjoerg if (AI->getParamAlign().valueOrOne() < AlignmentInt) {
2790*13fbcb42Sjoerg AI->removeAttr(llvm::Attribute::AttrKind::Alignment);
2791*13fbcb42Sjoerg AI->addAttrs(llvm::AttrBuilder().addAlignmentAttr(
2792*13fbcb42Sjoerg llvm::Align(AlignmentInt)));
2793*13fbcb42Sjoerg }
279406f32e7eSjoerg }
279506f32e7eSjoerg }
279606f32e7eSjoerg
2797*13fbcb42Sjoerg // Set 'noalias' if an argument type has the `restrict` qualifier.
279806f32e7eSjoerg if (Arg->getType().isRestrictQualified())
279906f32e7eSjoerg AI->addAttr(llvm::Attribute::NoAlias);
2800*13fbcb42Sjoerg }
2801*13fbcb42Sjoerg
2802*13fbcb42Sjoerg // Prepare the argument value. If we have the trivial case, handle it
2803*13fbcb42Sjoerg // with no muss and fuss.
2804*13fbcb42Sjoerg if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
2805*13fbcb42Sjoerg ArgI.getCoerceToType() == ConvertType(Ty) &&
2806*13fbcb42Sjoerg ArgI.getDirectOffset() == 0) {
2807*13fbcb42Sjoerg assert(NumIRArgs == 1);
280806f32e7eSjoerg
280906f32e7eSjoerg // LLVM expects swifterror parameters to be used in very restricted
281006f32e7eSjoerg // ways. Copy the value into a less-restricted temporary.
2811*13fbcb42Sjoerg llvm::Value *V = AI;
281206f32e7eSjoerg if (FI.getExtParameterInfo(ArgNo).getABI()
281306f32e7eSjoerg == ParameterABI::SwiftErrorResult) {
281406f32e7eSjoerg QualType pointeeTy = Ty->getPointeeType();
281506f32e7eSjoerg assert(pointeeTy->isPointerType());
281606f32e7eSjoerg Address temp =
281706f32e7eSjoerg CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
281806f32e7eSjoerg Address arg = Address(V, getContext().getTypeAlignInChars(pointeeTy));
281906f32e7eSjoerg llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
282006f32e7eSjoerg Builder.CreateStore(incomingErrorValue, temp);
282106f32e7eSjoerg V = temp.getPointer();
282206f32e7eSjoerg
282306f32e7eSjoerg // Push a cleanup to copy the value back at the end of the function.
282406f32e7eSjoerg // The convention does not guarantee that the value will be written
282506f32e7eSjoerg // back if the function exits with an unwind exception.
282606f32e7eSjoerg EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
282706f32e7eSjoerg }
282806f32e7eSjoerg
282906f32e7eSjoerg // Ensure the argument is the correct type.
283006f32e7eSjoerg if (V->getType() != ArgI.getCoerceToType())
283106f32e7eSjoerg V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
283206f32e7eSjoerg
283306f32e7eSjoerg if (isPromoted)
283406f32e7eSjoerg V = emitArgumentDemotion(*this, Arg, V);
283506f32e7eSjoerg
283606f32e7eSjoerg // Because of merging of function types from multiple decls it is
283706f32e7eSjoerg // possible for the type of an argument to not match the corresponding
283806f32e7eSjoerg // type in the function type. Since we are codegening the callee
283906f32e7eSjoerg // in here, add a cast to the argument type.
284006f32e7eSjoerg llvm::Type *LTy = ConvertType(Arg->getType());
284106f32e7eSjoerg if (V->getType() != LTy)
284206f32e7eSjoerg V = Builder.CreateBitCast(V, LTy);
284306f32e7eSjoerg
284406f32e7eSjoerg ArgVals.push_back(ParamValue::forDirect(V));
284506f32e7eSjoerg break;
284606f32e7eSjoerg }
284706f32e7eSjoerg
2848*13fbcb42Sjoerg // VLST arguments are coerced to VLATs at the function boundary for
2849*13fbcb42Sjoerg // ABI consistency. If this is a VLST that was coerced to
2850*13fbcb42Sjoerg // a VLAT at the function boundary and the types match up, use
2851*13fbcb42Sjoerg // llvm.experimental.vector.extract to convert back to the original
2852*13fbcb42Sjoerg // VLST.
2853*13fbcb42Sjoerg if (auto *VecTyTo = dyn_cast<llvm::FixedVectorType>(ConvertType(Ty))) {
2854*13fbcb42Sjoerg auto *Coerced = Fn->getArg(FirstIRArg);
2855*13fbcb42Sjoerg if (auto *VecTyFrom =
2856*13fbcb42Sjoerg dyn_cast<llvm::ScalableVectorType>(Coerced->getType())) {
2857*13fbcb42Sjoerg if (VecTyFrom->getElementType() == VecTyTo->getElementType()) {
2858*13fbcb42Sjoerg llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int64Ty);
2859*13fbcb42Sjoerg
2860*13fbcb42Sjoerg assert(NumIRArgs == 1);
2861*13fbcb42Sjoerg Coerced->setName(Arg->getName() + ".coerce");
2862*13fbcb42Sjoerg ArgVals.push_back(ParamValue::forDirect(Builder.CreateExtractVector(
2863*13fbcb42Sjoerg VecTyTo, Coerced, Zero, "castFixedSve")));
2864*13fbcb42Sjoerg break;
2865*13fbcb42Sjoerg }
2866*13fbcb42Sjoerg }
2867*13fbcb42Sjoerg }
2868*13fbcb42Sjoerg
286906f32e7eSjoerg Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
287006f32e7eSjoerg Arg->getName());
287106f32e7eSjoerg
287206f32e7eSjoerg // Pointer to store into.
287306f32e7eSjoerg Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
287406f32e7eSjoerg
287506f32e7eSjoerg // Fast-isel and the optimizer generally like scalar values better than
287606f32e7eSjoerg // FCAs, so we flatten them if this is safe to do for this argument.
287706f32e7eSjoerg llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
287806f32e7eSjoerg if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
287906f32e7eSjoerg STy->getNumElements() > 1) {
288006f32e7eSjoerg uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
288106f32e7eSjoerg llvm::Type *DstTy = Ptr.getElementType();
288206f32e7eSjoerg uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
288306f32e7eSjoerg
288406f32e7eSjoerg Address AddrToStoreInto = Address::invalid();
288506f32e7eSjoerg if (SrcSize <= DstSize) {
288606f32e7eSjoerg AddrToStoreInto = Builder.CreateElementBitCast(Ptr, STy);
288706f32e7eSjoerg } else {
288806f32e7eSjoerg AddrToStoreInto =
288906f32e7eSjoerg CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
289006f32e7eSjoerg }
289106f32e7eSjoerg
289206f32e7eSjoerg assert(STy->getNumElements() == NumIRArgs);
289306f32e7eSjoerg for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2894*13fbcb42Sjoerg auto AI = Fn->getArg(FirstIRArg + i);
289506f32e7eSjoerg AI->setName(Arg->getName() + ".coerce" + Twine(i));
289606f32e7eSjoerg Address EltPtr = Builder.CreateStructGEP(AddrToStoreInto, i);
289706f32e7eSjoerg Builder.CreateStore(AI, EltPtr);
289806f32e7eSjoerg }
289906f32e7eSjoerg
290006f32e7eSjoerg if (SrcSize > DstSize) {
290106f32e7eSjoerg Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
290206f32e7eSjoerg }
290306f32e7eSjoerg
290406f32e7eSjoerg } else {
290506f32e7eSjoerg // Simple case, just do a coerced store of the argument into the alloca.
290606f32e7eSjoerg assert(NumIRArgs == 1);
2907*13fbcb42Sjoerg auto AI = Fn->getArg(FirstIRArg);
290806f32e7eSjoerg AI->setName(Arg->getName() + ".coerce");
290906f32e7eSjoerg CreateCoercedStore(AI, Ptr, /*DstIsVolatile=*/false, *this);
291006f32e7eSjoerg }
291106f32e7eSjoerg
291206f32e7eSjoerg // Match to what EmitParmDecl is expecting for this type.
291306f32e7eSjoerg if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
291406f32e7eSjoerg llvm::Value *V =
291506f32e7eSjoerg EmitLoadOfScalar(Alloca, false, Ty, Arg->getBeginLoc());
291606f32e7eSjoerg if (isPromoted)
291706f32e7eSjoerg V = emitArgumentDemotion(*this, Arg, V);
291806f32e7eSjoerg ArgVals.push_back(ParamValue::forDirect(V));
291906f32e7eSjoerg } else {
292006f32e7eSjoerg ArgVals.push_back(ParamValue::forIndirect(Alloca));
292106f32e7eSjoerg }
292206f32e7eSjoerg break;
292306f32e7eSjoerg }
292406f32e7eSjoerg
292506f32e7eSjoerg case ABIArgInfo::CoerceAndExpand: {
292606f32e7eSjoerg // Reconstruct into a temporary.
292706f32e7eSjoerg Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
292806f32e7eSjoerg ArgVals.push_back(ParamValue::forIndirect(alloca));
292906f32e7eSjoerg
293006f32e7eSjoerg auto coercionType = ArgI.getCoerceAndExpandType();
293106f32e7eSjoerg alloca = Builder.CreateElementBitCast(alloca, coercionType);
293206f32e7eSjoerg
293306f32e7eSjoerg unsigned argIndex = FirstIRArg;
293406f32e7eSjoerg for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
293506f32e7eSjoerg llvm::Type *eltType = coercionType->getElementType(i);
293606f32e7eSjoerg if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
293706f32e7eSjoerg continue;
293806f32e7eSjoerg
293906f32e7eSjoerg auto eltAddr = Builder.CreateStructGEP(alloca, i);
2940*13fbcb42Sjoerg auto elt = Fn->getArg(argIndex++);
294106f32e7eSjoerg Builder.CreateStore(elt, eltAddr);
294206f32e7eSjoerg }
294306f32e7eSjoerg assert(argIndex == FirstIRArg + NumIRArgs);
294406f32e7eSjoerg break;
294506f32e7eSjoerg }
294606f32e7eSjoerg
294706f32e7eSjoerg case ABIArgInfo::Expand: {
294806f32e7eSjoerg // If this structure was expanded into multiple arguments then
294906f32e7eSjoerg // we need to create a temporary and reconstruct it from the
295006f32e7eSjoerg // arguments.
295106f32e7eSjoerg Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
295206f32e7eSjoerg LValue LV = MakeAddrLValue(Alloca, Ty);
295306f32e7eSjoerg ArgVals.push_back(ParamValue::forIndirect(Alloca));
295406f32e7eSjoerg
2955*13fbcb42Sjoerg auto FnArgIter = Fn->arg_begin() + FirstIRArg;
295606f32e7eSjoerg ExpandTypeFromArgs(Ty, LV, FnArgIter);
2957*13fbcb42Sjoerg assert(FnArgIter == Fn->arg_begin() + FirstIRArg + NumIRArgs);
295806f32e7eSjoerg for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
2959*13fbcb42Sjoerg auto AI = Fn->getArg(FirstIRArg + i);
296006f32e7eSjoerg AI->setName(Arg->getName() + "." + Twine(i));
296106f32e7eSjoerg }
296206f32e7eSjoerg break;
296306f32e7eSjoerg }
296406f32e7eSjoerg
296506f32e7eSjoerg case ABIArgInfo::Ignore:
296606f32e7eSjoerg assert(NumIRArgs == 0);
296706f32e7eSjoerg // Initialize the local variable appropriately.
296806f32e7eSjoerg if (!hasScalarEvaluationKind(Ty)) {
296906f32e7eSjoerg ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
297006f32e7eSjoerg } else {
297106f32e7eSjoerg llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
297206f32e7eSjoerg ArgVals.push_back(ParamValue::forDirect(U));
297306f32e7eSjoerg }
297406f32e7eSjoerg break;
297506f32e7eSjoerg }
297606f32e7eSjoerg }
297706f32e7eSjoerg
297806f32e7eSjoerg if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
297906f32e7eSjoerg for (int I = Args.size() - 1; I >= 0; --I)
298006f32e7eSjoerg EmitParmDecl(*Args[I], ArgVals[I], I + 1);
298106f32e7eSjoerg } else {
298206f32e7eSjoerg for (unsigned I = 0, E = Args.size(); I != E; ++I)
298306f32e7eSjoerg EmitParmDecl(*Args[I], ArgVals[I], I + 1);
298406f32e7eSjoerg }
298506f32e7eSjoerg }
298606f32e7eSjoerg
eraseUnusedBitCasts(llvm::Instruction * insn)298706f32e7eSjoerg static void eraseUnusedBitCasts(llvm::Instruction *insn) {
298806f32e7eSjoerg while (insn->use_empty()) {
298906f32e7eSjoerg llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
299006f32e7eSjoerg if (!bitcast) return;
299106f32e7eSjoerg
299206f32e7eSjoerg // This is "safe" because we would have used a ConstantExpr otherwise.
299306f32e7eSjoerg insn = cast<llvm::Instruction>(bitcast->getOperand(0));
299406f32e7eSjoerg bitcast->eraseFromParent();
299506f32e7eSjoerg }
299606f32e7eSjoerg }
299706f32e7eSjoerg
299806f32e7eSjoerg /// Try to emit a fused autorelease of a return result.
tryEmitFusedAutoreleaseOfResult(CodeGenFunction & CGF,llvm::Value * result)299906f32e7eSjoerg static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
300006f32e7eSjoerg llvm::Value *result) {
300106f32e7eSjoerg // We must be immediately followed the cast.
300206f32e7eSjoerg llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
300306f32e7eSjoerg if (BB->empty()) return nullptr;
300406f32e7eSjoerg if (&BB->back() != result) return nullptr;
300506f32e7eSjoerg
300606f32e7eSjoerg llvm::Type *resultType = result->getType();
300706f32e7eSjoerg
300806f32e7eSjoerg // result is in a BasicBlock and is therefore an Instruction.
300906f32e7eSjoerg llvm::Instruction *generator = cast<llvm::Instruction>(result);
301006f32e7eSjoerg
301106f32e7eSjoerg SmallVector<llvm::Instruction *, 4> InstsToKill;
301206f32e7eSjoerg
301306f32e7eSjoerg // Look for:
301406f32e7eSjoerg // %generator = bitcast %type1* %generator2 to %type2*
301506f32e7eSjoerg while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
301606f32e7eSjoerg // We would have emitted this as a constant if the operand weren't
301706f32e7eSjoerg // an Instruction.
301806f32e7eSjoerg generator = cast<llvm::Instruction>(bitcast->getOperand(0));
301906f32e7eSjoerg
302006f32e7eSjoerg // Require the generator to be immediately followed by the cast.
302106f32e7eSjoerg if (generator->getNextNode() != bitcast)
302206f32e7eSjoerg return nullptr;
302306f32e7eSjoerg
302406f32e7eSjoerg InstsToKill.push_back(bitcast);
302506f32e7eSjoerg }
302606f32e7eSjoerg
302706f32e7eSjoerg // Look for:
302806f32e7eSjoerg // %generator = call i8* @objc_retain(i8* %originalResult)
302906f32e7eSjoerg // or
303006f32e7eSjoerg // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
303106f32e7eSjoerg llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
303206f32e7eSjoerg if (!call) return nullptr;
303306f32e7eSjoerg
303406f32e7eSjoerg bool doRetainAutorelease;
303506f32e7eSjoerg
3036*13fbcb42Sjoerg if (call->getCalledOperand() == CGF.CGM.getObjCEntrypoints().objc_retain) {
303706f32e7eSjoerg doRetainAutorelease = true;
3038*13fbcb42Sjoerg } else if (call->getCalledOperand() ==
3039*13fbcb42Sjoerg CGF.CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue) {
304006f32e7eSjoerg doRetainAutorelease = false;
304106f32e7eSjoerg
304206f32e7eSjoerg // If we emitted an assembly marker for this call (and the
304306f32e7eSjoerg // ARCEntrypoints field should have been set if so), go looking
304406f32e7eSjoerg // for that call. If we can't find it, we can't do this
304506f32e7eSjoerg // optimization. But it should always be the immediately previous
304606f32e7eSjoerg // instruction, unless we needed bitcasts around the call.
304706f32e7eSjoerg if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
304806f32e7eSjoerg llvm::Instruction *prev = call->getPrevNode();
304906f32e7eSjoerg assert(prev);
305006f32e7eSjoerg if (isa<llvm::BitCastInst>(prev)) {
305106f32e7eSjoerg prev = prev->getPrevNode();
305206f32e7eSjoerg assert(prev);
305306f32e7eSjoerg }
305406f32e7eSjoerg assert(isa<llvm::CallInst>(prev));
3055*13fbcb42Sjoerg assert(cast<llvm::CallInst>(prev)->getCalledOperand() ==
305606f32e7eSjoerg CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
305706f32e7eSjoerg InstsToKill.push_back(prev);
305806f32e7eSjoerg }
305906f32e7eSjoerg } else {
306006f32e7eSjoerg return nullptr;
306106f32e7eSjoerg }
306206f32e7eSjoerg
306306f32e7eSjoerg result = call->getArgOperand(0);
306406f32e7eSjoerg InstsToKill.push_back(call);
306506f32e7eSjoerg
306606f32e7eSjoerg // Keep killing bitcasts, for sanity. Note that we no longer care
306706f32e7eSjoerg // about precise ordering as long as there's exactly one use.
306806f32e7eSjoerg while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
306906f32e7eSjoerg if (!bitcast->hasOneUse()) break;
307006f32e7eSjoerg InstsToKill.push_back(bitcast);
307106f32e7eSjoerg result = bitcast->getOperand(0);
307206f32e7eSjoerg }
307306f32e7eSjoerg
307406f32e7eSjoerg // Delete all the unnecessary instructions, from latest to earliest.
307506f32e7eSjoerg for (auto *I : InstsToKill)
307606f32e7eSjoerg I->eraseFromParent();
307706f32e7eSjoerg
307806f32e7eSjoerg // Do the fused retain/autorelease if we were asked to.
307906f32e7eSjoerg if (doRetainAutorelease)
308006f32e7eSjoerg result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
308106f32e7eSjoerg
308206f32e7eSjoerg // Cast back to the result type.
308306f32e7eSjoerg return CGF.Builder.CreateBitCast(result, resultType);
308406f32e7eSjoerg }
308506f32e7eSjoerg
308606f32e7eSjoerg /// If this is a +1 of the value of an immutable 'self', remove it.
tryRemoveRetainOfSelf(CodeGenFunction & CGF,llvm::Value * result)308706f32e7eSjoerg static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
308806f32e7eSjoerg llvm::Value *result) {
308906f32e7eSjoerg // This is only applicable to a method with an immutable 'self'.
309006f32e7eSjoerg const ObjCMethodDecl *method =
309106f32e7eSjoerg dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
309206f32e7eSjoerg if (!method) return nullptr;
309306f32e7eSjoerg const VarDecl *self = method->getSelfDecl();
309406f32e7eSjoerg if (!self->getType().isConstQualified()) return nullptr;
309506f32e7eSjoerg
309606f32e7eSjoerg // Look for a retain call.
309706f32e7eSjoerg llvm::CallInst *retainCall =
309806f32e7eSjoerg dyn_cast<llvm::CallInst>(result->stripPointerCasts());
3099*13fbcb42Sjoerg if (!retainCall || retainCall->getCalledOperand() !=
3100*13fbcb42Sjoerg CGF.CGM.getObjCEntrypoints().objc_retain)
310106f32e7eSjoerg return nullptr;
310206f32e7eSjoerg
310306f32e7eSjoerg // Look for an ordinary load of 'self'.
310406f32e7eSjoerg llvm::Value *retainedValue = retainCall->getArgOperand(0);
310506f32e7eSjoerg llvm::LoadInst *load =
310606f32e7eSjoerg dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
310706f32e7eSjoerg if (!load || load->isAtomic() || load->isVolatile() ||
310806f32e7eSjoerg load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
310906f32e7eSjoerg return nullptr;
311006f32e7eSjoerg
311106f32e7eSjoerg // Okay! Burn it all down. This relies for correctness on the
311206f32e7eSjoerg // assumption that the retain is emitted as part of the return and
311306f32e7eSjoerg // that thereafter everything is used "linearly".
311406f32e7eSjoerg llvm::Type *resultType = result->getType();
311506f32e7eSjoerg eraseUnusedBitCasts(cast<llvm::Instruction>(result));
311606f32e7eSjoerg assert(retainCall->use_empty());
311706f32e7eSjoerg retainCall->eraseFromParent();
311806f32e7eSjoerg eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
311906f32e7eSjoerg
312006f32e7eSjoerg return CGF.Builder.CreateBitCast(load, resultType);
312106f32e7eSjoerg }
312206f32e7eSjoerg
312306f32e7eSjoerg /// Emit an ARC autorelease of the result of a function.
312406f32e7eSjoerg ///
312506f32e7eSjoerg /// \return the value to actually return from the function
emitAutoreleaseOfResult(CodeGenFunction & CGF,llvm::Value * result)312606f32e7eSjoerg static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
312706f32e7eSjoerg llvm::Value *result) {
312806f32e7eSjoerg // If we're returning 'self', kill the initial retain. This is a
312906f32e7eSjoerg // heuristic attempt to "encourage correctness" in the really unfortunate
313006f32e7eSjoerg // case where we have a return of self during a dealloc and we desperately
313106f32e7eSjoerg // need to avoid the possible autorelease.
313206f32e7eSjoerg if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
313306f32e7eSjoerg return self;
313406f32e7eSjoerg
313506f32e7eSjoerg // At -O0, try to emit a fused retain/autorelease.
313606f32e7eSjoerg if (CGF.shouldUseFusedARCCalls())
313706f32e7eSjoerg if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
313806f32e7eSjoerg return fused;
313906f32e7eSjoerg
314006f32e7eSjoerg return CGF.EmitARCAutoreleaseReturnValue(result);
314106f32e7eSjoerg }
314206f32e7eSjoerg
314306f32e7eSjoerg /// Heuristically search for a dominating store to the return-value slot.
findDominatingStoreToReturnValue(CodeGenFunction & CGF)314406f32e7eSjoerg static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
314506f32e7eSjoerg // Check if a User is a store which pointerOperand is the ReturnValue.
314606f32e7eSjoerg // We are looking for stores to the ReturnValue, not for stores of the
314706f32e7eSjoerg // ReturnValue to some other location.
314806f32e7eSjoerg auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
314906f32e7eSjoerg auto *SI = dyn_cast<llvm::StoreInst>(U);
315006f32e7eSjoerg if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer())
315106f32e7eSjoerg return nullptr;
315206f32e7eSjoerg // These aren't actually possible for non-coerced returns, and we
315306f32e7eSjoerg // only care about non-coerced returns on this code path.
315406f32e7eSjoerg assert(!SI->isAtomic() && !SI->isVolatile());
315506f32e7eSjoerg return SI;
315606f32e7eSjoerg };
315706f32e7eSjoerg // If there are multiple uses of the return-value slot, just check
315806f32e7eSjoerg // for something immediately preceding the IP. Sometimes this can
315906f32e7eSjoerg // happen with how we generate implicit-returns; it can also happen
316006f32e7eSjoerg // with noreturn cleanups.
316106f32e7eSjoerg if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
316206f32e7eSjoerg llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
316306f32e7eSjoerg if (IP->empty()) return nullptr;
316406f32e7eSjoerg llvm::Instruction *I = &IP->back();
316506f32e7eSjoerg
316606f32e7eSjoerg // Skip lifetime markers
316706f32e7eSjoerg for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
316806f32e7eSjoerg IE = IP->rend();
316906f32e7eSjoerg II != IE; ++II) {
317006f32e7eSjoerg if (llvm::IntrinsicInst *Intrinsic =
317106f32e7eSjoerg dyn_cast<llvm::IntrinsicInst>(&*II)) {
317206f32e7eSjoerg if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
317306f32e7eSjoerg const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
317406f32e7eSjoerg ++II;
317506f32e7eSjoerg if (II == IE)
317606f32e7eSjoerg break;
317706f32e7eSjoerg if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
317806f32e7eSjoerg continue;
317906f32e7eSjoerg }
318006f32e7eSjoerg }
318106f32e7eSjoerg I = &*II;
318206f32e7eSjoerg break;
318306f32e7eSjoerg }
318406f32e7eSjoerg
318506f32e7eSjoerg return GetStoreIfValid(I);
318606f32e7eSjoerg }
318706f32e7eSjoerg
318806f32e7eSjoerg llvm::StoreInst *store =
318906f32e7eSjoerg GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
319006f32e7eSjoerg if (!store) return nullptr;
319106f32e7eSjoerg
319206f32e7eSjoerg // Now do a first-and-dirty dominance check: just walk up the
319306f32e7eSjoerg // single-predecessors chain from the current insertion point.
319406f32e7eSjoerg llvm::BasicBlock *StoreBB = store->getParent();
319506f32e7eSjoerg llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
319606f32e7eSjoerg while (IP != StoreBB) {
319706f32e7eSjoerg if (!(IP = IP->getSinglePredecessor()))
319806f32e7eSjoerg return nullptr;
319906f32e7eSjoerg }
320006f32e7eSjoerg
320106f32e7eSjoerg // Okay, the store's basic block dominates the insertion point; we
320206f32e7eSjoerg // can do our thing.
320306f32e7eSjoerg return store;
320406f32e7eSjoerg }
320506f32e7eSjoerg
3206*13fbcb42Sjoerg // Helper functions for EmitCMSEClearRecord
3207*13fbcb42Sjoerg
3208*13fbcb42Sjoerg // Set the bits corresponding to a field having width `BitWidth` and located at
3209*13fbcb42Sjoerg // offset `BitOffset` (from the least significant bit) within a storage unit of
3210*13fbcb42Sjoerg // `Bits.size()` bytes. Each element of `Bits` corresponds to one target byte.
3211*13fbcb42Sjoerg // Use little-endian layout, i.e.`Bits[0]` is the LSB.
setBitRange(SmallVectorImpl<uint64_t> & Bits,int BitOffset,int BitWidth,int CharWidth)3212*13fbcb42Sjoerg static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int BitOffset,
3213*13fbcb42Sjoerg int BitWidth, int CharWidth) {
3214*13fbcb42Sjoerg assert(CharWidth <= 64);
3215*13fbcb42Sjoerg assert(static_cast<unsigned>(BitWidth) <= Bits.size() * CharWidth);
3216*13fbcb42Sjoerg
3217*13fbcb42Sjoerg int Pos = 0;
3218*13fbcb42Sjoerg if (BitOffset >= CharWidth) {
3219*13fbcb42Sjoerg Pos += BitOffset / CharWidth;
3220*13fbcb42Sjoerg BitOffset = BitOffset % CharWidth;
3221*13fbcb42Sjoerg }
3222*13fbcb42Sjoerg
3223*13fbcb42Sjoerg const uint64_t Used = (uint64_t(1) << CharWidth) - 1;
3224*13fbcb42Sjoerg if (BitOffset + BitWidth >= CharWidth) {
3225*13fbcb42Sjoerg Bits[Pos++] |= (Used << BitOffset) & Used;
3226*13fbcb42Sjoerg BitWidth -= CharWidth - BitOffset;
3227*13fbcb42Sjoerg BitOffset = 0;
3228*13fbcb42Sjoerg }
3229*13fbcb42Sjoerg
3230*13fbcb42Sjoerg while (BitWidth >= CharWidth) {
3231*13fbcb42Sjoerg Bits[Pos++] = Used;
3232*13fbcb42Sjoerg BitWidth -= CharWidth;
3233*13fbcb42Sjoerg }
3234*13fbcb42Sjoerg
3235*13fbcb42Sjoerg if (BitWidth > 0)
3236*13fbcb42Sjoerg Bits[Pos++] |= (Used >> (CharWidth - BitWidth)) << BitOffset;
3237*13fbcb42Sjoerg }
3238*13fbcb42Sjoerg
3239*13fbcb42Sjoerg // Set the bits corresponding to a field having width `BitWidth` and located at
3240*13fbcb42Sjoerg // offset `BitOffset` (from the least significant bit) within a storage unit of
3241*13fbcb42Sjoerg // `StorageSize` bytes, located at `StorageOffset` in `Bits`. Each element of
3242*13fbcb42Sjoerg // `Bits` corresponds to one target byte. Use target endian layout.
setBitRange(SmallVectorImpl<uint64_t> & Bits,int StorageOffset,int StorageSize,int BitOffset,int BitWidth,int CharWidth,bool BigEndian)3243*13fbcb42Sjoerg static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int StorageOffset,
3244*13fbcb42Sjoerg int StorageSize, int BitOffset, int BitWidth,
3245*13fbcb42Sjoerg int CharWidth, bool BigEndian) {
3246*13fbcb42Sjoerg
3247*13fbcb42Sjoerg SmallVector<uint64_t, 8> TmpBits(StorageSize);
3248*13fbcb42Sjoerg setBitRange(TmpBits, BitOffset, BitWidth, CharWidth);
3249*13fbcb42Sjoerg
3250*13fbcb42Sjoerg if (BigEndian)
3251*13fbcb42Sjoerg std::reverse(TmpBits.begin(), TmpBits.end());
3252*13fbcb42Sjoerg
3253*13fbcb42Sjoerg for (uint64_t V : TmpBits)
3254*13fbcb42Sjoerg Bits[StorageOffset++] |= V;
3255*13fbcb42Sjoerg }
3256*13fbcb42Sjoerg
3257*13fbcb42Sjoerg static void setUsedBits(CodeGenModule &, QualType, int,
3258*13fbcb42Sjoerg SmallVectorImpl<uint64_t> &);
3259*13fbcb42Sjoerg
3260*13fbcb42Sjoerg // Set the bits in `Bits`, which correspond to the value representations of
3261*13fbcb42Sjoerg // the actual members of the record type `RTy`. Note that this function does
3262*13fbcb42Sjoerg // not handle base classes, virtual tables, etc, since they cannot happen in
3263*13fbcb42Sjoerg // CMSE function arguments or return. The bit mask corresponds to the target
3264*13fbcb42Sjoerg // memory layout, i.e. it's endian dependent.
setUsedBits(CodeGenModule & CGM,const RecordType * RTy,int Offset,SmallVectorImpl<uint64_t> & Bits)3265*13fbcb42Sjoerg static void setUsedBits(CodeGenModule &CGM, const RecordType *RTy, int Offset,
3266*13fbcb42Sjoerg SmallVectorImpl<uint64_t> &Bits) {
3267*13fbcb42Sjoerg ASTContext &Context = CGM.getContext();
3268*13fbcb42Sjoerg int CharWidth = Context.getCharWidth();
3269*13fbcb42Sjoerg const RecordDecl *RD = RTy->getDecl()->getDefinition();
3270*13fbcb42Sjoerg const ASTRecordLayout &ASTLayout = Context.getASTRecordLayout(RD);
3271*13fbcb42Sjoerg const CGRecordLayout &Layout = CGM.getTypes().getCGRecordLayout(RD);
3272*13fbcb42Sjoerg
3273*13fbcb42Sjoerg int Idx = 0;
3274*13fbcb42Sjoerg for (auto I = RD->field_begin(), E = RD->field_end(); I != E; ++I, ++Idx) {
3275*13fbcb42Sjoerg const FieldDecl *F = *I;
3276*13fbcb42Sjoerg
3277*13fbcb42Sjoerg if (F->isUnnamedBitfield() || F->isZeroLengthBitField(Context) ||
3278*13fbcb42Sjoerg F->getType()->isIncompleteArrayType())
3279*13fbcb42Sjoerg continue;
3280*13fbcb42Sjoerg
3281*13fbcb42Sjoerg if (F->isBitField()) {
3282*13fbcb42Sjoerg const CGBitFieldInfo &BFI = Layout.getBitFieldInfo(F);
3283*13fbcb42Sjoerg setBitRange(Bits, Offset + BFI.StorageOffset.getQuantity(),
3284*13fbcb42Sjoerg BFI.StorageSize / CharWidth, BFI.Offset,
3285*13fbcb42Sjoerg BFI.Size, CharWidth,
3286*13fbcb42Sjoerg CGM.getDataLayout().isBigEndian());
3287*13fbcb42Sjoerg continue;
3288*13fbcb42Sjoerg }
3289*13fbcb42Sjoerg
3290*13fbcb42Sjoerg setUsedBits(CGM, F->getType(),
3291*13fbcb42Sjoerg Offset + ASTLayout.getFieldOffset(Idx) / CharWidth, Bits);
3292*13fbcb42Sjoerg }
3293*13fbcb42Sjoerg }
3294*13fbcb42Sjoerg
3295*13fbcb42Sjoerg // Set the bits in `Bits`, which correspond to the value representations of
3296*13fbcb42Sjoerg // the elements of an array type `ATy`.
setUsedBits(CodeGenModule & CGM,const ConstantArrayType * ATy,int Offset,SmallVectorImpl<uint64_t> & Bits)3297*13fbcb42Sjoerg static void setUsedBits(CodeGenModule &CGM, const ConstantArrayType *ATy,
3298*13fbcb42Sjoerg int Offset, SmallVectorImpl<uint64_t> &Bits) {
3299*13fbcb42Sjoerg const ASTContext &Context = CGM.getContext();
3300*13fbcb42Sjoerg
3301*13fbcb42Sjoerg QualType ETy = Context.getBaseElementType(ATy);
3302*13fbcb42Sjoerg int Size = Context.getTypeSizeInChars(ETy).getQuantity();
3303*13fbcb42Sjoerg SmallVector<uint64_t, 4> TmpBits(Size);
3304*13fbcb42Sjoerg setUsedBits(CGM, ETy, 0, TmpBits);
3305*13fbcb42Sjoerg
3306*13fbcb42Sjoerg for (int I = 0, N = Context.getConstantArrayElementCount(ATy); I < N; ++I) {
3307*13fbcb42Sjoerg auto Src = TmpBits.begin();
3308*13fbcb42Sjoerg auto Dst = Bits.begin() + Offset + I * Size;
3309*13fbcb42Sjoerg for (int J = 0; J < Size; ++J)
3310*13fbcb42Sjoerg *Dst++ |= *Src++;
3311*13fbcb42Sjoerg }
3312*13fbcb42Sjoerg }
3313*13fbcb42Sjoerg
3314*13fbcb42Sjoerg // Set the bits in `Bits`, which correspond to the value representations of
3315*13fbcb42Sjoerg // the type `QTy`.
setUsedBits(CodeGenModule & CGM,QualType QTy,int Offset,SmallVectorImpl<uint64_t> & Bits)3316*13fbcb42Sjoerg static void setUsedBits(CodeGenModule &CGM, QualType QTy, int Offset,
3317*13fbcb42Sjoerg SmallVectorImpl<uint64_t> &Bits) {
3318*13fbcb42Sjoerg if (const auto *RTy = QTy->getAs<RecordType>())
3319*13fbcb42Sjoerg return setUsedBits(CGM, RTy, Offset, Bits);
3320*13fbcb42Sjoerg
3321*13fbcb42Sjoerg ASTContext &Context = CGM.getContext();
3322*13fbcb42Sjoerg if (const auto *ATy = Context.getAsConstantArrayType(QTy))
3323*13fbcb42Sjoerg return setUsedBits(CGM, ATy, Offset, Bits);
3324*13fbcb42Sjoerg
3325*13fbcb42Sjoerg int Size = Context.getTypeSizeInChars(QTy).getQuantity();
3326*13fbcb42Sjoerg if (Size <= 0)
3327*13fbcb42Sjoerg return;
3328*13fbcb42Sjoerg
3329*13fbcb42Sjoerg std::fill_n(Bits.begin() + Offset, Size,
3330*13fbcb42Sjoerg (uint64_t(1) << Context.getCharWidth()) - 1);
3331*13fbcb42Sjoerg }
3332*13fbcb42Sjoerg
buildMultiCharMask(const SmallVectorImpl<uint64_t> & Bits,int Pos,int Size,int CharWidth,bool BigEndian)3333*13fbcb42Sjoerg static uint64_t buildMultiCharMask(const SmallVectorImpl<uint64_t> &Bits,
3334*13fbcb42Sjoerg int Pos, int Size, int CharWidth,
3335*13fbcb42Sjoerg bool BigEndian) {
3336*13fbcb42Sjoerg assert(Size > 0);
3337*13fbcb42Sjoerg uint64_t Mask = 0;
3338*13fbcb42Sjoerg if (BigEndian) {
3339*13fbcb42Sjoerg for (auto P = Bits.begin() + Pos, E = Bits.begin() + Pos + Size; P != E;
3340*13fbcb42Sjoerg ++P)
3341*13fbcb42Sjoerg Mask = (Mask << CharWidth) | *P;
3342*13fbcb42Sjoerg } else {
3343*13fbcb42Sjoerg auto P = Bits.begin() + Pos + Size, End = Bits.begin() + Pos;
3344*13fbcb42Sjoerg do
3345*13fbcb42Sjoerg Mask = (Mask << CharWidth) | *--P;
3346*13fbcb42Sjoerg while (P != End);
3347*13fbcb42Sjoerg }
3348*13fbcb42Sjoerg return Mask;
3349*13fbcb42Sjoerg }
3350*13fbcb42Sjoerg
3351*13fbcb42Sjoerg // Emit code to clear the bits in a record, which aren't a part of any user
3352*13fbcb42Sjoerg // declared member, when the record is a function return.
EmitCMSEClearRecord(llvm::Value * Src,llvm::IntegerType * ITy,QualType QTy)3353*13fbcb42Sjoerg llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
3354*13fbcb42Sjoerg llvm::IntegerType *ITy,
3355*13fbcb42Sjoerg QualType QTy) {
3356*13fbcb42Sjoerg assert(Src->getType() == ITy);
3357*13fbcb42Sjoerg assert(ITy->getScalarSizeInBits() <= 64);
3358*13fbcb42Sjoerg
3359*13fbcb42Sjoerg const llvm::DataLayout &DataLayout = CGM.getDataLayout();
3360*13fbcb42Sjoerg int Size = DataLayout.getTypeStoreSize(ITy);
3361*13fbcb42Sjoerg SmallVector<uint64_t, 4> Bits(Size);
3362*13fbcb42Sjoerg setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits);
3363*13fbcb42Sjoerg
3364*13fbcb42Sjoerg int CharWidth = CGM.getContext().getCharWidth();
3365*13fbcb42Sjoerg uint64_t Mask =
3366*13fbcb42Sjoerg buildMultiCharMask(Bits, 0, Size, CharWidth, DataLayout.isBigEndian());
3367*13fbcb42Sjoerg
3368*13fbcb42Sjoerg return Builder.CreateAnd(Src, Mask, "cmse.clear");
3369*13fbcb42Sjoerg }
3370*13fbcb42Sjoerg
3371*13fbcb42Sjoerg // Emit code to clear the bits in a record, which aren't a part of any user
3372*13fbcb42Sjoerg // declared member, when the record is a function argument.
EmitCMSEClearRecord(llvm::Value * Src,llvm::ArrayType * ATy,QualType QTy)3373*13fbcb42Sjoerg llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
3374*13fbcb42Sjoerg llvm::ArrayType *ATy,
3375*13fbcb42Sjoerg QualType QTy) {
3376*13fbcb42Sjoerg const llvm::DataLayout &DataLayout = CGM.getDataLayout();
3377*13fbcb42Sjoerg int Size = DataLayout.getTypeStoreSize(ATy);
3378*13fbcb42Sjoerg SmallVector<uint64_t, 16> Bits(Size);
3379*13fbcb42Sjoerg setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits);
3380*13fbcb42Sjoerg
3381*13fbcb42Sjoerg // Clear each element of the LLVM array.
3382*13fbcb42Sjoerg int CharWidth = CGM.getContext().getCharWidth();
3383*13fbcb42Sjoerg int CharsPerElt =
3384*13fbcb42Sjoerg ATy->getArrayElementType()->getScalarSizeInBits() / CharWidth;
3385*13fbcb42Sjoerg int MaskIndex = 0;
3386*13fbcb42Sjoerg llvm::Value *R = llvm::UndefValue::get(ATy);
3387*13fbcb42Sjoerg for (int I = 0, N = ATy->getArrayNumElements(); I != N; ++I) {
3388*13fbcb42Sjoerg uint64_t Mask = buildMultiCharMask(Bits, MaskIndex, CharsPerElt, CharWidth,
3389*13fbcb42Sjoerg DataLayout.isBigEndian());
3390*13fbcb42Sjoerg MaskIndex += CharsPerElt;
3391*13fbcb42Sjoerg llvm::Value *T0 = Builder.CreateExtractValue(Src, I);
3392*13fbcb42Sjoerg llvm::Value *T1 = Builder.CreateAnd(T0, Mask, "cmse.clear");
3393*13fbcb42Sjoerg R = Builder.CreateInsertValue(R, T1, I);
3394*13fbcb42Sjoerg }
3395*13fbcb42Sjoerg
3396*13fbcb42Sjoerg return R;
3397*13fbcb42Sjoerg }
3398*13fbcb42Sjoerg
EmitFunctionEpilog(const CGFunctionInfo & FI,bool EmitRetDbgLoc,SourceLocation EndLoc)339906f32e7eSjoerg void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
340006f32e7eSjoerg bool EmitRetDbgLoc,
340106f32e7eSjoerg SourceLocation EndLoc) {
340206f32e7eSjoerg if (FI.isNoReturn()) {
340306f32e7eSjoerg // Noreturn functions don't return.
340406f32e7eSjoerg EmitUnreachable(EndLoc);
340506f32e7eSjoerg return;
340606f32e7eSjoerg }
340706f32e7eSjoerg
340806f32e7eSjoerg if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
340906f32e7eSjoerg // Naked functions don't have epilogues.
341006f32e7eSjoerg Builder.CreateUnreachable();
341106f32e7eSjoerg return;
341206f32e7eSjoerg }
341306f32e7eSjoerg
341406f32e7eSjoerg // Functions with no result always return void.
341506f32e7eSjoerg if (!ReturnValue.isValid()) {
341606f32e7eSjoerg Builder.CreateRetVoid();
341706f32e7eSjoerg return;
341806f32e7eSjoerg }
341906f32e7eSjoerg
342006f32e7eSjoerg llvm::DebugLoc RetDbgLoc;
342106f32e7eSjoerg llvm::Value *RV = nullptr;
342206f32e7eSjoerg QualType RetTy = FI.getReturnType();
342306f32e7eSjoerg const ABIArgInfo &RetAI = FI.getReturnInfo();
342406f32e7eSjoerg
342506f32e7eSjoerg switch (RetAI.getKind()) {
342606f32e7eSjoerg case ABIArgInfo::InAlloca:
342706f32e7eSjoerg // Aggregrates get evaluated directly into the destination. Sometimes we
342806f32e7eSjoerg // need to return the sret value in a register, though.
342906f32e7eSjoerg assert(hasAggregateEvaluationKind(RetTy));
343006f32e7eSjoerg if (RetAI.getInAllocaSRet()) {
343106f32e7eSjoerg llvm::Function::arg_iterator EI = CurFn->arg_end();
343206f32e7eSjoerg --EI;
343306f32e7eSjoerg llvm::Value *ArgStruct = &*EI;
343406f32e7eSjoerg llvm::Value *SRet = Builder.CreateStructGEP(
343506f32e7eSjoerg nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
3436*13fbcb42Sjoerg llvm::Type *Ty =
3437*13fbcb42Sjoerg cast<llvm::GetElementPtrInst>(SRet)->getResultElementType();
3438*13fbcb42Sjoerg RV = Builder.CreateAlignedLoad(Ty, SRet, getPointerAlign(), "sret");
343906f32e7eSjoerg }
344006f32e7eSjoerg break;
344106f32e7eSjoerg
344206f32e7eSjoerg case ABIArgInfo::Indirect: {
344306f32e7eSjoerg auto AI = CurFn->arg_begin();
344406f32e7eSjoerg if (RetAI.isSRetAfterThis())
344506f32e7eSjoerg ++AI;
344606f32e7eSjoerg switch (getEvaluationKind(RetTy)) {
344706f32e7eSjoerg case TEK_Complex: {
344806f32e7eSjoerg ComplexPairTy RT =
344906f32e7eSjoerg EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
345006f32e7eSjoerg EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
345106f32e7eSjoerg /*isInit*/ true);
345206f32e7eSjoerg break;
345306f32e7eSjoerg }
345406f32e7eSjoerg case TEK_Aggregate:
345506f32e7eSjoerg // Do nothing; aggregrates get evaluated directly into the destination.
345606f32e7eSjoerg break;
345706f32e7eSjoerg case TEK_Scalar:
345806f32e7eSjoerg EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
345906f32e7eSjoerg MakeNaturalAlignAddrLValue(&*AI, RetTy),
346006f32e7eSjoerg /*isInit*/ true);
346106f32e7eSjoerg break;
346206f32e7eSjoerg }
346306f32e7eSjoerg break;
346406f32e7eSjoerg }
346506f32e7eSjoerg
346606f32e7eSjoerg case ABIArgInfo::Extend:
346706f32e7eSjoerg case ABIArgInfo::Direct:
346806f32e7eSjoerg if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
346906f32e7eSjoerg RetAI.getDirectOffset() == 0) {
347006f32e7eSjoerg // The internal return value temp always will have pointer-to-return-type
347106f32e7eSjoerg // type, just do a load.
347206f32e7eSjoerg
347306f32e7eSjoerg // If there is a dominating store to ReturnValue, we can elide
347406f32e7eSjoerg // the load, zap the store, and usually zap the alloca.
347506f32e7eSjoerg if (llvm::StoreInst *SI =
347606f32e7eSjoerg findDominatingStoreToReturnValue(*this)) {
347706f32e7eSjoerg // Reuse the debug location from the store unless there is
347806f32e7eSjoerg // cleanup code to be emitted between the store and return
347906f32e7eSjoerg // instruction.
348006f32e7eSjoerg if (EmitRetDbgLoc && !AutoreleaseResult)
348106f32e7eSjoerg RetDbgLoc = SI->getDebugLoc();
348206f32e7eSjoerg // Get the stored value and nuke the now-dead store.
348306f32e7eSjoerg RV = SI->getValueOperand();
348406f32e7eSjoerg SI->eraseFromParent();
348506f32e7eSjoerg
348606f32e7eSjoerg // Otherwise, we have to do a simple load.
348706f32e7eSjoerg } else {
348806f32e7eSjoerg RV = Builder.CreateLoad(ReturnValue);
348906f32e7eSjoerg }
349006f32e7eSjoerg } else {
349106f32e7eSjoerg // If the value is offset in memory, apply the offset now.
349206f32e7eSjoerg Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
349306f32e7eSjoerg
349406f32e7eSjoerg RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
349506f32e7eSjoerg }
349606f32e7eSjoerg
349706f32e7eSjoerg // In ARC, end functions that return a retainable type with a call
349806f32e7eSjoerg // to objc_autoreleaseReturnValue.
349906f32e7eSjoerg if (AutoreleaseResult) {
350006f32e7eSjoerg #ifndef NDEBUG
350106f32e7eSjoerg // Type::isObjCRetainabletype has to be called on a QualType that hasn't
350206f32e7eSjoerg // been stripped of the typedefs, so we cannot use RetTy here. Get the
350306f32e7eSjoerg // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
350406f32e7eSjoerg // CurCodeDecl or BlockInfo.
350506f32e7eSjoerg QualType RT;
350606f32e7eSjoerg
350706f32e7eSjoerg if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
350806f32e7eSjoerg RT = FD->getReturnType();
350906f32e7eSjoerg else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
351006f32e7eSjoerg RT = MD->getReturnType();
351106f32e7eSjoerg else if (isa<BlockDecl>(CurCodeDecl))
351206f32e7eSjoerg RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
351306f32e7eSjoerg else
351406f32e7eSjoerg llvm_unreachable("Unexpected function/method type");
351506f32e7eSjoerg
351606f32e7eSjoerg assert(getLangOpts().ObjCAutoRefCount &&
351706f32e7eSjoerg !FI.isReturnsRetained() &&
351806f32e7eSjoerg RT->isObjCRetainableType());
351906f32e7eSjoerg #endif
352006f32e7eSjoerg RV = emitAutoreleaseOfResult(*this, RV);
352106f32e7eSjoerg }
352206f32e7eSjoerg
352306f32e7eSjoerg break;
352406f32e7eSjoerg
352506f32e7eSjoerg case ABIArgInfo::Ignore:
352606f32e7eSjoerg break;
352706f32e7eSjoerg
352806f32e7eSjoerg case ABIArgInfo::CoerceAndExpand: {
352906f32e7eSjoerg auto coercionType = RetAI.getCoerceAndExpandType();
353006f32e7eSjoerg
353106f32e7eSjoerg // Load all of the coerced elements out into results.
353206f32e7eSjoerg llvm::SmallVector<llvm::Value*, 4> results;
353306f32e7eSjoerg Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType);
353406f32e7eSjoerg for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
353506f32e7eSjoerg auto coercedEltType = coercionType->getElementType(i);
353606f32e7eSjoerg if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
353706f32e7eSjoerg continue;
353806f32e7eSjoerg
353906f32e7eSjoerg auto eltAddr = Builder.CreateStructGEP(addr, i);
354006f32e7eSjoerg auto elt = Builder.CreateLoad(eltAddr);
354106f32e7eSjoerg results.push_back(elt);
354206f32e7eSjoerg }
354306f32e7eSjoerg
354406f32e7eSjoerg // If we have one result, it's the single direct result type.
354506f32e7eSjoerg if (results.size() == 1) {
354606f32e7eSjoerg RV = results[0];
354706f32e7eSjoerg
354806f32e7eSjoerg // Otherwise, we need to make a first-class aggregate.
354906f32e7eSjoerg } else {
355006f32e7eSjoerg // Construct a return type that lacks padding elements.
355106f32e7eSjoerg llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
355206f32e7eSjoerg
355306f32e7eSjoerg RV = llvm::UndefValue::get(returnType);
355406f32e7eSjoerg for (unsigned i = 0, e = results.size(); i != e; ++i) {
355506f32e7eSjoerg RV = Builder.CreateInsertValue(RV, results[i], i);
355606f32e7eSjoerg }
355706f32e7eSjoerg }
355806f32e7eSjoerg break;
355906f32e7eSjoerg }
356006f32e7eSjoerg case ABIArgInfo::Expand:
3561*13fbcb42Sjoerg case ABIArgInfo::IndirectAliased:
356206f32e7eSjoerg llvm_unreachable("Invalid ABI kind for return argument");
356306f32e7eSjoerg }
356406f32e7eSjoerg
356506f32e7eSjoerg llvm::Instruction *Ret;
356606f32e7eSjoerg if (RV) {
3567*13fbcb42Sjoerg if (CurFuncDecl && CurFuncDecl->hasAttr<CmseNSEntryAttr>()) {
3568*13fbcb42Sjoerg // For certain return types, clear padding bits, as they may reveal
3569*13fbcb42Sjoerg // sensitive information.
3570*13fbcb42Sjoerg // Small struct/union types are passed as integers.
3571*13fbcb42Sjoerg auto *ITy = dyn_cast<llvm::IntegerType>(RV->getType());
3572*13fbcb42Sjoerg if (ITy != nullptr && isa<RecordType>(RetTy.getCanonicalType()))
3573*13fbcb42Sjoerg RV = EmitCMSEClearRecord(RV, ITy, RetTy);
3574*13fbcb42Sjoerg }
357506f32e7eSjoerg EmitReturnValueCheck(RV);
357606f32e7eSjoerg Ret = Builder.CreateRet(RV);
357706f32e7eSjoerg } else {
357806f32e7eSjoerg Ret = Builder.CreateRetVoid();
357906f32e7eSjoerg }
358006f32e7eSjoerg
358106f32e7eSjoerg if (RetDbgLoc)
358206f32e7eSjoerg Ret->setDebugLoc(std::move(RetDbgLoc));
358306f32e7eSjoerg }
358406f32e7eSjoerg
EmitReturnValueCheck(llvm::Value * RV)358506f32e7eSjoerg void CodeGenFunction::EmitReturnValueCheck(llvm::Value *RV) {
358606f32e7eSjoerg // A current decl may not be available when emitting vtable thunks.
358706f32e7eSjoerg if (!CurCodeDecl)
358806f32e7eSjoerg return;
358906f32e7eSjoerg
3590*13fbcb42Sjoerg // If the return block isn't reachable, neither is this check, so don't emit
3591*13fbcb42Sjoerg // it.
3592*13fbcb42Sjoerg if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty())
3593*13fbcb42Sjoerg return;
3594*13fbcb42Sjoerg
359506f32e7eSjoerg ReturnsNonNullAttr *RetNNAttr = nullptr;
359606f32e7eSjoerg if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute))
359706f32e7eSjoerg RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>();
359806f32e7eSjoerg
359906f32e7eSjoerg if (!RetNNAttr && !requiresReturnValueNullabilityCheck())
360006f32e7eSjoerg return;
360106f32e7eSjoerg
360206f32e7eSjoerg // Prefer the returns_nonnull attribute if it's present.
360306f32e7eSjoerg SourceLocation AttrLoc;
360406f32e7eSjoerg SanitizerMask CheckKind;
360506f32e7eSjoerg SanitizerHandler Handler;
360606f32e7eSjoerg if (RetNNAttr) {
360706f32e7eSjoerg assert(!requiresReturnValueNullabilityCheck() &&
360806f32e7eSjoerg "Cannot check nullability and the nonnull attribute");
360906f32e7eSjoerg AttrLoc = RetNNAttr->getLocation();
361006f32e7eSjoerg CheckKind = SanitizerKind::ReturnsNonnullAttribute;
361106f32e7eSjoerg Handler = SanitizerHandler::NonnullReturn;
361206f32e7eSjoerg } else {
361306f32e7eSjoerg if (auto *DD = dyn_cast<DeclaratorDecl>(CurCodeDecl))
361406f32e7eSjoerg if (auto *TSI = DD->getTypeSourceInfo())
3615*13fbcb42Sjoerg if (auto FTL = TSI->getTypeLoc().getAsAdjusted<FunctionTypeLoc>())
361606f32e7eSjoerg AttrLoc = FTL.getReturnLoc().findNullabilityLoc();
361706f32e7eSjoerg CheckKind = SanitizerKind::NullabilityReturn;
361806f32e7eSjoerg Handler = SanitizerHandler::NullabilityReturn;
361906f32e7eSjoerg }
362006f32e7eSjoerg
362106f32e7eSjoerg SanitizerScope SanScope(this);
362206f32e7eSjoerg
362306f32e7eSjoerg // Make sure the "return" source location is valid. If we're checking a
362406f32e7eSjoerg // nullability annotation, make sure the preconditions for the check are met.
362506f32e7eSjoerg llvm::BasicBlock *Check = createBasicBlock("nullcheck");
362606f32e7eSjoerg llvm::BasicBlock *NoCheck = createBasicBlock("no.nullcheck");
362706f32e7eSjoerg llvm::Value *SLocPtr = Builder.CreateLoad(ReturnLocation, "return.sloc.load");
362806f32e7eSjoerg llvm::Value *CanNullCheck = Builder.CreateIsNotNull(SLocPtr);
362906f32e7eSjoerg if (requiresReturnValueNullabilityCheck())
363006f32e7eSjoerg CanNullCheck =
363106f32e7eSjoerg Builder.CreateAnd(CanNullCheck, RetValNullabilityPrecondition);
363206f32e7eSjoerg Builder.CreateCondBr(CanNullCheck, Check, NoCheck);
363306f32e7eSjoerg EmitBlock(Check);
363406f32e7eSjoerg
363506f32e7eSjoerg // Now do the null check.
363606f32e7eSjoerg llvm::Value *Cond = Builder.CreateIsNotNull(RV);
363706f32e7eSjoerg llvm::Constant *StaticData[] = {EmitCheckSourceLocation(AttrLoc)};
363806f32e7eSjoerg llvm::Value *DynamicData[] = {SLocPtr};
363906f32e7eSjoerg EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, DynamicData);
364006f32e7eSjoerg
364106f32e7eSjoerg EmitBlock(NoCheck);
364206f32e7eSjoerg
364306f32e7eSjoerg #ifndef NDEBUG
364406f32e7eSjoerg // The return location should not be used after the check has been emitted.
364506f32e7eSjoerg ReturnLocation = Address::invalid();
364606f32e7eSjoerg #endif
364706f32e7eSjoerg }
364806f32e7eSjoerg
isInAllocaArgument(CGCXXABI & ABI,QualType type)364906f32e7eSjoerg static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
365006f32e7eSjoerg const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
365106f32e7eSjoerg return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
365206f32e7eSjoerg }
365306f32e7eSjoerg
createPlaceholderSlot(CodeGenFunction & CGF,QualType Ty)365406f32e7eSjoerg static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
365506f32e7eSjoerg QualType Ty) {
365606f32e7eSjoerg // FIXME: Generate IR in one pass, rather than going back and fixing up these
365706f32e7eSjoerg // placeholders.
365806f32e7eSjoerg llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
365906f32e7eSjoerg llvm::Type *IRPtrTy = IRTy->getPointerTo();
366006f32e7eSjoerg llvm::Value *Placeholder = llvm::UndefValue::get(IRPtrTy->getPointerTo());
366106f32e7eSjoerg
366206f32e7eSjoerg // FIXME: When we generate this IR in one pass, we shouldn't need
366306f32e7eSjoerg // this win32-specific alignment hack.
366406f32e7eSjoerg CharUnits Align = CharUnits::fromQuantity(4);
366506f32e7eSjoerg Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align);
366606f32e7eSjoerg
366706f32e7eSjoerg return AggValueSlot::forAddr(Address(Placeholder, Align),
366806f32e7eSjoerg Ty.getQualifiers(),
366906f32e7eSjoerg AggValueSlot::IsNotDestructed,
367006f32e7eSjoerg AggValueSlot::DoesNotNeedGCBarriers,
367106f32e7eSjoerg AggValueSlot::IsNotAliased,
367206f32e7eSjoerg AggValueSlot::DoesNotOverlap);
367306f32e7eSjoerg }
367406f32e7eSjoerg
EmitDelegateCallArg(CallArgList & args,const VarDecl * param,SourceLocation loc)367506f32e7eSjoerg void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
367606f32e7eSjoerg const VarDecl *param,
367706f32e7eSjoerg SourceLocation loc) {
367806f32e7eSjoerg // StartFunction converted the ABI-lowered parameter(s) into a
367906f32e7eSjoerg // local alloca. We need to turn that into an r-value suitable
368006f32e7eSjoerg // for EmitCall.
368106f32e7eSjoerg Address local = GetAddrOfLocalVar(param);
368206f32e7eSjoerg
368306f32e7eSjoerg QualType type = param->getType();
368406f32e7eSjoerg
368506f32e7eSjoerg if (isInAllocaArgument(CGM.getCXXABI(), type)) {
368606f32e7eSjoerg CGM.ErrorUnsupported(param, "forwarded non-trivially copyable parameter");
368706f32e7eSjoerg }
368806f32e7eSjoerg
368906f32e7eSjoerg // GetAddrOfLocalVar returns a pointer-to-pointer for references,
369006f32e7eSjoerg // but the argument needs to be the original pointer.
369106f32e7eSjoerg if (type->isReferenceType()) {
369206f32e7eSjoerg args.add(RValue::get(Builder.CreateLoad(local)), type);
369306f32e7eSjoerg
369406f32e7eSjoerg // In ARC, move out of consumed arguments so that the release cleanup
369506f32e7eSjoerg // entered by StartFunction doesn't cause an over-release. This isn't
369606f32e7eSjoerg // optimal -O0 code generation, but it should get cleaned up when
369706f32e7eSjoerg // optimization is enabled. This also assumes that delegate calls are
369806f32e7eSjoerg // performed exactly once for a set of arguments, but that should be safe.
369906f32e7eSjoerg } else if (getLangOpts().ObjCAutoRefCount &&
370006f32e7eSjoerg param->hasAttr<NSConsumedAttr>() &&
370106f32e7eSjoerg type->isObjCRetainableType()) {
370206f32e7eSjoerg llvm::Value *ptr = Builder.CreateLoad(local);
370306f32e7eSjoerg auto null =
370406f32e7eSjoerg llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType()));
370506f32e7eSjoerg Builder.CreateStore(null, local);
370606f32e7eSjoerg args.add(RValue::get(ptr), type);
370706f32e7eSjoerg
370806f32e7eSjoerg // For the most part, we just need to load the alloca, except that
370906f32e7eSjoerg // aggregate r-values are actually pointers to temporaries.
371006f32e7eSjoerg } else {
371106f32e7eSjoerg args.add(convertTempToRValue(local, type, loc), type);
371206f32e7eSjoerg }
371306f32e7eSjoerg
371406f32e7eSjoerg // Deactivate the cleanup for the callee-destructed param that was pushed.
3715*13fbcb42Sjoerg if (type->isRecordType() && !CurFuncIsThunk &&
371606f32e7eSjoerg type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee() &&
371706f32e7eSjoerg param->needsDestruction(getContext())) {
371806f32e7eSjoerg EHScopeStack::stable_iterator cleanup =
371906f32e7eSjoerg CalleeDestructedParamCleanups.lookup(cast<ParmVarDecl>(param));
372006f32e7eSjoerg assert(cleanup.isValid() &&
372106f32e7eSjoerg "cleanup for callee-destructed param not recorded");
372206f32e7eSjoerg // This unreachable is a temporary marker which will be removed later.
372306f32e7eSjoerg llvm::Instruction *isActive = Builder.CreateUnreachable();
372406f32e7eSjoerg args.addArgCleanupDeactivation(cleanup, isActive);
372506f32e7eSjoerg }
372606f32e7eSjoerg }
372706f32e7eSjoerg
isProvablyNull(llvm::Value * addr)372806f32e7eSjoerg static bool isProvablyNull(llvm::Value *addr) {
372906f32e7eSjoerg return isa<llvm::ConstantPointerNull>(addr);
373006f32e7eSjoerg }
373106f32e7eSjoerg
373206f32e7eSjoerg /// Emit the actual writing-back of a writeback.
emitWriteback(CodeGenFunction & CGF,const CallArgList::Writeback & writeback)373306f32e7eSjoerg static void emitWriteback(CodeGenFunction &CGF,
373406f32e7eSjoerg const CallArgList::Writeback &writeback) {
373506f32e7eSjoerg const LValue &srcLV = writeback.Source;
3736*13fbcb42Sjoerg Address srcAddr = srcLV.getAddress(CGF);
373706f32e7eSjoerg assert(!isProvablyNull(srcAddr.getPointer()) &&
373806f32e7eSjoerg "shouldn't have writeback for provably null argument");
373906f32e7eSjoerg
374006f32e7eSjoerg llvm::BasicBlock *contBB = nullptr;
374106f32e7eSjoerg
374206f32e7eSjoerg // If the argument wasn't provably non-null, we need to null check
374306f32e7eSjoerg // before doing the store.
374406f32e7eSjoerg bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
374506f32e7eSjoerg CGF.CGM.getDataLayout());
374606f32e7eSjoerg if (!provablyNonNull) {
374706f32e7eSjoerg llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
374806f32e7eSjoerg contBB = CGF.createBasicBlock("icr.done");
374906f32e7eSjoerg
375006f32e7eSjoerg llvm::Value *isNull =
375106f32e7eSjoerg CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
375206f32e7eSjoerg CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
375306f32e7eSjoerg CGF.EmitBlock(writebackBB);
375406f32e7eSjoerg }
375506f32e7eSjoerg
375606f32e7eSjoerg // Load the value to writeback.
375706f32e7eSjoerg llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
375806f32e7eSjoerg
375906f32e7eSjoerg // Cast it back, in case we're writing an id to a Foo* or something.
376006f32e7eSjoerg value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
376106f32e7eSjoerg "icr.writeback-cast");
376206f32e7eSjoerg
376306f32e7eSjoerg // Perform the writeback.
376406f32e7eSjoerg
376506f32e7eSjoerg // If we have a "to use" value, it's something we need to emit a use
376606f32e7eSjoerg // of. This has to be carefully threaded in: if it's done after the
376706f32e7eSjoerg // release it's potentially undefined behavior (and the optimizer
376806f32e7eSjoerg // will ignore it), and if it happens before the retain then the
376906f32e7eSjoerg // optimizer could move the release there.
377006f32e7eSjoerg if (writeback.ToUse) {
377106f32e7eSjoerg assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
377206f32e7eSjoerg
377306f32e7eSjoerg // Retain the new value. No need to block-copy here: the block's
377406f32e7eSjoerg // being passed up the stack.
377506f32e7eSjoerg value = CGF.EmitARCRetainNonBlock(value);
377606f32e7eSjoerg
377706f32e7eSjoerg // Emit the intrinsic use here.
377806f32e7eSjoerg CGF.EmitARCIntrinsicUse(writeback.ToUse);
377906f32e7eSjoerg
378006f32e7eSjoerg // Load the old value (primitively).
378106f32e7eSjoerg llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
378206f32e7eSjoerg
378306f32e7eSjoerg // Put the new value in place (primitively).
378406f32e7eSjoerg CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
378506f32e7eSjoerg
378606f32e7eSjoerg // Release the old value.
378706f32e7eSjoerg CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
378806f32e7eSjoerg
378906f32e7eSjoerg // Otherwise, we can just do a normal lvalue store.
379006f32e7eSjoerg } else {
379106f32e7eSjoerg CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
379206f32e7eSjoerg }
379306f32e7eSjoerg
379406f32e7eSjoerg // Jump to the continuation block.
379506f32e7eSjoerg if (!provablyNonNull)
379606f32e7eSjoerg CGF.EmitBlock(contBB);
379706f32e7eSjoerg }
379806f32e7eSjoerg
emitWritebacks(CodeGenFunction & CGF,const CallArgList & args)379906f32e7eSjoerg static void emitWritebacks(CodeGenFunction &CGF,
380006f32e7eSjoerg const CallArgList &args) {
380106f32e7eSjoerg for (const auto &I : args.writebacks())
380206f32e7eSjoerg emitWriteback(CGF, I);
380306f32e7eSjoerg }
380406f32e7eSjoerg
deactivateArgCleanupsBeforeCall(CodeGenFunction & CGF,const CallArgList & CallArgs)380506f32e7eSjoerg static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
380606f32e7eSjoerg const CallArgList &CallArgs) {
380706f32e7eSjoerg ArrayRef<CallArgList::CallArgCleanup> Cleanups =
380806f32e7eSjoerg CallArgs.getCleanupsToDeactivate();
380906f32e7eSjoerg // Iterate in reverse to increase the likelihood of popping the cleanup.
381006f32e7eSjoerg for (const auto &I : llvm::reverse(Cleanups)) {
381106f32e7eSjoerg CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
381206f32e7eSjoerg I.IsActiveIP->eraseFromParent();
381306f32e7eSjoerg }
381406f32e7eSjoerg }
381506f32e7eSjoerg
maybeGetUnaryAddrOfOperand(const Expr * E)381606f32e7eSjoerg static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
381706f32e7eSjoerg if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
381806f32e7eSjoerg if (uop->getOpcode() == UO_AddrOf)
381906f32e7eSjoerg return uop->getSubExpr();
382006f32e7eSjoerg return nullptr;
382106f32e7eSjoerg }
382206f32e7eSjoerg
382306f32e7eSjoerg /// Emit an argument that's being passed call-by-writeback. That is,
382406f32e7eSjoerg /// we are passing the address of an __autoreleased temporary; it
382506f32e7eSjoerg /// might be copy-initialized with the current value of the given
382606f32e7eSjoerg /// address, but it will definitely be copied out of after the call.
emitWritebackArg(CodeGenFunction & CGF,CallArgList & args,const ObjCIndirectCopyRestoreExpr * CRE)382706f32e7eSjoerg static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
382806f32e7eSjoerg const ObjCIndirectCopyRestoreExpr *CRE) {
382906f32e7eSjoerg LValue srcLV;
383006f32e7eSjoerg
383106f32e7eSjoerg // Make an optimistic effort to emit the address as an l-value.
383206f32e7eSjoerg // This can fail if the argument expression is more complicated.
383306f32e7eSjoerg if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
383406f32e7eSjoerg srcLV = CGF.EmitLValue(lvExpr);
383506f32e7eSjoerg
383606f32e7eSjoerg // Otherwise, just emit it as a scalar.
383706f32e7eSjoerg } else {
383806f32e7eSjoerg Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
383906f32e7eSjoerg
384006f32e7eSjoerg QualType srcAddrType =
384106f32e7eSjoerg CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
384206f32e7eSjoerg srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
384306f32e7eSjoerg }
3844*13fbcb42Sjoerg Address srcAddr = srcLV.getAddress(CGF);
384506f32e7eSjoerg
384606f32e7eSjoerg // The dest and src types don't necessarily match in LLVM terms
384706f32e7eSjoerg // because of the crazy ObjC compatibility rules.
384806f32e7eSjoerg
384906f32e7eSjoerg llvm::PointerType *destType =
385006f32e7eSjoerg cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
385106f32e7eSjoerg
385206f32e7eSjoerg // If the address is a constant null, just pass the appropriate null.
385306f32e7eSjoerg if (isProvablyNull(srcAddr.getPointer())) {
385406f32e7eSjoerg args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
385506f32e7eSjoerg CRE->getType());
385606f32e7eSjoerg return;
385706f32e7eSjoerg }
385806f32e7eSjoerg
385906f32e7eSjoerg // Create the temporary.
386006f32e7eSjoerg Address temp = CGF.CreateTempAlloca(destType->getElementType(),
386106f32e7eSjoerg CGF.getPointerAlign(),
386206f32e7eSjoerg "icr.temp");
386306f32e7eSjoerg // Loading an l-value can introduce a cleanup if the l-value is __weak,
386406f32e7eSjoerg // and that cleanup will be conditional if we can't prove that the l-value
386506f32e7eSjoerg // isn't null, so we need to register a dominating point so that the cleanups
386606f32e7eSjoerg // system will make valid IR.
386706f32e7eSjoerg CodeGenFunction::ConditionalEvaluation condEval(CGF);
386806f32e7eSjoerg
386906f32e7eSjoerg // Zero-initialize it if we're not doing a copy-initialization.
387006f32e7eSjoerg bool shouldCopy = CRE->shouldCopy();
387106f32e7eSjoerg if (!shouldCopy) {
387206f32e7eSjoerg llvm::Value *null =
387306f32e7eSjoerg llvm::ConstantPointerNull::get(
387406f32e7eSjoerg cast<llvm::PointerType>(destType->getElementType()));
387506f32e7eSjoerg CGF.Builder.CreateStore(null, temp);
387606f32e7eSjoerg }
387706f32e7eSjoerg
387806f32e7eSjoerg llvm::BasicBlock *contBB = nullptr;
387906f32e7eSjoerg llvm::BasicBlock *originBB = nullptr;
388006f32e7eSjoerg
388106f32e7eSjoerg // If the address is *not* known to be non-null, we need to switch.
388206f32e7eSjoerg llvm::Value *finalArgument;
388306f32e7eSjoerg
388406f32e7eSjoerg bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
388506f32e7eSjoerg CGF.CGM.getDataLayout());
388606f32e7eSjoerg if (provablyNonNull) {
388706f32e7eSjoerg finalArgument = temp.getPointer();
388806f32e7eSjoerg } else {
388906f32e7eSjoerg llvm::Value *isNull =
389006f32e7eSjoerg CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
389106f32e7eSjoerg
389206f32e7eSjoerg finalArgument = CGF.Builder.CreateSelect(isNull,
389306f32e7eSjoerg llvm::ConstantPointerNull::get(destType),
389406f32e7eSjoerg temp.getPointer(), "icr.argument");
389506f32e7eSjoerg
389606f32e7eSjoerg // If we need to copy, then the load has to be conditional, which
389706f32e7eSjoerg // means we need control flow.
389806f32e7eSjoerg if (shouldCopy) {
389906f32e7eSjoerg originBB = CGF.Builder.GetInsertBlock();
390006f32e7eSjoerg contBB = CGF.createBasicBlock("icr.cont");
390106f32e7eSjoerg llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
390206f32e7eSjoerg CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
390306f32e7eSjoerg CGF.EmitBlock(copyBB);
390406f32e7eSjoerg condEval.begin(CGF);
390506f32e7eSjoerg }
390606f32e7eSjoerg }
390706f32e7eSjoerg
390806f32e7eSjoerg llvm::Value *valueToUse = nullptr;
390906f32e7eSjoerg
391006f32e7eSjoerg // Perform a copy if necessary.
391106f32e7eSjoerg if (shouldCopy) {
391206f32e7eSjoerg RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
391306f32e7eSjoerg assert(srcRV.isScalar());
391406f32e7eSjoerg
391506f32e7eSjoerg llvm::Value *src = srcRV.getScalarVal();
391606f32e7eSjoerg src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
391706f32e7eSjoerg "icr.cast");
391806f32e7eSjoerg
391906f32e7eSjoerg // Use an ordinary store, not a store-to-lvalue.
392006f32e7eSjoerg CGF.Builder.CreateStore(src, temp);
392106f32e7eSjoerg
392206f32e7eSjoerg // If optimization is enabled, and the value was held in a
392306f32e7eSjoerg // __strong variable, we need to tell the optimizer that this
392406f32e7eSjoerg // value has to stay alive until we're doing the store back.
392506f32e7eSjoerg // This is because the temporary is effectively unretained,
392606f32e7eSjoerg // and so otherwise we can violate the high-level semantics.
392706f32e7eSjoerg if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
392806f32e7eSjoerg srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
392906f32e7eSjoerg valueToUse = src;
393006f32e7eSjoerg }
393106f32e7eSjoerg }
393206f32e7eSjoerg
393306f32e7eSjoerg // Finish the control flow if we needed it.
393406f32e7eSjoerg if (shouldCopy && !provablyNonNull) {
393506f32e7eSjoerg llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
393606f32e7eSjoerg CGF.EmitBlock(contBB);
393706f32e7eSjoerg
393806f32e7eSjoerg // Make a phi for the value to intrinsically use.
393906f32e7eSjoerg if (valueToUse) {
394006f32e7eSjoerg llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
394106f32e7eSjoerg "icr.to-use");
394206f32e7eSjoerg phiToUse->addIncoming(valueToUse, copyBB);
394306f32e7eSjoerg phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
394406f32e7eSjoerg originBB);
394506f32e7eSjoerg valueToUse = phiToUse;
394606f32e7eSjoerg }
394706f32e7eSjoerg
394806f32e7eSjoerg condEval.end(CGF);
394906f32e7eSjoerg }
395006f32e7eSjoerg
395106f32e7eSjoerg args.addWriteback(srcLV, temp, valueToUse);
395206f32e7eSjoerg args.add(RValue::get(finalArgument), CRE->getType());
395306f32e7eSjoerg }
395406f32e7eSjoerg
allocateArgumentMemory(CodeGenFunction & CGF)395506f32e7eSjoerg void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
395606f32e7eSjoerg assert(!StackBase);
395706f32e7eSjoerg
395806f32e7eSjoerg // Save the stack.
395906f32e7eSjoerg llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
396006f32e7eSjoerg StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
396106f32e7eSjoerg }
396206f32e7eSjoerg
freeArgumentMemory(CodeGenFunction & CGF) const396306f32e7eSjoerg void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
396406f32e7eSjoerg if (StackBase) {
396506f32e7eSjoerg // Restore the stack after the call.
396606f32e7eSjoerg llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
396706f32e7eSjoerg CGF.Builder.CreateCall(F, StackBase);
396806f32e7eSjoerg }
396906f32e7eSjoerg }
397006f32e7eSjoerg
EmitNonNullArgCheck(RValue RV,QualType ArgType,SourceLocation ArgLoc,AbstractCallee AC,unsigned ParmNum)397106f32e7eSjoerg void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
397206f32e7eSjoerg SourceLocation ArgLoc,
397306f32e7eSjoerg AbstractCallee AC,
397406f32e7eSjoerg unsigned ParmNum) {
397506f32e7eSjoerg if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
397606f32e7eSjoerg SanOpts.has(SanitizerKind::NullabilityArg)))
397706f32e7eSjoerg return;
397806f32e7eSjoerg
397906f32e7eSjoerg // The param decl may be missing in a variadic function.
398006f32e7eSjoerg auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr;
398106f32e7eSjoerg unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
398206f32e7eSjoerg
398306f32e7eSjoerg // Prefer the nonnull attribute if it's present.
398406f32e7eSjoerg const NonNullAttr *NNAttr = nullptr;
398506f32e7eSjoerg if (SanOpts.has(SanitizerKind::NonnullAttribute))
398606f32e7eSjoerg NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo);
398706f32e7eSjoerg
398806f32e7eSjoerg bool CanCheckNullability = false;
398906f32e7eSjoerg if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD) {
399006f32e7eSjoerg auto Nullability = PVD->getType()->getNullability(getContext());
399106f32e7eSjoerg CanCheckNullability = Nullability &&
399206f32e7eSjoerg *Nullability == NullabilityKind::NonNull &&
399306f32e7eSjoerg PVD->getTypeSourceInfo();
399406f32e7eSjoerg }
399506f32e7eSjoerg
399606f32e7eSjoerg if (!NNAttr && !CanCheckNullability)
399706f32e7eSjoerg return;
399806f32e7eSjoerg
399906f32e7eSjoerg SourceLocation AttrLoc;
400006f32e7eSjoerg SanitizerMask CheckKind;
400106f32e7eSjoerg SanitizerHandler Handler;
400206f32e7eSjoerg if (NNAttr) {
400306f32e7eSjoerg AttrLoc = NNAttr->getLocation();
400406f32e7eSjoerg CheckKind = SanitizerKind::NonnullAttribute;
400506f32e7eSjoerg Handler = SanitizerHandler::NonnullArg;
400606f32e7eSjoerg } else {
400706f32e7eSjoerg AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc();
400806f32e7eSjoerg CheckKind = SanitizerKind::NullabilityArg;
400906f32e7eSjoerg Handler = SanitizerHandler::NullabilityArg;
401006f32e7eSjoerg }
401106f32e7eSjoerg
401206f32e7eSjoerg SanitizerScope SanScope(this);
4013*13fbcb42Sjoerg llvm::Value *Cond = EmitNonNullRValueCheck(RV, ArgType);
401406f32e7eSjoerg llvm::Constant *StaticData[] = {
401506f32e7eSjoerg EmitCheckSourceLocation(ArgLoc), EmitCheckSourceLocation(AttrLoc),
401606f32e7eSjoerg llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
401706f32e7eSjoerg };
401806f32e7eSjoerg EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, None);
401906f32e7eSjoerg }
402006f32e7eSjoerg
4021*13fbcb42Sjoerg // Check if the call is going to use the inalloca convention. This needs to
4022*13fbcb42Sjoerg // agree with CGFunctionInfo::usesInAlloca. The CGFunctionInfo is arranged
4023*13fbcb42Sjoerg // later, so we can't check it directly.
hasInAllocaArgs(CodeGenModule & CGM,CallingConv ExplicitCC,ArrayRef<QualType> ArgTypes)4024*13fbcb42Sjoerg static bool hasInAllocaArgs(CodeGenModule &CGM, CallingConv ExplicitCC,
4025*13fbcb42Sjoerg ArrayRef<QualType> ArgTypes) {
4026*13fbcb42Sjoerg // The Swift calling convention doesn't go through the target-specific
4027*13fbcb42Sjoerg // argument classification, so it never uses inalloca.
4028*13fbcb42Sjoerg // TODO: Consider limiting inalloca use to only calling conventions supported
4029*13fbcb42Sjoerg // by MSVC.
4030*13fbcb42Sjoerg if (ExplicitCC == CC_Swift)
4031*13fbcb42Sjoerg return false;
4032*13fbcb42Sjoerg if (!CGM.getTarget().getCXXABI().isMicrosoft())
4033*13fbcb42Sjoerg return false;
4034*13fbcb42Sjoerg return llvm::any_of(ArgTypes, [&](QualType Ty) {
4035*13fbcb42Sjoerg return isInAllocaArgument(CGM.getCXXABI(), Ty);
4036*13fbcb42Sjoerg });
4037*13fbcb42Sjoerg }
4038*13fbcb42Sjoerg
4039*13fbcb42Sjoerg #ifndef NDEBUG
4040*13fbcb42Sjoerg // Determine whether the given argument is an Objective-C method
4041*13fbcb42Sjoerg // that may have type parameters in its signature.
isObjCMethodWithTypeParams(const ObjCMethodDecl * method)4042*13fbcb42Sjoerg static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
4043*13fbcb42Sjoerg const DeclContext *dc = method->getDeclContext();
4044*13fbcb42Sjoerg if (const ObjCInterfaceDecl *classDecl = dyn_cast<ObjCInterfaceDecl>(dc)) {
4045*13fbcb42Sjoerg return classDecl->getTypeParamListAsWritten();
4046*13fbcb42Sjoerg }
4047*13fbcb42Sjoerg
4048*13fbcb42Sjoerg if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
4049*13fbcb42Sjoerg return catDecl->getTypeParamList();
4050*13fbcb42Sjoerg }
4051*13fbcb42Sjoerg
4052*13fbcb42Sjoerg return false;
4053*13fbcb42Sjoerg }
4054*13fbcb42Sjoerg #endif
4055*13fbcb42Sjoerg
4056*13fbcb42Sjoerg /// EmitCallArgs - Emit call arguments for a function.
EmitCallArgs(CallArgList & Args,PrototypeWrapper Prototype,llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,AbstractCallee AC,unsigned ParamsToSkip,EvaluationOrder Order)405706f32e7eSjoerg void CodeGenFunction::EmitCallArgs(
4058*13fbcb42Sjoerg CallArgList &Args, PrototypeWrapper Prototype,
405906f32e7eSjoerg llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
406006f32e7eSjoerg AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) {
4061*13fbcb42Sjoerg SmallVector<QualType, 16> ArgTypes;
4062*13fbcb42Sjoerg
4063*13fbcb42Sjoerg assert((ParamsToSkip == 0 || Prototype.P) &&
4064*13fbcb42Sjoerg "Can't skip parameters if type info is not provided");
4065*13fbcb42Sjoerg
4066*13fbcb42Sjoerg // This variable only captures *explicitly* written conventions, not those
4067*13fbcb42Sjoerg // applied by default via command line flags or target defaults, such as
4068*13fbcb42Sjoerg // thiscall, aapcs, stdcall via -mrtd, etc. Computing that correctly would
4069*13fbcb42Sjoerg // require knowing if this is a C++ instance method or being able to see
4070*13fbcb42Sjoerg // unprototyped FunctionTypes.
4071*13fbcb42Sjoerg CallingConv ExplicitCC = CC_C;
4072*13fbcb42Sjoerg
4073*13fbcb42Sjoerg // First, if a prototype was provided, use those argument types.
4074*13fbcb42Sjoerg bool IsVariadic = false;
4075*13fbcb42Sjoerg if (Prototype.P) {
4076*13fbcb42Sjoerg const auto *MD = Prototype.P.dyn_cast<const ObjCMethodDecl *>();
4077*13fbcb42Sjoerg if (MD) {
4078*13fbcb42Sjoerg IsVariadic = MD->isVariadic();
4079*13fbcb42Sjoerg ExplicitCC = getCallingConventionForDecl(
4080*13fbcb42Sjoerg MD, CGM.getTarget().getTriple().isOSWindows());
4081*13fbcb42Sjoerg ArgTypes.assign(MD->param_type_begin() + ParamsToSkip,
4082*13fbcb42Sjoerg MD->param_type_end());
4083*13fbcb42Sjoerg } else {
4084*13fbcb42Sjoerg const auto *FPT = Prototype.P.get<const FunctionProtoType *>();
4085*13fbcb42Sjoerg IsVariadic = FPT->isVariadic();
4086*13fbcb42Sjoerg ExplicitCC = FPT->getExtInfo().getCC();
4087*13fbcb42Sjoerg ArgTypes.assign(FPT->param_type_begin() + ParamsToSkip,
4088*13fbcb42Sjoerg FPT->param_type_end());
4089*13fbcb42Sjoerg }
4090*13fbcb42Sjoerg
4091*13fbcb42Sjoerg #ifndef NDEBUG
4092*13fbcb42Sjoerg // Check that the prototyped types match the argument expression types.
4093*13fbcb42Sjoerg bool isGenericMethod = MD && isObjCMethodWithTypeParams(MD);
4094*13fbcb42Sjoerg CallExpr::const_arg_iterator Arg = ArgRange.begin();
4095*13fbcb42Sjoerg for (QualType Ty : ArgTypes) {
4096*13fbcb42Sjoerg assert(Arg != ArgRange.end() && "Running over edge of argument list!");
4097*13fbcb42Sjoerg assert(
4098*13fbcb42Sjoerg (isGenericMethod || Ty->isVariablyModifiedType() ||
4099*13fbcb42Sjoerg Ty.getNonReferenceType()->isObjCRetainableType() ||
4100*13fbcb42Sjoerg getContext()
4101*13fbcb42Sjoerg .getCanonicalType(Ty.getNonReferenceType())
4102*13fbcb42Sjoerg .getTypePtr() ==
4103*13fbcb42Sjoerg getContext().getCanonicalType((*Arg)->getType()).getTypePtr()) &&
4104*13fbcb42Sjoerg "type mismatch in call argument!");
4105*13fbcb42Sjoerg ++Arg;
4106*13fbcb42Sjoerg }
4107*13fbcb42Sjoerg
4108*13fbcb42Sjoerg // Either we've emitted all the call args, or we have a call to variadic
4109*13fbcb42Sjoerg // function.
4110*13fbcb42Sjoerg assert((Arg == ArgRange.end() || IsVariadic) &&
4111*13fbcb42Sjoerg "Extra arguments in non-variadic function!");
4112*13fbcb42Sjoerg #endif
4113*13fbcb42Sjoerg }
4114*13fbcb42Sjoerg
4115*13fbcb42Sjoerg // If we still have any arguments, emit them using the type of the argument.
4116*13fbcb42Sjoerg for (auto *A : llvm::make_range(std::next(ArgRange.begin(), ArgTypes.size()),
4117*13fbcb42Sjoerg ArgRange.end()))
4118*13fbcb42Sjoerg ArgTypes.push_back(IsVariadic ? getVarArgType(A) : A->getType());
411906f32e7eSjoerg assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
412006f32e7eSjoerg
4121*13fbcb42Sjoerg // We must evaluate arguments from right to left in the MS C++ ABI,
412206f32e7eSjoerg // because arguments are destroyed left to right in the callee. As a special
412306f32e7eSjoerg // case, there are certain language constructs that require left-to-right
412406f32e7eSjoerg // evaluation, and in those cases we consider the evaluation order requirement
412506f32e7eSjoerg // to trump the "destruction order is reverse construction order" guarantee.
412606f32e7eSjoerg bool LeftToRight =
412706f32e7eSjoerg CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()
412806f32e7eSjoerg ? Order == EvaluationOrder::ForceLeftToRight
412906f32e7eSjoerg : Order != EvaluationOrder::ForceRightToLeft;
413006f32e7eSjoerg
413106f32e7eSjoerg auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg,
413206f32e7eSjoerg RValue EmittedArg) {
413306f32e7eSjoerg if (!AC.hasFunctionDecl() || I >= AC.getNumParams())
413406f32e7eSjoerg return;
413506f32e7eSjoerg auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>();
413606f32e7eSjoerg if (PS == nullptr)
413706f32e7eSjoerg return;
413806f32e7eSjoerg
413906f32e7eSjoerg const auto &Context = getContext();
414006f32e7eSjoerg auto SizeTy = Context.getSizeType();
414106f32e7eSjoerg auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
414206f32e7eSjoerg assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?");
414306f32e7eSjoerg llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T,
414406f32e7eSjoerg EmittedArg.getScalarVal(),
414506f32e7eSjoerg PS->isDynamic());
414606f32e7eSjoerg Args.add(RValue::get(V), SizeTy);
414706f32e7eSjoerg // If we're emitting args in reverse, be sure to do so with
414806f32e7eSjoerg // pass_object_size, as well.
414906f32e7eSjoerg if (!LeftToRight)
415006f32e7eSjoerg std::swap(Args.back(), *(&Args.back() - 1));
415106f32e7eSjoerg };
415206f32e7eSjoerg
415306f32e7eSjoerg // Insert a stack save if we're going to need any inalloca args.
4154*13fbcb42Sjoerg if (hasInAllocaArgs(CGM, ExplicitCC, ArgTypes)) {
4155*13fbcb42Sjoerg assert(getTarget().getTriple().getArch() == llvm::Triple::x86 &&
4156*13fbcb42Sjoerg "inalloca only supported on x86");
415706f32e7eSjoerg Args.allocateArgumentMemory(*this);
415806f32e7eSjoerg }
415906f32e7eSjoerg
416006f32e7eSjoerg // Evaluate each argument in the appropriate order.
416106f32e7eSjoerg size_t CallArgsStart = Args.size();
416206f32e7eSjoerg for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
416306f32e7eSjoerg unsigned Idx = LeftToRight ? I : E - I - 1;
416406f32e7eSjoerg CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
416506f32e7eSjoerg unsigned InitialArgSize = Args.size();
416606f32e7eSjoerg // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of
416706f32e7eSjoerg // the argument and parameter match or the objc method is parameterized.
416806f32e7eSjoerg assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) ||
416906f32e7eSjoerg getContext().hasSameUnqualifiedType((*Arg)->getType(),
417006f32e7eSjoerg ArgTypes[Idx]) ||
417106f32e7eSjoerg (isa<ObjCMethodDecl>(AC.getDecl()) &&
417206f32e7eSjoerg isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) &&
417306f32e7eSjoerg "Argument and parameter types don't match");
417406f32e7eSjoerg EmitCallArg(Args, *Arg, ArgTypes[Idx]);
417506f32e7eSjoerg // In particular, we depend on it being the last arg in Args, and the
417606f32e7eSjoerg // objectsize bits depend on there only being one arg if !LeftToRight.
417706f32e7eSjoerg assert(InitialArgSize + 1 == Args.size() &&
417806f32e7eSjoerg "The code below depends on only adding one arg per EmitCallArg");
417906f32e7eSjoerg (void)InitialArgSize;
418006f32e7eSjoerg // Since pointer argument are never emitted as LValue, it is safe to emit
418106f32e7eSjoerg // non-null argument check for r-value only.
418206f32e7eSjoerg if (!Args.back().hasLValue()) {
418306f32e7eSjoerg RValue RVArg = Args.back().getKnownRValue();
418406f32e7eSjoerg EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC,
418506f32e7eSjoerg ParamsToSkip + Idx);
418606f32e7eSjoerg // @llvm.objectsize should never have side-effects and shouldn't need
418706f32e7eSjoerg // destruction/cleanups, so we can safely "emit" it after its arg,
418806f32e7eSjoerg // regardless of right-to-leftness
418906f32e7eSjoerg MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
419006f32e7eSjoerg }
419106f32e7eSjoerg }
419206f32e7eSjoerg
419306f32e7eSjoerg if (!LeftToRight) {
419406f32e7eSjoerg // Un-reverse the arguments we just evaluated so they match up with the LLVM
419506f32e7eSjoerg // IR function.
419606f32e7eSjoerg std::reverse(Args.begin() + CallArgsStart, Args.end());
419706f32e7eSjoerg }
419806f32e7eSjoerg }
419906f32e7eSjoerg
420006f32e7eSjoerg namespace {
420106f32e7eSjoerg
420206f32e7eSjoerg struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
DestroyUnpassedArg__anon2a3770250c11::DestroyUnpassedArg420306f32e7eSjoerg DestroyUnpassedArg(Address Addr, QualType Ty)
420406f32e7eSjoerg : Addr(Addr), Ty(Ty) {}
420506f32e7eSjoerg
420606f32e7eSjoerg Address Addr;
420706f32e7eSjoerg QualType Ty;
420806f32e7eSjoerg
Emit__anon2a3770250c11::DestroyUnpassedArg420906f32e7eSjoerg void Emit(CodeGenFunction &CGF, Flags flags) override {
421006f32e7eSjoerg QualType::DestructionKind DtorKind = Ty.isDestructedType();
421106f32e7eSjoerg if (DtorKind == QualType::DK_cxx_destructor) {
421206f32e7eSjoerg const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
421306f32e7eSjoerg assert(!Dtor->isTrivial());
421406f32e7eSjoerg CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
421506f32e7eSjoerg /*Delegating=*/false, Addr, Ty);
421606f32e7eSjoerg } else {
421706f32e7eSjoerg CGF.callCStructDestructor(CGF.MakeAddrLValue(Addr, Ty));
421806f32e7eSjoerg }
421906f32e7eSjoerg }
422006f32e7eSjoerg };
422106f32e7eSjoerg
422206f32e7eSjoerg struct DisableDebugLocationUpdates {
422306f32e7eSjoerg CodeGenFunction &CGF;
422406f32e7eSjoerg bool disabledDebugInfo;
DisableDebugLocationUpdates__anon2a3770250c11::DisableDebugLocationUpdates422506f32e7eSjoerg DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
422606f32e7eSjoerg if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
422706f32e7eSjoerg CGF.disableDebugInfo();
422806f32e7eSjoerg }
~DisableDebugLocationUpdates__anon2a3770250c11::DisableDebugLocationUpdates422906f32e7eSjoerg ~DisableDebugLocationUpdates() {
423006f32e7eSjoerg if (disabledDebugInfo)
423106f32e7eSjoerg CGF.enableDebugInfo();
423206f32e7eSjoerg }
423306f32e7eSjoerg };
423406f32e7eSjoerg
423506f32e7eSjoerg } // end anonymous namespace
423606f32e7eSjoerg
getRValue(CodeGenFunction & CGF) const423706f32e7eSjoerg RValue CallArg::getRValue(CodeGenFunction &CGF) const {
423806f32e7eSjoerg if (!HasLV)
423906f32e7eSjoerg return RV;
424006f32e7eSjoerg LValue Copy = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty), Ty);
424106f32e7eSjoerg CGF.EmitAggregateCopy(Copy, LV, Ty, AggValueSlot::DoesNotOverlap,
424206f32e7eSjoerg LV.isVolatile());
424306f32e7eSjoerg IsUsed = true;
4244*13fbcb42Sjoerg return RValue::getAggregate(Copy.getAddress(CGF));
424506f32e7eSjoerg }
424606f32e7eSjoerg
copyInto(CodeGenFunction & CGF,Address Addr) const424706f32e7eSjoerg void CallArg::copyInto(CodeGenFunction &CGF, Address Addr) const {
424806f32e7eSjoerg LValue Dst = CGF.MakeAddrLValue(Addr, Ty);
424906f32e7eSjoerg if (!HasLV && RV.isScalar())
425006f32e7eSjoerg CGF.EmitStoreOfScalar(RV.getScalarVal(), Dst, /*isInit=*/true);
425106f32e7eSjoerg else if (!HasLV && RV.isComplex())
425206f32e7eSjoerg CGF.EmitStoreOfComplex(RV.getComplexVal(), Dst, /*init=*/true);
425306f32e7eSjoerg else {
4254*13fbcb42Sjoerg auto Addr = HasLV ? LV.getAddress(CGF) : RV.getAggregateAddress();
425506f32e7eSjoerg LValue SrcLV = CGF.MakeAddrLValue(Addr, Ty);
425606f32e7eSjoerg // We assume that call args are never copied into subobjects.
425706f32e7eSjoerg CGF.EmitAggregateCopy(Dst, SrcLV, Ty, AggValueSlot::DoesNotOverlap,
425806f32e7eSjoerg HasLV ? LV.isVolatileQualified()
425906f32e7eSjoerg : RV.isVolatileQualified());
426006f32e7eSjoerg }
426106f32e7eSjoerg IsUsed = true;
426206f32e7eSjoerg }
426306f32e7eSjoerg
EmitCallArg(CallArgList & args,const Expr * E,QualType type)426406f32e7eSjoerg void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
426506f32e7eSjoerg QualType type) {
426606f32e7eSjoerg DisableDebugLocationUpdates Dis(*this, E);
426706f32e7eSjoerg if (const ObjCIndirectCopyRestoreExpr *CRE
426806f32e7eSjoerg = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
426906f32e7eSjoerg assert(getLangOpts().ObjCAutoRefCount);
427006f32e7eSjoerg return emitWritebackArg(*this, args, CRE);
427106f32e7eSjoerg }
427206f32e7eSjoerg
427306f32e7eSjoerg assert(type->isReferenceType() == E->isGLValue() &&
427406f32e7eSjoerg "reference binding to unmaterialized r-value!");
427506f32e7eSjoerg
427606f32e7eSjoerg if (E->isGLValue()) {
427706f32e7eSjoerg assert(E->getObjectKind() == OK_Ordinary);
427806f32e7eSjoerg return args.add(EmitReferenceBindingToExpr(E), type);
427906f32e7eSjoerg }
428006f32e7eSjoerg
428106f32e7eSjoerg bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
428206f32e7eSjoerg
428306f32e7eSjoerg // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
428406f32e7eSjoerg // However, we still have to push an EH-only cleanup in case we unwind before
428506f32e7eSjoerg // we make it to the call.
4286*13fbcb42Sjoerg if (type->isRecordType() &&
428706f32e7eSjoerg type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
428806f32e7eSjoerg // If we're using inalloca, use the argument memory. Otherwise, use a
428906f32e7eSjoerg // temporary.
429006f32e7eSjoerg AggValueSlot Slot;
429106f32e7eSjoerg if (args.isUsingInAlloca())
429206f32e7eSjoerg Slot = createPlaceholderSlot(*this, type);
429306f32e7eSjoerg else
429406f32e7eSjoerg Slot = CreateAggTemp(type, "agg.tmp");
429506f32e7eSjoerg
429606f32e7eSjoerg bool DestroyedInCallee = true, NeedsEHCleanup = true;
429706f32e7eSjoerg if (const auto *RD = type->getAsCXXRecordDecl())
429806f32e7eSjoerg DestroyedInCallee = RD->hasNonTrivialDestructor();
429906f32e7eSjoerg else
430006f32e7eSjoerg NeedsEHCleanup = needsEHCleanup(type.isDestructedType());
430106f32e7eSjoerg
430206f32e7eSjoerg if (DestroyedInCallee)
430306f32e7eSjoerg Slot.setExternallyDestructed();
430406f32e7eSjoerg
430506f32e7eSjoerg EmitAggExpr(E, Slot);
430606f32e7eSjoerg RValue RV = Slot.asRValue();
430706f32e7eSjoerg args.add(RV, type);
430806f32e7eSjoerg
430906f32e7eSjoerg if (DestroyedInCallee && NeedsEHCleanup) {
431006f32e7eSjoerg // Create a no-op GEP between the placeholder and the cleanup so we can
431106f32e7eSjoerg // RAUW it successfully. It also serves as a marker of the first
431206f32e7eSjoerg // instruction where the cleanup is active.
431306f32e7eSjoerg pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
431406f32e7eSjoerg type);
431506f32e7eSjoerg // This unreachable is a temporary marker which will be removed later.
431606f32e7eSjoerg llvm::Instruction *IsActive = Builder.CreateUnreachable();
431706f32e7eSjoerg args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
431806f32e7eSjoerg }
431906f32e7eSjoerg return;
432006f32e7eSjoerg }
432106f32e7eSjoerg
432206f32e7eSjoerg if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
432306f32e7eSjoerg cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
432406f32e7eSjoerg LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
432506f32e7eSjoerg assert(L.isSimple());
432606f32e7eSjoerg args.addUncopiedAggregate(L, type);
432706f32e7eSjoerg return;
432806f32e7eSjoerg }
432906f32e7eSjoerg
433006f32e7eSjoerg args.add(EmitAnyExprToTemp(E), type);
433106f32e7eSjoerg }
433206f32e7eSjoerg
getVarArgType(const Expr * Arg)433306f32e7eSjoerg QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
433406f32e7eSjoerg // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
433506f32e7eSjoerg // implicitly widens null pointer constants that are arguments to varargs
433606f32e7eSjoerg // functions to pointer-sized ints.
433706f32e7eSjoerg if (!getTarget().getTriple().isOSWindows())
433806f32e7eSjoerg return Arg->getType();
433906f32e7eSjoerg
434006f32e7eSjoerg if (Arg->getType()->isIntegerType() &&
434106f32e7eSjoerg getContext().getTypeSize(Arg->getType()) <
434206f32e7eSjoerg getContext().getTargetInfo().getPointerWidth(0) &&
434306f32e7eSjoerg Arg->isNullPointerConstant(getContext(),
434406f32e7eSjoerg Expr::NPC_ValueDependentIsNotNull)) {
434506f32e7eSjoerg return getContext().getIntPtrType();
434606f32e7eSjoerg }
434706f32e7eSjoerg
434806f32e7eSjoerg return Arg->getType();
434906f32e7eSjoerg }
435006f32e7eSjoerg
435106f32e7eSjoerg // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
435206f32e7eSjoerg // optimizer it can aggressively ignore unwind edges.
435306f32e7eSjoerg void
AddObjCARCExceptionMetadata(llvm::Instruction * Inst)435406f32e7eSjoerg CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
435506f32e7eSjoerg if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
435606f32e7eSjoerg !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
435706f32e7eSjoerg Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
435806f32e7eSjoerg CGM.getNoObjCARCExceptionsMetadata());
435906f32e7eSjoerg }
436006f32e7eSjoerg
436106f32e7eSjoerg /// Emits a call to the given no-arguments nounwind runtime function.
436206f32e7eSjoerg llvm::CallInst *
EmitNounwindRuntimeCall(llvm::FunctionCallee callee,const llvm::Twine & name)436306f32e7eSjoerg CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
436406f32e7eSjoerg const llvm::Twine &name) {
436506f32e7eSjoerg return EmitNounwindRuntimeCall(callee, None, name);
436606f32e7eSjoerg }
436706f32e7eSjoerg
436806f32e7eSjoerg /// Emits a call to the given nounwind runtime function.
436906f32e7eSjoerg llvm::CallInst *
EmitNounwindRuntimeCall(llvm::FunctionCallee callee,ArrayRef<llvm::Value * > args,const llvm::Twine & name)437006f32e7eSjoerg CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
437106f32e7eSjoerg ArrayRef<llvm::Value *> args,
437206f32e7eSjoerg const llvm::Twine &name) {
437306f32e7eSjoerg llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
437406f32e7eSjoerg call->setDoesNotThrow();
437506f32e7eSjoerg return call;
437606f32e7eSjoerg }
437706f32e7eSjoerg
437806f32e7eSjoerg /// Emits a simple call (never an invoke) to the given no-arguments
437906f32e7eSjoerg /// runtime function.
EmitRuntimeCall(llvm::FunctionCallee callee,const llvm::Twine & name)438006f32e7eSjoerg llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
438106f32e7eSjoerg const llvm::Twine &name) {
438206f32e7eSjoerg return EmitRuntimeCall(callee, None, name);
438306f32e7eSjoerg }
438406f32e7eSjoerg
438506f32e7eSjoerg // Calls which may throw must have operand bundles indicating which funclet
438606f32e7eSjoerg // they are nested within.
438706f32e7eSjoerg SmallVector<llvm::OperandBundleDef, 1>
getBundlesForFunclet(llvm::Value * Callee)438806f32e7eSjoerg CodeGenFunction::getBundlesForFunclet(llvm::Value *Callee) {
438906f32e7eSjoerg SmallVector<llvm::OperandBundleDef, 1> BundleList;
439006f32e7eSjoerg // There is no need for a funclet operand bundle if we aren't inside a
439106f32e7eSjoerg // funclet.
439206f32e7eSjoerg if (!CurrentFuncletPad)
439306f32e7eSjoerg return BundleList;
439406f32e7eSjoerg
439506f32e7eSjoerg // Skip intrinsics which cannot throw.
439606f32e7eSjoerg auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts());
439706f32e7eSjoerg if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow())
439806f32e7eSjoerg return BundleList;
439906f32e7eSjoerg
440006f32e7eSjoerg BundleList.emplace_back("funclet", CurrentFuncletPad);
440106f32e7eSjoerg return BundleList;
440206f32e7eSjoerg }
440306f32e7eSjoerg
440406f32e7eSjoerg /// Emits a simple call (never an invoke) to the given runtime function.
EmitRuntimeCall(llvm::FunctionCallee callee,ArrayRef<llvm::Value * > args,const llvm::Twine & name)440506f32e7eSjoerg llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
440606f32e7eSjoerg ArrayRef<llvm::Value *> args,
440706f32e7eSjoerg const llvm::Twine &name) {
440806f32e7eSjoerg llvm::CallInst *call = Builder.CreateCall(
440906f32e7eSjoerg callee, args, getBundlesForFunclet(callee.getCallee()), name);
441006f32e7eSjoerg call->setCallingConv(getRuntimeCC());
441106f32e7eSjoerg return call;
441206f32e7eSjoerg }
441306f32e7eSjoerg
441406f32e7eSjoerg /// Emits a call or invoke to the given noreturn runtime function.
EmitNoreturnRuntimeCallOrInvoke(llvm::FunctionCallee callee,ArrayRef<llvm::Value * > args)441506f32e7eSjoerg void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(
441606f32e7eSjoerg llvm::FunctionCallee callee, ArrayRef<llvm::Value *> args) {
441706f32e7eSjoerg SmallVector<llvm::OperandBundleDef, 1> BundleList =
441806f32e7eSjoerg getBundlesForFunclet(callee.getCallee());
441906f32e7eSjoerg
442006f32e7eSjoerg if (getInvokeDest()) {
442106f32e7eSjoerg llvm::InvokeInst *invoke =
442206f32e7eSjoerg Builder.CreateInvoke(callee,
442306f32e7eSjoerg getUnreachableBlock(),
442406f32e7eSjoerg getInvokeDest(),
442506f32e7eSjoerg args,
442606f32e7eSjoerg BundleList);
442706f32e7eSjoerg invoke->setDoesNotReturn();
442806f32e7eSjoerg invoke->setCallingConv(getRuntimeCC());
442906f32e7eSjoerg } else {
443006f32e7eSjoerg llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
443106f32e7eSjoerg call->setDoesNotReturn();
443206f32e7eSjoerg call->setCallingConv(getRuntimeCC());
443306f32e7eSjoerg Builder.CreateUnreachable();
443406f32e7eSjoerg }
443506f32e7eSjoerg }
443606f32e7eSjoerg
443706f32e7eSjoerg /// Emits a call or invoke instruction to the given nullary runtime function.
443806f32e7eSjoerg llvm::CallBase *
EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,const Twine & name)443906f32e7eSjoerg CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
444006f32e7eSjoerg const Twine &name) {
444106f32e7eSjoerg return EmitRuntimeCallOrInvoke(callee, None, name);
444206f32e7eSjoerg }
444306f32e7eSjoerg
444406f32e7eSjoerg /// Emits a call or invoke instruction to the given runtime function.
444506f32e7eSjoerg llvm::CallBase *
EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,ArrayRef<llvm::Value * > args,const Twine & name)444606f32e7eSjoerg CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
444706f32e7eSjoerg ArrayRef<llvm::Value *> args,
444806f32e7eSjoerg const Twine &name) {
444906f32e7eSjoerg llvm::CallBase *call = EmitCallOrInvoke(callee, args, name);
445006f32e7eSjoerg call->setCallingConv(getRuntimeCC());
445106f32e7eSjoerg return call;
445206f32e7eSjoerg }
445306f32e7eSjoerg
445406f32e7eSjoerg /// Emits a call or invoke instruction to the given function, depending
445506f32e7eSjoerg /// on the current state of the EH stack.
EmitCallOrInvoke(llvm::FunctionCallee Callee,ArrayRef<llvm::Value * > Args,const Twine & Name)445606f32e7eSjoerg llvm::CallBase *CodeGenFunction::EmitCallOrInvoke(llvm::FunctionCallee Callee,
445706f32e7eSjoerg ArrayRef<llvm::Value *> Args,
445806f32e7eSjoerg const Twine &Name) {
445906f32e7eSjoerg llvm::BasicBlock *InvokeDest = getInvokeDest();
446006f32e7eSjoerg SmallVector<llvm::OperandBundleDef, 1> BundleList =
446106f32e7eSjoerg getBundlesForFunclet(Callee.getCallee());
446206f32e7eSjoerg
446306f32e7eSjoerg llvm::CallBase *Inst;
446406f32e7eSjoerg if (!InvokeDest)
446506f32e7eSjoerg Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
446606f32e7eSjoerg else {
446706f32e7eSjoerg llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
446806f32e7eSjoerg Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
446906f32e7eSjoerg Name);
447006f32e7eSjoerg EmitBlock(ContBB);
447106f32e7eSjoerg }
447206f32e7eSjoerg
447306f32e7eSjoerg // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
447406f32e7eSjoerg // optimizer it can aggressively ignore unwind edges.
447506f32e7eSjoerg if (CGM.getLangOpts().ObjCAutoRefCount)
447606f32e7eSjoerg AddObjCARCExceptionMetadata(Inst);
447706f32e7eSjoerg
447806f32e7eSjoerg return Inst;
447906f32e7eSjoerg }
448006f32e7eSjoerg
deferPlaceholderReplacement(llvm::Instruction * Old,llvm::Value * New)448106f32e7eSjoerg void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
448206f32e7eSjoerg llvm::Value *New) {
4483*13fbcb42Sjoerg DeferredReplacements.push_back(
4484*13fbcb42Sjoerg std::make_pair(llvm::WeakTrackingVH(Old), New));
448506f32e7eSjoerg }
448606f32e7eSjoerg
4487*13fbcb42Sjoerg namespace {
4488*13fbcb42Sjoerg
4489*13fbcb42Sjoerg /// Specify given \p NewAlign as the alignment of return value attribute. If
4490*13fbcb42Sjoerg /// such attribute already exists, re-set it to the maximal one of two options.
4491*13fbcb42Sjoerg LLVM_NODISCARD llvm::AttributeList
maybeRaiseRetAlignmentAttribute(llvm::LLVMContext & Ctx,const llvm::AttributeList & Attrs,llvm::Align NewAlign)4492*13fbcb42Sjoerg maybeRaiseRetAlignmentAttribute(llvm::LLVMContext &Ctx,
4493*13fbcb42Sjoerg const llvm::AttributeList &Attrs,
4494*13fbcb42Sjoerg llvm::Align NewAlign) {
4495*13fbcb42Sjoerg llvm::Align CurAlign = Attrs.getRetAlignment().valueOrOne();
4496*13fbcb42Sjoerg if (CurAlign >= NewAlign)
4497*13fbcb42Sjoerg return Attrs;
4498*13fbcb42Sjoerg llvm::Attribute AlignAttr = llvm::Attribute::getWithAlignment(Ctx, NewAlign);
4499*13fbcb42Sjoerg return Attrs
4500*13fbcb42Sjoerg .removeAttribute(Ctx, llvm::AttributeList::ReturnIndex,
4501*13fbcb42Sjoerg llvm::Attribute::AttrKind::Alignment)
4502*13fbcb42Sjoerg .addAttribute(Ctx, llvm::AttributeList::ReturnIndex, AlignAttr);
4503*13fbcb42Sjoerg }
4504*13fbcb42Sjoerg
4505*13fbcb42Sjoerg template <typename AlignedAttrTy> class AbstractAssumeAlignedAttrEmitter {
4506*13fbcb42Sjoerg protected:
4507*13fbcb42Sjoerg CodeGenFunction &CGF;
4508*13fbcb42Sjoerg
4509*13fbcb42Sjoerg /// We do nothing if this is, or becomes, nullptr.
4510*13fbcb42Sjoerg const AlignedAttrTy *AA = nullptr;
4511*13fbcb42Sjoerg
4512*13fbcb42Sjoerg llvm::Value *Alignment = nullptr; // May or may not be a constant.
4513*13fbcb42Sjoerg llvm::ConstantInt *OffsetCI = nullptr; // Constant, hopefully zero.
4514*13fbcb42Sjoerg
AbstractAssumeAlignedAttrEmitter(CodeGenFunction & CGF_,const Decl * FuncDecl)4515*13fbcb42Sjoerg AbstractAssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
4516*13fbcb42Sjoerg : CGF(CGF_) {
4517*13fbcb42Sjoerg if (!FuncDecl)
4518*13fbcb42Sjoerg return;
4519*13fbcb42Sjoerg AA = FuncDecl->getAttr<AlignedAttrTy>();
4520*13fbcb42Sjoerg }
4521*13fbcb42Sjoerg
4522*13fbcb42Sjoerg public:
4523*13fbcb42Sjoerg /// If we can, materialize the alignment as an attribute on return value.
4524*13fbcb42Sjoerg LLVM_NODISCARD llvm::AttributeList
TryEmitAsCallSiteAttribute(const llvm::AttributeList & Attrs)4525*13fbcb42Sjoerg TryEmitAsCallSiteAttribute(const llvm::AttributeList &Attrs) {
4526*13fbcb42Sjoerg if (!AA || OffsetCI || CGF.SanOpts.has(SanitizerKind::Alignment))
4527*13fbcb42Sjoerg return Attrs;
4528*13fbcb42Sjoerg const auto *AlignmentCI = dyn_cast<llvm::ConstantInt>(Alignment);
4529*13fbcb42Sjoerg if (!AlignmentCI)
4530*13fbcb42Sjoerg return Attrs;
4531*13fbcb42Sjoerg // We may legitimately have non-power-of-2 alignment here.
4532*13fbcb42Sjoerg // If so, this is UB land, emit it via `@llvm.assume` instead.
4533*13fbcb42Sjoerg if (!AlignmentCI->getValue().isPowerOf2())
4534*13fbcb42Sjoerg return Attrs;
4535*13fbcb42Sjoerg llvm::AttributeList NewAttrs = maybeRaiseRetAlignmentAttribute(
4536*13fbcb42Sjoerg CGF.getLLVMContext(), Attrs,
4537*13fbcb42Sjoerg llvm::Align(
4538*13fbcb42Sjoerg AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment)));
4539*13fbcb42Sjoerg AA = nullptr; // We're done. Disallow doing anything else.
4540*13fbcb42Sjoerg return NewAttrs;
4541*13fbcb42Sjoerg }
4542*13fbcb42Sjoerg
4543*13fbcb42Sjoerg /// Emit alignment assumption.
4544*13fbcb42Sjoerg /// This is a general fallback that we take if either there is an offset,
4545*13fbcb42Sjoerg /// or the alignment is variable or we are sanitizing for alignment.
EmitAsAnAssumption(SourceLocation Loc,QualType RetTy,RValue & Ret)4546*13fbcb42Sjoerg void EmitAsAnAssumption(SourceLocation Loc, QualType RetTy, RValue &Ret) {
4547*13fbcb42Sjoerg if (!AA)
4548*13fbcb42Sjoerg return;
4549*13fbcb42Sjoerg CGF.emitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc,
4550*13fbcb42Sjoerg AA->getLocation(), Alignment, OffsetCI);
4551*13fbcb42Sjoerg AA = nullptr; // We're done. Disallow doing anything else.
4552*13fbcb42Sjoerg }
4553*13fbcb42Sjoerg };
4554*13fbcb42Sjoerg
4555*13fbcb42Sjoerg /// Helper data structure to emit `AssumeAlignedAttr`.
4556*13fbcb42Sjoerg class AssumeAlignedAttrEmitter final
4557*13fbcb42Sjoerg : public AbstractAssumeAlignedAttrEmitter<AssumeAlignedAttr> {
4558*13fbcb42Sjoerg public:
AssumeAlignedAttrEmitter(CodeGenFunction & CGF_,const Decl * FuncDecl)4559*13fbcb42Sjoerg AssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
4560*13fbcb42Sjoerg : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
4561*13fbcb42Sjoerg if (!AA)
4562*13fbcb42Sjoerg return;
4563*13fbcb42Sjoerg // It is guaranteed that the alignment/offset are constants.
4564*13fbcb42Sjoerg Alignment = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AA->getAlignment()));
4565*13fbcb42Sjoerg if (Expr *Offset = AA->getOffset()) {
4566*13fbcb42Sjoerg OffsetCI = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(Offset));
4567*13fbcb42Sjoerg if (OffsetCI->isNullValue()) // Canonicalize zero offset to no offset.
4568*13fbcb42Sjoerg OffsetCI = nullptr;
4569*13fbcb42Sjoerg }
4570*13fbcb42Sjoerg }
4571*13fbcb42Sjoerg };
4572*13fbcb42Sjoerg
4573*13fbcb42Sjoerg /// Helper data structure to emit `AllocAlignAttr`.
4574*13fbcb42Sjoerg class AllocAlignAttrEmitter final
4575*13fbcb42Sjoerg : public AbstractAssumeAlignedAttrEmitter<AllocAlignAttr> {
4576*13fbcb42Sjoerg public:
AllocAlignAttrEmitter(CodeGenFunction & CGF_,const Decl * FuncDecl,const CallArgList & CallArgs)4577*13fbcb42Sjoerg AllocAlignAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl,
4578*13fbcb42Sjoerg const CallArgList &CallArgs)
4579*13fbcb42Sjoerg : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
4580*13fbcb42Sjoerg if (!AA)
4581*13fbcb42Sjoerg return;
4582*13fbcb42Sjoerg // Alignment may or may not be a constant, and that is okay.
4583*13fbcb42Sjoerg Alignment = CallArgs[AA->getParamIndex().getLLVMIndex()]
4584*13fbcb42Sjoerg .getRValue(CGF)
4585*13fbcb42Sjoerg .getScalarVal();
4586*13fbcb42Sjoerg }
4587*13fbcb42Sjoerg };
4588*13fbcb42Sjoerg
4589*13fbcb42Sjoerg } // namespace
4590*13fbcb42Sjoerg
EmitCall(const CGFunctionInfo & CallInfo,const CGCallee & Callee,ReturnValueSlot ReturnValue,const CallArgList & CallArgs,llvm::CallBase ** callOrInvoke,bool IsMustTail,SourceLocation Loc)459106f32e7eSjoerg RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
459206f32e7eSjoerg const CGCallee &Callee,
459306f32e7eSjoerg ReturnValueSlot ReturnValue,
459406f32e7eSjoerg const CallArgList &CallArgs,
4595*13fbcb42Sjoerg llvm::CallBase **callOrInvoke, bool IsMustTail,
459606f32e7eSjoerg SourceLocation Loc) {
459706f32e7eSjoerg // FIXME: We no longer need the types from CallArgs; lift up and simplify.
459806f32e7eSjoerg
459906f32e7eSjoerg assert(Callee.isOrdinary() || Callee.isVirtual());
460006f32e7eSjoerg
460106f32e7eSjoerg // Handle struct-return functions by passing a pointer to the
460206f32e7eSjoerg // location that we would like to return into.
460306f32e7eSjoerg QualType RetTy = CallInfo.getReturnType();
460406f32e7eSjoerg const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
460506f32e7eSjoerg
460606f32e7eSjoerg llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo);
460706f32e7eSjoerg
460806f32e7eSjoerg const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
4609*13fbcb42Sjoerg if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
461006f32e7eSjoerg // We can only guarantee that a function is called from the correct
461106f32e7eSjoerg // context/function based on the appropriate target attributes,
461206f32e7eSjoerg // so only check in the case where we have both always_inline and target
461306f32e7eSjoerg // since otherwise we could be making a conditional call after a check for
461406f32e7eSjoerg // the proper cpu features (and it won't cause code generation issues due to
461506f32e7eSjoerg // function based code generation).
461606f32e7eSjoerg if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
461706f32e7eSjoerg TargetDecl->hasAttr<TargetAttr>())
461806f32e7eSjoerg checkTargetFeatures(Loc, FD);
461906f32e7eSjoerg
4620*13fbcb42Sjoerg // Some architectures (such as x86-64) have the ABI changed based on
4621*13fbcb42Sjoerg // attribute-target/features. Give them a chance to diagnose.
4622*13fbcb42Sjoerg CGM.getTargetCodeGenInfo().checkFunctionCallABI(
4623*13fbcb42Sjoerg CGM, Loc, dyn_cast_or_null<FunctionDecl>(CurCodeDecl), FD, CallArgs);
4624*13fbcb42Sjoerg }
4625*13fbcb42Sjoerg
462606f32e7eSjoerg #ifndef NDEBUG
462706f32e7eSjoerg if (!(CallInfo.isVariadic() && CallInfo.getArgStruct())) {
462806f32e7eSjoerg // For an inalloca varargs function, we don't expect CallInfo to match the
462906f32e7eSjoerg // function pointer's type, because the inalloca struct a will have extra
463006f32e7eSjoerg // fields in it for the varargs parameters. Code later in this function
463106f32e7eSjoerg // bitcasts the function pointer to the type derived from CallInfo.
463206f32e7eSjoerg //
463306f32e7eSjoerg // In other cases, we assert that the types match up (until pointers stop
463406f32e7eSjoerg // having pointee types).
463506f32e7eSjoerg llvm::Type *TypeFromVal;
463606f32e7eSjoerg if (Callee.isVirtual())
463706f32e7eSjoerg TypeFromVal = Callee.getVirtualFunctionType();
463806f32e7eSjoerg else
463906f32e7eSjoerg TypeFromVal =
464006f32e7eSjoerg Callee.getFunctionPointer()->getType()->getPointerElementType();
464106f32e7eSjoerg assert(IRFuncTy == TypeFromVal);
464206f32e7eSjoerg }
464306f32e7eSjoerg #endif
464406f32e7eSjoerg
464506f32e7eSjoerg // 1. Set up the arguments.
464606f32e7eSjoerg
464706f32e7eSjoerg // If we're using inalloca, insert the allocation after the stack save.
464806f32e7eSjoerg // FIXME: Do this earlier rather than hacking it in here!
464906f32e7eSjoerg Address ArgMemory = Address::invalid();
465006f32e7eSjoerg if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
465106f32e7eSjoerg const llvm::DataLayout &DL = CGM.getDataLayout();
465206f32e7eSjoerg llvm::Instruction *IP = CallArgs.getStackBase();
465306f32e7eSjoerg llvm::AllocaInst *AI;
465406f32e7eSjoerg if (IP) {
465506f32e7eSjoerg IP = IP->getNextNode();
465606f32e7eSjoerg AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(),
465706f32e7eSjoerg "argmem", IP);
465806f32e7eSjoerg } else {
465906f32e7eSjoerg AI = CreateTempAlloca(ArgStruct, "argmem");
466006f32e7eSjoerg }
466106f32e7eSjoerg auto Align = CallInfo.getArgStructAlignment();
466206f32e7eSjoerg AI->setAlignment(Align.getAsAlign());
466306f32e7eSjoerg AI->setUsedWithInAlloca(true);
466406f32e7eSjoerg assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
466506f32e7eSjoerg ArgMemory = Address(AI, Align);
466606f32e7eSjoerg }
466706f32e7eSjoerg
466806f32e7eSjoerg ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
466906f32e7eSjoerg SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
467006f32e7eSjoerg
467106f32e7eSjoerg // If the call returns a temporary with struct return, create a temporary
467206f32e7eSjoerg // alloca to hold the result, unless one is given to us.
467306f32e7eSjoerg Address SRetPtr = Address::invalid();
467406f32e7eSjoerg Address SRetAlloca = Address::invalid();
467506f32e7eSjoerg llvm::Value *UnusedReturnSizePtr = nullptr;
467606f32e7eSjoerg if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
467706f32e7eSjoerg if (!ReturnValue.isNull()) {
467806f32e7eSjoerg SRetPtr = ReturnValue.getValue();
467906f32e7eSjoerg } else {
468006f32e7eSjoerg SRetPtr = CreateMemTemp(RetTy, "tmp", &SRetAlloca);
468106f32e7eSjoerg if (HaveInsertPoint() && ReturnValue.isUnused()) {
468206f32e7eSjoerg uint64_t size =
468306f32e7eSjoerg CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
468406f32e7eSjoerg UnusedReturnSizePtr = EmitLifetimeStart(size, SRetAlloca.getPointer());
468506f32e7eSjoerg }
468606f32e7eSjoerg }
468706f32e7eSjoerg if (IRFunctionArgs.hasSRetArg()) {
468806f32e7eSjoerg IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
468906f32e7eSjoerg } else if (RetAI.isInAlloca()) {
469006f32e7eSjoerg Address Addr =
469106f32e7eSjoerg Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
469206f32e7eSjoerg Builder.CreateStore(SRetPtr.getPointer(), Addr);
469306f32e7eSjoerg }
469406f32e7eSjoerg }
469506f32e7eSjoerg
469606f32e7eSjoerg Address swiftErrorTemp = Address::invalid();
469706f32e7eSjoerg Address swiftErrorArg = Address::invalid();
469806f32e7eSjoerg
469906f32e7eSjoerg // When passing arguments using temporary allocas, we need to add the
470006f32e7eSjoerg // appropriate lifetime markers. This vector keeps track of all the lifetime
470106f32e7eSjoerg // markers that need to be ended right after the call.
470206f32e7eSjoerg SmallVector<CallLifetimeEnd, 2> CallLifetimeEndAfterCall;
470306f32e7eSjoerg
470406f32e7eSjoerg // Translate all of the arguments as necessary to match the IR lowering.
470506f32e7eSjoerg assert(CallInfo.arg_size() == CallArgs.size() &&
470606f32e7eSjoerg "Mismatch between function signature & arguments.");
470706f32e7eSjoerg unsigned ArgNo = 0;
470806f32e7eSjoerg CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
470906f32e7eSjoerg for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
471006f32e7eSjoerg I != E; ++I, ++info_it, ++ArgNo) {
471106f32e7eSjoerg const ABIArgInfo &ArgInfo = info_it->info;
471206f32e7eSjoerg
471306f32e7eSjoerg // Insert a padding argument to ensure proper alignment.
471406f32e7eSjoerg if (IRFunctionArgs.hasPaddingArg(ArgNo))
471506f32e7eSjoerg IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
471606f32e7eSjoerg llvm::UndefValue::get(ArgInfo.getPaddingType());
471706f32e7eSjoerg
471806f32e7eSjoerg unsigned FirstIRArg, NumIRArgs;
471906f32e7eSjoerg std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
472006f32e7eSjoerg
472106f32e7eSjoerg switch (ArgInfo.getKind()) {
472206f32e7eSjoerg case ABIArgInfo::InAlloca: {
472306f32e7eSjoerg assert(NumIRArgs == 0);
472406f32e7eSjoerg assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
472506f32e7eSjoerg if (I->isAggregate()) {
472606f32e7eSjoerg Address Addr = I->hasLValue()
4727*13fbcb42Sjoerg ? I->getKnownLValue().getAddress(*this)
472806f32e7eSjoerg : I->getKnownRValue().getAggregateAddress();
472906f32e7eSjoerg llvm::Instruction *Placeholder =
473006f32e7eSjoerg cast<llvm::Instruction>(Addr.getPointer());
4731*13fbcb42Sjoerg
4732*13fbcb42Sjoerg if (!ArgInfo.getInAllocaIndirect()) {
4733*13fbcb42Sjoerg // Replace the placeholder with the appropriate argument slot GEP.
473406f32e7eSjoerg CGBuilderTy::InsertPoint IP = Builder.saveIP();
473506f32e7eSjoerg Builder.SetInsertPoint(Placeholder);
4736*13fbcb42Sjoerg Addr = Builder.CreateStructGEP(ArgMemory,
4737*13fbcb42Sjoerg ArgInfo.getInAllocaFieldIndex());
473806f32e7eSjoerg Builder.restoreIP(IP);
4739*13fbcb42Sjoerg } else {
4740*13fbcb42Sjoerg // For indirect things such as overaligned structs, replace the
4741*13fbcb42Sjoerg // placeholder with a regular aggregate temporary alloca. Store the
4742*13fbcb42Sjoerg // address of this alloca into the struct.
4743*13fbcb42Sjoerg Addr = CreateMemTemp(info_it->type, "inalloca.indirect.tmp");
4744*13fbcb42Sjoerg Address ArgSlot = Builder.CreateStructGEP(
4745*13fbcb42Sjoerg ArgMemory, ArgInfo.getInAllocaFieldIndex());
4746*13fbcb42Sjoerg Builder.CreateStore(Addr.getPointer(), ArgSlot);
4747*13fbcb42Sjoerg }
474806f32e7eSjoerg deferPlaceholderReplacement(Placeholder, Addr.getPointer());
4749*13fbcb42Sjoerg } else if (ArgInfo.getInAllocaIndirect()) {
4750*13fbcb42Sjoerg // Make a temporary alloca and store the address of it into the argument
4751*13fbcb42Sjoerg // struct.
4752*13fbcb42Sjoerg Address Addr = CreateMemTempWithoutCast(
4753*13fbcb42Sjoerg I->Ty, getContext().getTypeAlignInChars(I->Ty),
4754*13fbcb42Sjoerg "indirect-arg-temp");
4755*13fbcb42Sjoerg I->copyInto(*this, Addr);
4756*13fbcb42Sjoerg Address ArgSlot =
4757*13fbcb42Sjoerg Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
4758*13fbcb42Sjoerg Builder.CreateStore(Addr.getPointer(), ArgSlot);
475906f32e7eSjoerg } else {
476006f32e7eSjoerg // Store the RValue into the argument struct.
476106f32e7eSjoerg Address Addr =
476206f32e7eSjoerg Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
476306f32e7eSjoerg unsigned AS = Addr.getType()->getPointerAddressSpace();
476406f32e7eSjoerg llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
476506f32e7eSjoerg // There are some cases where a trivial bitcast is not avoidable. The
476606f32e7eSjoerg // definition of a type later in a translation unit may change it's type
476706f32e7eSjoerg // from {}* to (%struct.foo*)*.
476806f32e7eSjoerg if (Addr.getType() != MemType)
476906f32e7eSjoerg Addr = Builder.CreateBitCast(Addr, MemType);
477006f32e7eSjoerg I->copyInto(*this, Addr);
477106f32e7eSjoerg }
477206f32e7eSjoerg break;
477306f32e7eSjoerg }
477406f32e7eSjoerg
4775*13fbcb42Sjoerg case ABIArgInfo::Indirect:
4776*13fbcb42Sjoerg case ABIArgInfo::IndirectAliased: {
477706f32e7eSjoerg assert(NumIRArgs == 1);
477806f32e7eSjoerg if (!I->isAggregate()) {
477906f32e7eSjoerg // Make a temporary alloca to pass the argument.
478006f32e7eSjoerg Address Addr = CreateMemTempWithoutCast(
478106f32e7eSjoerg I->Ty, ArgInfo.getIndirectAlign(), "indirect-arg-temp");
478206f32e7eSjoerg IRCallArgs[FirstIRArg] = Addr.getPointer();
478306f32e7eSjoerg
478406f32e7eSjoerg I->copyInto(*this, Addr);
478506f32e7eSjoerg } else {
478606f32e7eSjoerg // We want to avoid creating an unnecessary temporary+copy here;
478706f32e7eSjoerg // however, we need one in three cases:
478806f32e7eSjoerg // 1. If the argument is not byval, and we are required to copy the
478906f32e7eSjoerg // source. (This case doesn't occur on any common architecture.)
479006f32e7eSjoerg // 2. If the argument is byval, RV is not sufficiently aligned, and
479106f32e7eSjoerg // we cannot force it to be sufficiently aligned.
479206f32e7eSjoerg // 3. If the argument is byval, but RV is not located in default
479306f32e7eSjoerg // or alloca address space.
479406f32e7eSjoerg Address Addr = I->hasLValue()
4795*13fbcb42Sjoerg ? I->getKnownLValue().getAddress(*this)
479606f32e7eSjoerg : I->getKnownRValue().getAggregateAddress();
479706f32e7eSjoerg llvm::Value *V = Addr.getPointer();
479806f32e7eSjoerg CharUnits Align = ArgInfo.getIndirectAlign();
479906f32e7eSjoerg const llvm::DataLayout *TD = &CGM.getDataLayout();
480006f32e7eSjoerg
480106f32e7eSjoerg assert((FirstIRArg >= IRFuncTy->getNumParams() ||
480206f32e7eSjoerg IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() ==
480306f32e7eSjoerg TD->getAllocaAddrSpace()) &&
480406f32e7eSjoerg "indirect argument must be in alloca address space");
480506f32e7eSjoerg
480606f32e7eSjoerg bool NeedCopy = false;
480706f32e7eSjoerg
480806f32e7eSjoerg if (Addr.getAlignment() < Align &&
4809*13fbcb42Sjoerg llvm::getOrEnforceKnownAlignment(V, Align.getAsAlign(), *TD) <
4810*13fbcb42Sjoerg Align.getAsAlign()) {
481106f32e7eSjoerg NeedCopy = true;
481206f32e7eSjoerg } else if (I->hasLValue()) {
481306f32e7eSjoerg auto LV = I->getKnownLValue();
481406f32e7eSjoerg auto AS = LV.getAddressSpace();
481506f32e7eSjoerg
4816*13fbcb42Sjoerg if (!ArgInfo.getIndirectByVal() ||
4817*13fbcb42Sjoerg (LV.getAlignment() < getContext().getTypeAlignInChars(I->Ty))) {
481806f32e7eSjoerg NeedCopy = true;
481906f32e7eSjoerg }
482006f32e7eSjoerg if (!getLangOpts().OpenCL) {
482106f32e7eSjoerg if ((ArgInfo.getIndirectByVal() &&
482206f32e7eSjoerg (AS != LangAS::Default &&
482306f32e7eSjoerg AS != CGM.getASTAllocaAddressSpace()))) {
482406f32e7eSjoerg NeedCopy = true;
482506f32e7eSjoerg }
482606f32e7eSjoerg }
482706f32e7eSjoerg // For OpenCL even if RV is located in default or alloca address space
482806f32e7eSjoerg // we don't want to perform address space cast for it.
482906f32e7eSjoerg else if ((ArgInfo.getIndirectByVal() &&
483006f32e7eSjoerg Addr.getType()->getAddressSpace() != IRFuncTy->
483106f32e7eSjoerg getParamType(FirstIRArg)->getPointerAddressSpace())) {
483206f32e7eSjoerg NeedCopy = true;
483306f32e7eSjoerg }
483406f32e7eSjoerg }
483506f32e7eSjoerg
483606f32e7eSjoerg if (NeedCopy) {
483706f32e7eSjoerg // Create an aligned temporary, and copy to it.
483806f32e7eSjoerg Address AI = CreateMemTempWithoutCast(
483906f32e7eSjoerg I->Ty, ArgInfo.getIndirectAlign(), "byval-temp");
484006f32e7eSjoerg IRCallArgs[FirstIRArg] = AI.getPointer();
484106f32e7eSjoerg
484206f32e7eSjoerg // Emit lifetime markers for the temporary alloca.
484306f32e7eSjoerg uint64_t ByvalTempElementSize =
484406f32e7eSjoerg CGM.getDataLayout().getTypeAllocSize(AI.getElementType());
484506f32e7eSjoerg llvm::Value *LifetimeSize =
484606f32e7eSjoerg EmitLifetimeStart(ByvalTempElementSize, AI.getPointer());
484706f32e7eSjoerg
484806f32e7eSjoerg // Add cleanup code to emit the end lifetime marker after the call.
484906f32e7eSjoerg if (LifetimeSize) // In case we disabled lifetime markers.
485006f32e7eSjoerg CallLifetimeEndAfterCall.emplace_back(AI, LifetimeSize);
485106f32e7eSjoerg
485206f32e7eSjoerg // Generate the copy.
485306f32e7eSjoerg I->copyInto(*this, AI);
485406f32e7eSjoerg } else {
485506f32e7eSjoerg // Skip the extra memcpy call.
485606f32e7eSjoerg auto *T = V->getType()->getPointerElementType()->getPointerTo(
485706f32e7eSjoerg CGM.getDataLayout().getAllocaAddrSpace());
485806f32e7eSjoerg IRCallArgs[FirstIRArg] = getTargetHooks().performAddrSpaceCast(
485906f32e7eSjoerg *this, V, LangAS::Default, CGM.getASTAllocaAddressSpace(), T,
486006f32e7eSjoerg true);
486106f32e7eSjoerg }
486206f32e7eSjoerg }
486306f32e7eSjoerg break;
486406f32e7eSjoerg }
486506f32e7eSjoerg
486606f32e7eSjoerg case ABIArgInfo::Ignore:
486706f32e7eSjoerg assert(NumIRArgs == 0);
486806f32e7eSjoerg break;
486906f32e7eSjoerg
487006f32e7eSjoerg case ABIArgInfo::Extend:
487106f32e7eSjoerg case ABIArgInfo::Direct: {
487206f32e7eSjoerg if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
487306f32e7eSjoerg ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
487406f32e7eSjoerg ArgInfo.getDirectOffset() == 0) {
487506f32e7eSjoerg assert(NumIRArgs == 1);
487606f32e7eSjoerg llvm::Value *V;
487706f32e7eSjoerg if (!I->isAggregate())
487806f32e7eSjoerg V = I->getKnownRValue().getScalarVal();
487906f32e7eSjoerg else
488006f32e7eSjoerg V = Builder.CreateLoad(
4881*13fbcb42Sjoerg I->hasLValue() ? I->getKnownLValue().getAddress(*this)
488206f32e7eSjoerg : I->getKnownRValue().getAggregateAddress());
488306f32e7eSjoerg
488406f32e7eSjoerg // Implement swifterror by copying into a new swifterror argument.
488506f32e7eSjoerg // We'll write back in the normal path out of the call.
488606f32e7eSjoerg if (CallInfo.getExtParameterInfo(ArgNo).getABI()
488706f32e7eSjoerg == ParameterABI::SwiftErrorResult) {
488806f32e7eSjoerg assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
488906f32e7eSjoerg
489006f32e7eSjoerg QualType pointeeTy = I->Ty->getPointeeType();
489106f32e7eSjoerg swiftErrorArg =
489206f32e7eSjoerg Address(V, getContext().getTypeAlignInChars(pointeeTy));
489306f32e7eSjoerg
489406f32e7eSjoerg swiftErrorTemp =
489506f32e7eSjoerg CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
489606f32e7eSjoerg V = swiftErrorTemp.getPointer();
489706f32e7eSjoerg cast<llvm::AllocaInst>(V)->setSwiftError(true);
489806f32e7eSjoerg
489906f32e7eSjoerg llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
490006f32e7eSjoerg Builder.CreateStore(errorValue, swiftErrorTemp);
490106f32e7eSjoerg }
490206f32e7eSjoerg
490306f32e7eSjoerg // We might have to widen integers, but we should never truncate.
490406f32e7eSjoerg if (ArgInfo.getCoerceToType() != V->getType() &&
490506f32e7eSjoerg V->getType()->isIntegerTy())
490606f32e7eSjoerg V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
490706f32e7eSjoerg
490806f32e7eSjoerg // If the argument doesn't match, perform a bitcast to coerce it. This
490906f32e7eSjoerg // can happen due to trivial type mismatches.
491006f32e7eSjoerg if (FirstIRArg < IRFuncTy->getNumParams() &&
491106f32e7eSjoerg V->getType() != IRFuncTy->getParamType(FirstIRArg))
491206f32e7eSjoerg V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
491306f32e7eSjoerg
491406f32e7eSjoerg IRCallArgs[FirstIRArg] = V;
491506f32e7eSjoerg break;
491606f32e7eSjoerg }
491706f32e7eSjoerg
491806f32e7eSjoerg // FIXME: Avoid the conversion through memory if possible.
491906f32e7eSjoerg Address Src = Address::invalid();
492006f32e7eSjoerg if (!I->isAggregate()) {
492106f32e7eSjoerg Src = CreateMemTemp(I->Ty, "coerce");
492206f32e7eSjoerg I->copyInto(*this, Src);
492306f32e7eSjoerg } else {
4924*13fbcb42Sjoerg Src = I->hasLValue() ? I->getKnownLValue().getAddress(*this)
492506f32e7eSjoerg : I->getKnownRValue().getAggregateAddress();
492606f32e7eSjoerg }
492706f32e7eSjoerg
492806f32e7eSjoerg // If the value is offset in memory, apply the offset now.
492906f32e7eSjoerg Src = emitAddressAtOffset(*this, Src, ArgInfo);
493006f32e7eSjoerg
493106f32e7eSjoerg // Fast-isel and the optimizer generally like scalar values better than
493206f32e7eSjoerg // FCAs, so we flatten them if this is safe to do for this argument.
493306f32e7eSjoerg llvm::StructType *STy =
493406f32e7eSjoerg dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
493506f32e7eSjoerg if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
4936*13fbcb42Sjoerg llvm::Type *SrcTy = Src.getElementType();
493706f32e7eSjoerg uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
493806f32e7eSjoerg uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
493906f32e7eSjoerg
494006f32e7eSjoerg // If the source type is smaller than the destination type of the
494106f32e7eSjoerg // coerce-to logic, copy the source value into a temp alloca the size
494206f32e7eSjoerg // of the destination type to allow loading all of it. The bits past
494306f32e7eSjoerg // the source value are left undef.
494406f32e7eSjoerg if (SrcSize < DstSize) {
494506f32e7eSjoerg Address TempAlloca
494606f32e7eSjoerg = CreateTempAlloca(STy, Src.getAlignment(),
494706f32e7eSjoerg Src.getName() + ".coerce");
494806f32e7eSjoerg Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
494906f32e7eSjoerg Src = TempAlloca;
495006f32e7eSjoerg } else {
495106f32e7eSjoerg Src = Builder.CreateBitCast(Src,
495206f32e7eSjoerg STy->getPointerTo(Src.getAddressSpace()));
495306f32e7eSjoerg }
495406f32e7eSjoerg
495506f32e7eSjoerg assert(NumIRArgs == STy->getNumElements());
495606f32e7eSjoerg for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
495706f32e7eSjoerg Address EltPtr = Builder.CreateStructGEP(Src, i);
495806f32e7eSjoerg llvm::Value *LI = Builder.CreateLoad(EltPtr);
495906f32e7eSjoerg IRCallArgs[FirstIRArg + i] = LI;
496006f32e7eSjoerg }
496106f32e7eSjoerg } else {
496206f32e7eSjoerg // In the simple case, just pass the coerced loaded value.
496306f32e7eSjoerg assert(NumIRArgs == 1);
4964*13fbcb42Sjoerg llvm::Value *Load =
496506f32e7eSjoerg CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
4966*13fbcb42Sjoerg
4967*13fbcb42Sjoerg if (CallInfo.isCmseNSCall()) {
4968*13fbcb42Sjoerg // For certain parameter types, clear padding bits, as they may reveal
4969*13fbcb42Sjoerg // sensitive information.
4970*13fbcb42Sjoerg // Small struct/union types are passed as integer arrays.
4971*13fbcb42Sjoerg auto *ATy = dyn_cast<llvm::ArrayType>(Load->getType());
4972*13fbcb42Sjoerg if (ATy != nullptr && isa<RecordType>(I->Ty.getCanonicalType()))
4973*13fbcb42Sjoerg Load = EmitCMSEClearRecord(Load, ATy, I->Ty);
4974*13fbcb42Sjoerg }
4975*13fbcb42Sjoerg IRCallArgs[FirstIRArg] = Load;
497606f32e7eSjoerg }
497706f32e7eSjoerg
497806f32e7eSjoerg break;
497906f32e7eSjoerg }
498006f32e7eSjoerg
498106f32e7eSjoerg case ABIArgInfo::CoerceAndExpand: {
498206f32e7eSjoerg auto coercionType = ArgInfo.getCoerceAndExpandType();
498306f32e7eSjoerg auto layout = CGM.getDataLayout().getStructLayout(coercionType);
498406f32e7eSjoerg
498506f32e7eSjoerg llvm::Value *tempSize = nullptr;
498606f32e7eSjoerg Address addr = Address::invalid();
498706f32e7eSjoerg Address AllocaAddr = Address::invalid();
498806f32e7eSjoerg if (I->isAggregate()) {
4989*13fbcb42Sjoerg addr = I->hasLValue() ? I->getKnownLValue().getAddress(*this)
499006f32e7eSjoerg : I->getKnownRValue().getAggregateAddress();
499106f32e7eSjoerg
499206f32e7eSjoerg } else {
499306f32e7eSjoerg RValue RV = I->getKnownRValue();
499406f32e7eSjoerg assert(RV.isScalar()); // complex should always just be direct
499506f32e7eSjoerg
499606f32e7eSjoerg llvm::Type *scalarType = RV.getScalarVal()->getType();
499706f32e7eSjoerg auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
499806f32e7eSjoerg auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType);
499906f32e7eSjoerg
500006f32e7eSjoerg // Materialize to a temporary.
500106f32e7eSjoerg addr = CreateTempAlloca(
500206f32e7eSjoerg RV.getScalarVal()->getType(),
500306f32e7eSjoerg CharUnits::fromQuantity(std::max(
500406f32e7eSjoerg (unsigned)layout->getAlignment().value(), scalarAlign)),
500506f32e7eSjoerg "tmp",
500606f32e7eSjoerg /*ArraySize=*/nullptr, &AllocaAddr);
500706f32e7eSjoerg tempSize = EmitLifetimeStart(scalarSize, AllocaAddr.getPointer());
500806f32e7eSjoerg
500906f32e7eSjoerg Builder.CreateStore(RV.getScalarVal(), addr);
501006f32e7eSjoerg }
501106f32e7eSjoerg
501206f32e7eSjoerg addr = Builder.CreateElementBitCast(addr, coercionType);
501306f32e7eSjoerg
501406f32e7eSjoerg unsigned IRArgPos = FirstIRArg;
501506f32e7eSjoerg for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
501606f32e7eSjoerg llvm::Type *eltType = coercionType->getElementType(i);
501706f32e7eSjoerg if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
501806f32e7eSjoerg Address eltAddr = Builder.CreateStructGEP(addr, i);
501906f32e7eSjoerg llvm::Value *elt = Builder.CreateLoad(eltAddr);
502006f32e7eSjoerg IRCallArgs[IRArgPos++] = elt;
502106f32e7eSjoerg }
502206f32e7eSjoerg assert(IRArgPos == FirstIRArg + NumIRArgs);
502306f32e7eSjoerg
502406f32e7eSjoerg if (tempSize) {
502506f32e7eSjoerg EmitLifetimeEnd(tempSize, AllocaAddr.getPointer());
502606f32e7eSjoerg }
502706f32e7eSjoerg
502806f32e7eSjoerg break;
502906f32e7eSjoerg }
503006f32e7eSjoerg
5031*13fbcb42Sjoerg case ABIArgInfo::Expand: {
503206f32e7eSjoerg unsigned IRArgPos = FirstIRArg;
503306f32e7eSjoerg ExpandTypeToArgs(I->Ty, *I, IRFuncTy, IRCallArgs, IRArgPos);
503406f32e7eSjoerg assert(IRArgPos == FirstIRArg + NumIRArgs);
503506f32e7eSjoerg break;
503606f32e7eSjoerg }
503706f32e7eSjoerg }
5038*13fbcb42Sjoerg }
503906f32e7eSjoerg
504006f32e7eSjoerg const CGCallee &ConcreteCallee = Callee.prepareConcreteCallee(*this);
504106f32e7eSjoerg llvm::Value *CalleePtr = ConcreteCallee.getFunctionPointer();
504206f32e7eSjoerg
504306f32e7eSjoerg // If we're using inalloca, set up that argument.
504406f32e7eSjoerg if (ArgMemory.isValid()) {
504506f32e7eSjoerg llvm::Value *Arg = ArgMemory.getPointer();
504606f32e7eSjoerg if (CallInfo.isVariadic()) {
504706f32e7eSjoerg // When passing non-POD arguments by value to variadic functions, we will
504806f32e7eSjoerg // end up with a variadic prototype and an inalloca call site. In such
504906f32e7eSjoerg // cases, we can't do any parameter mismatch checks. Give up and bitcast
505006f32e7eSjoerg // the callee.
505106f32e7eSjoerg unsigned CalleeAS = CalleePtr->getType()->getPointerAddressSpace();
505206f32e7eSjoerg CalleePtr =
505306f32e7eSjoerg Builder.CreateBitCast(CalleePtr, IRFuncTy->getPointerTo(CalleeAS));
505406f32e7eSjoerg } else {
505506f32e7eSjoerg llvm::Type *LastParamTy =
505606f32e7eSjoerg IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
505706f32e7eSjoerg if (Arg->getType() != LastParamTy) {
505806f32e7eSjoerg #ifndef NDEBUG
505906f32e7eSjoerg // Assert that these structs have equivalent element types.
506006f32e7eSjoerg llvm::StructType *FullTy = CallInfo.getArgStruct();
506106f32e7eSjoerg llvm::StructType *DeclaredTy = cast<llvm::StructType>(
506206f32e7eSjoerg cast<llvm::PointerType>(LastParamTy)->getElementType());
506306f32e7eSjoerg assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
506406f32e7eSjoerg for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
506506f32e7eSjoerg DE = DeclaredTy->element_end(),
506606f32e7eSjoerg FI = FullTy->element_begin();
506706f32e7eSjoerg DI != DE; ++DI, ++FI)
506806f32e7eSjoerg assert(*DI == *FI);
506906f32e7eSjoerg #endif
507006f32e7eSjoerg Arg = Builder.CreateBitCast(Arg, LastParamTy);
507106f32e7eSjoerg }
507206f32e7eSjoerg }
507306f32e7eSjoerg assert(IRFunctionArgs.hasInallocaArg());
507406f32e7eSjoerg IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
507506f32e7eSjoerg }
507606f32e7eSjoerg
507706f32e7eSjoerg // 2. Prepare the function pointer.
507806f32e7eSjoerg
507906f32e7eSjoerg // If the callee is a bitcast of a non-variadic function to have a
508006f32e7eSjoerg // variadic function pointer type, check to see if we can remove the
508106f32e7eSjoerg // bitcast. This comes up with unprototyped functions.
508206f32e7eSjoerg //
508306f32e7eSjoerg // This makes the IR nicer, but more importantly it ensures that we
508406f32e7eSjoerg // can inline the function at -O0 if it is marked always_inline.
508506f32e7eSjoerg auto simplifyVariadicCallee = [](llvm::FunctionType *CalleeFT,
508606f32e7eSjoerg llvm::Value *Ptr) -> llvm::Function * {
508706f32e7eSjoerg if (!CalleeFT->isVarArg())
508806f32e7eSjoerg return nullptr;
508906f32e7eSjoerg
509006f32e7eSjoerg // Get underlying value if it's a bitcast
509106f32e7eSjoerg if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr)) {
509206f32e7eSjoerg if (CE->getOpcode() == llvm::Instruction::BitCast)
509306f32e7eSjoerg Ptr = CE->getOperand(0);
509406f32e7eSjoerg }
509506f32e7eSjoerg
509606f32e7eSjoerg llvm::Function *OrigFn = dyn_cast<llvm::Function>(Ptr);
509706f32e7eSjoerg if (!OrigFn)
509806f32e7eSjoerg return nullptr;
509906f32e7eSjoerg
510006f32e7eSjoerg llvm::FunctionType *OrigFT = OrigFn->getFunctionType();
510106f32e7eSjoerg
510206f32e7eSjoerg // If the original type is variadic, or if any of the component types
510306f32e7eSjoerg // disagree, we cannot remove the cast.
510406f32e7eSjoerg if (OrigFT->isVarArg() ||
510506f32e7eSjoerg OrigFT->getNumParams() != CalleeFT->getNumParams() ||
510606f32e7eSjoerg OrigFT->getReturnType() != CalleeFT->getReturnType())
510706f32e7eSjoerg return nullptr;
510806f32e7eSjoerg
510906f32e7eSjoerg for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i)
511006f32e7eSjoerg if (OrigFT->getParamType(i) != CalleeFT->getParamType(i))
511106f32e7eSjoerg return nullptr;
511206f32e7eSjoerg
511306f32e7eSjoerg return OrigFn;
511406f32e7eSjoerg };
511506f32e7eSjoerg
511606f32e7eSjoerg if (llvm::Function *OrigFn = simplifyVariadicCallee(IRFuncTy, CalleePtr)) {
511706f32e7eSjoerg CalleePtr = OrigFn;
511806f32e7eSjoerg IRFuncTy = OrigFn->getFunctionType();
511906f32e7eSjoerg }
512006f32e7eSjoerg
512106f32e7eSjoerg // 3. Perform the actual call.
512206f32e7eSjoerg
512306f32e7eSjoerg // Deactivate any cleanups that we're supposed to do immediately before
512406f32e7eSjoerg // the call.
512506f32e7eSjoerg if (!CallArgs.getCleanupsToDeactivate().empty())
512606f32e7eSjoerg deactivateArgCleanupsBeforeCall(*this, CallArgs);
512706f32e7eSjoerg
512806f32e7eSjoerg // Assert that the arguments we computed match up. The IR verifier
512906f32e7eSjoerg // will catch this, but this is a common enough source of problems
513006f32e7eSjoerg // during IRGen changes that it's way better for debugging to catch
513106f32e7eSjoerg // it ourselves here.
513206f32e7eSjoerg #ifndef NDEBUG
513306f32e7eSjoerg assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
513406f32e7eSjoerg for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
513506f32e7eSjoerg // Inalloca argument can have different type.
513606f32e7eSjoerg if (IRFunctionArgs.hasInallocaArg() &&
513706f32e7eSjoerg i == IRFunctionArgs.getInallocaArgNo())
513806f32e7eSjoerg continue;
513906f32e7eSjoerg if (i < IRFuncTy->getNumParams())
514006f32e7eSjoerg assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
514106f32e7eSjoerg }
514206f32e7eSjoerg #endif
514306f32e7eSjoerg
514406f32e7eSjoerg // Update the largest vector width if any arguments have vector types.
514506f32e7eSjoerg for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
514606f32e7eSjoerg if (auto *VT = dyn_cast<llvm::VectorType>(IRCallArgs[i]->getType()))
5147*13fbcb42Sjoerg LargestVectorWidth =
5148*13fbcb42Sjoerg std::max((uint64_t)LargestVectorWidth,
5149*13fbcb42Sjoerg VT->getPrimitiveSizeInBits().getKnownMinSize());
515006f32e7eSjoerg }
515106f32e7eSjoerg
515206f32e7eSjoerg // Compute the calling convention and attributes.
515306f32e7eSjoerg unsigned CallingConv;
515406f32e7eSjoerg llvm::AttributeList Attrs;
515506f32e7eSjoerg CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo,
515606f32e7eSjoerg Callee.getAbstractInfo(), Attrs, CallingConv,
5157*13fbcb42Sjoerg /*AttrOnCallSite=*/true,
5158*13fbcb42Sjoerg /*IsThunk=*/false);
5159*13fbcb42Sjoerg
5160*13fbcb42Sjoerg if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl))
5161*13fbcb42Sjoerg if (FD->hasAttr<StrictFPAttr>())
5162*13fbcb42Sjoerg // All calls within a strictfp function are marked strictfp
5163*13fbcb42Sjoerg Attrs =
5164*13fbcb42Sjoerg Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
5165*13fbcb42Sjoerg llvm::Attribute::StrictFP);
5166*13fbcb42Sjoerg
5167*13fbcb42Sjoerg // Add call-site nomerge attribute if exists.
5168*13fbcb42Sjoerg if (InNoMergeAttributedStmt)
5169*13fbcb42Sjoerg Attrs =
5170*13fbcb42Sjoerg Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
5171*13fbcb42Sjoerg llvm::Attribute::NoMerge);
517206f32e7eSjoerg
517306f32e7eSjoerg // Apply some call-site-specific attributes.
517406f32e7eSjoerg // TODO: work this into building the attribute set.
517506f32e7eSjoerg
517606f32e7eSjoerg // Apply always_inline to all calls within flatten functions.
517706f32e7eSjoerg // FIXME: should this really take priority over __try, below?
517806f32e7eSjoerg if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
517906f32e7eSjoerg !(TargetDecl && TargetDecl->hasAttr<NoInlineAttr>())) {
518006f32e7eSjoerg Attrs =
518106f32e7eSjoerg Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
518206f32e7eSjoerg llvm::Attribute::AlwaysInline);
518306f32e7eSjoerg }
518406f32e7eSjoerg
518506f32e7eSjoerg // Disable inlining inside SEH __try blocks.
518606f32e7eSjoerg if (isSEHTryScope()) {
518706f32e7eSjoerg Attrs =
518806f32e7eSjoerg Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
518906f32e7eSjoerg llvm::Attribute::NoInline);
519006f32e7eSjoerg }
519106f32e7eSjoerg
519206f32e7eSjoerg // Decide whether to use a call or an invoke.
519306f32e7eSjoerg bool CannotThrow;
519406f32e7eSjoerg if (currentFunctionUsesSEHTry()) {
519506f32e7eSjoerg // SEH cares about asynchronous exceptions, so everything can "throw."
519606f32e7eSjoerg CannotThrow = false;
519706f32e7eSjoerg } else if (isCleanupPadScope() &&
519806f32e7eSjoerg EHPersonality::get(*this).isMSVCXXPersonality()) {
519906f32e7eSjoerg // The MSVC++ personality will implicitly terminate the program if an
520006f32e7eSjoerg // exception is thrown during a cleanup outside of a try/catch.
520106f32e7eSjoerg // We don't need to model anything in IR to get this behavior.
520206f32e7eSjoerg CannotThrow = true;
520306f32e7eSjoerg } else {
520406f32e7eSjoerg // Otherwise, nounwind call sites will never throw.
5205*13fbcb42Sjoerg CannotThrow = Attrs.hasFnAttribute(llvm::Attribute::NoUnwind);
5206*13fbcb42Sjoerg
5207*13fbcb42Sjoerg if (auto *FPtr = dyn_cast<llvm::Function>(CalleePtr))
5208*13fbcb42Sjoerg if (FPtr->hasFnAttribute(llvm::Attribute::NoUnwind))
5209*13fbcb42Sjoerg CannotThrow = true;
521006f32e7eSjoerg }
521106f32e7eSjoerg
521206f32e7eSjoerg // If we made a temporary, be sure to clean up after ourselves. Note that we
521306f32e7eSjoerg // can't depend on being inside of an ExprWithCleanups, so we need to manually
521406f32e7eSjoerg // pop this cleanup later on. Being eager about this is OK, since this
521506f32e7eSjoerg // temporary is 'invisible' outside of the callee.
521606f32e7eSjoerg if (UnusedReturnSizePtr)
521706f32e7eSjoerg pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, SRetAlloca,
521806f32e7eSjoerg UnusedReturnSizePtr);
521906f32e7eSjoerg
522006f32e7eSjoerg llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
522106f32e7eSjoerg
522206f32e7eSjoerg SmallVector<llvm::OperandBundleDef, 1> BundleList =
522306f32e7eSjoerg getBundlesForFunclet(CalleePtr);
522406f32e7eSjoerg
5225*13fbcb42Sjoerg if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl))
5226*13fbcb42Sjoerg if (FD->hasAttr<StrictFPAttr>())
5227*13fbcb42Sjoerg // All calls within a strictfp function are marked strictfp
5228*13fbcb42Sjoerg Attrs =
5229*13fbcb42Sjoerg Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
5230*13fbcb42Sjoerg llvm::Attribute::StrictFP);
5231*13fbcb42Sjoerg
5232*13fbcb42Sjoerg AssumeAlignedAttrEmitter AssumeAlignedAttrEmitter(*this, TargetDecl);
5233*13fbcb42Sjoerg Attrs = AssumeAlignedAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
5234*13fbcb42Sjoerg
5235*13fbcb42Sjoerg AllocAlignAttrEmitter AllocAlignAttrEmitter(*this, TargetDecl, CallArgs);
5236*13fbcb42Sjoerg Attrs = AllocAlignAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
5237*13fbcb42Sjoerg
523806f32e7eSjoerg // Emit the actual call/invoke instruction.
523906f32e7eSjoerg llvm::CallBase *CI;
524006f32e7eSjoerg if (!InvokeDest) {
524106f32e7eSjoerg CI = Builder.CreateCall(IRFuncTy, CalleePtr, IRCallArgs, BundleList);
524206f32e7eSjoerg } else {
524306f32e7eSjoerg llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
524406f32e7eSjoerg CI = Builder.CreateInvoke(IRFuncTy, CalleePtr, Cont, InvokeDest, IRCallArgs,
524506f32e7eSjoerg BundleList);
524606f32e7eSjoerg EmitBlock(Cont);
524706f32e7eSjoerg }
524806f32e7eSjoerg if (callOrInvoke)
524906f32e7eSjoerg *callOrInvoke = CI;
525006f32e7eSjoerg
5251*13fbcb42Sjoerg // If this is within a function that has the guard(nocf) attribute and is an
5252*13fbcb42Sjoerg // indirect call, add the "guard_nocf" attribute to this call to indicate that
5253*13fbcb42Sjoerg // Control Flow Guard checks should not be added, even if the call is inlined.
5254*13fbcb42Sjoerg if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
5255*13fbcb42Sjoerg if (const auto *A = FD->getAttr<CFGuardAttr>()) {
5256*13fbcb42Sjoerg if (A->getGuard() == CFGuardAttr::GuardArg::nocf && !CI->getCalledFunction())
5257*13fbcb42Sjoerg Attrs = Attrs.addAttribute(
5258*13fbcb42Sjoerg getLLVMContext(), llvm::AttributeList::FunctionIndex, "guard_nocf");
5259*13fbcb42Sjoerg }
5260*13fbcb42Sjoerg }
5261*13fbcb42Sjoerg
526206f32e7eSjoerg // Apply the attributes and calling convention.
526306f32e7eSjoerg CI->setAttributes(Attrs);
526406f32e7eSjoerg CI->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
526506f32e7eSjoerg
526606f32e7eSjoerg // Apply various metadata.
526706f32e7eSjoerg
526806f32e7eSjoerg if (!CI->getType()->isVoidTy())
526906f32e7eSjoerg CI->setName("call");
527006f32e7eSjoerg
527106f32e7eSjoerg // Update largest vector width from the return type.
527206f32e7eSjoerg if (auto *VT = dyn_cast<llvm::VectorType>(CI->getType()))
5273*13fbcb42Sjoerg LargestVectorWidth =
5274*13fbcb42Sjoerg std::max((uint64_t)LargestVectorWidth,
5275*13fbcb42Sjoerg VT->getPrimitiveSizeInBits().getKnownMinSize());
527606f32e7eSjoerg
527706f32e7eSjoerg // Insert instrumentation or attach profile metadata at indirect call sites.
527806f32e7eSjoerg // For more details, see the comment before the definition of
527906f32e7eSjoerg // IPVK_IndirectCallTarget in InstrProfData.inc.
528006f32e7eSjoerg if (!CI->getCalledFunction())
528106f32e7eSjoerg PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
528206f32e7eSjoerg CI, CalleePtr);
528306f32e7eSjoerg
528406f32e7eSjoerg // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
528506f32e7eSjoerg // optimizer it can aggressively ignore unwind edges.
528606f32e7eSjoerg if (CGM.getLangOpts().ObjCAutoRefCount)
528706f32e7eSjoerg AddObjCARCExceptionMetadata(CI);
528806f32e7eSjoerg
5289*13fbcb42Sjoerg // Set tail call kind if necessary.
529006f32e7eSjoerg if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
529106f32e7eSjoerg if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
529206f32e7eSjoerg Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
5293*13fbcb42Sjoerg else if (IsMustTail)
5294*13fbcb42Sjoerg Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
529506f32e7eSjoerg }
529606f32e7eSjoerg
529706f32e7eSjoerg // Add metadata for calls to MSAllocator functions
529806f32e7eSjoerg if (getDebugInfo() && TargetDecl &&
529906f32e7eSjoerg TargetDecl->hasAttr<MSAllocatorAttr>())
5300*13fbcb42Sjoerg getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy->getPointeeType(), Loc);
530106f32e7eSjoerg
530206f32e7eSjoerg // 4. Finish the call.
530306f32e7eSjoerg
530406f32e7eSjoerg // If the call doesn't return, finish the basic block and clear the
530506f32e7eSjoerg // insertion point; this allows the rest of IRGen to discard
530606f32e7eSjoerg // unreachable code.
530706f32e7eSjoerg if (CI->doesNotReturn()) {
530806f32e7eSjoerg if (UnusedReturnSizePtr)
530906f32e7eSjoerg PopCleanupBlock();
531006f32e7eSjoerg
531106f32e7eSjoerg // Strip away the noreturn attribute to better diagnose unreachable UB.
531206f32e7eSjoerg if (SanOpts.has(SanitizerKind::Unreachable)) {
531306f32e7eSjoerg // Also remove from function since CallBase::hasFnAttr additionally checks
531406f32e7eSjoerg // attributes of the called function.
531506f32e7eSjoerg if (auto *F = CI->getCalledFunction())
531606f32e7eSjoerg F->removeFnAttr(llvm::Attribute::NoReturn);
531706f32e7eSjoerg CI->removeAttribute(llvm::AttributeList::FunctionIndex,
531806f32e7eSjoerg llvm::Attribute::NoReturn);
531906f32e7eSjoerg
532006f32e7eSjoerg // Avoid incompatibility with ASan which relies on the `noreturn`
532106f32e7eSjoerg // attribute to insert handler calls.
532206f32e7eSjoerg if (SanOpts.hasOneOf(SanitizerKind::Address |
532306f32e7eSjoerg SanitizerKind::KernelAddress)) {
532406f32e7eSjoerg SanitizerScope SanScope(this);
532506f32e7eSjoerg llvm::IRBuilder<>::InsertPointGuard IPGuard(Builder);
532606f32e7eSjoerg Builder.SetInsertPoint(CI);
532706f32e7eSjoerg auto *FnType = llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
532806f32e7eSjoerg llvm::FunctionCallee Fn =
532906f32e7eSjoerg CGM.CreateRuntimeFunction(FnType, "__asan_handle_no_return");
533006f32e7eSjoerg EmitNounwindRuntimeCall(Fn);
533106f32e7eSjoerg }
533206f32e7eSjoerg }
533306f32e7eSjoerg
533406f32e7eSjoerg EmitUnreachable(Loc);
533506f32e7eSjoerg Builder.ClearInsertionPoint();
533606f32e7eSjoerg
533706f32e7eSjoerg // FIXME: For now, emit a dummy basic block because expr emitters in
533806f32e7eSjoerg // generally are not ready to handle emitting expressions at unreachable
533906f32e7eSjoerg // points.
534006f32e7eSjoerg EnsureInsertPoint();
534106f32e7eSjoerg
534206f32e7eSjoerg // Return a reasonable RValue.
534306f32e7eSjoerg return GetUndefRValue(RetTy);
534406f32e7eSjoerg }
534506f32e7eSjoerg
5346*13fbcb42Sjoerg // If this is a musttail call, return immediately. We do not branch to the
5347*13fbcb42Sjoerg // epilogue in this case.
5348*13fbcb42Sjoerg if (IsMustTail) {
5349*13fbcb42Sjoerg for (auto it = EHStack.find(CurrentCleanupScopeDepth); it != EHStack.end();
5350*13fbcb42Sjoerg ++it) {
5351*13fbcb42Sjoerg EHCleanupScope *Cleanup = dyn_cast<EHCleanupScope>(&*it);
5352*13fbcb42Sjoerg if (!(Cleanup && Cleanup->getCleanup()->isRedundantBeforeReturn()))
5353*13fbcb42Sjoerg CGM.ErrorUnsupported(MustTailCall, "tail call skipping over cleanups");
5354*13fbcb42Sjoerg }
5355*13fbcb42Sjoerg if (CI->getType()->isVoidTy())
5356*13fbcb42Sjoerg Builder.CreateRetVoid();
5357*13fbcb42Sjoerg else
5358*13fbcb42Sjoerg Builder.CreateRet(CI);
5359*13fbcb42Sjoerg Builder.ClearInsertionPoint();
5360*13fbcb42Sjoerg EnsureInsertPoint();
5361*13fbcb42Sjoerg return GetUndefRValue(RetTy);
5362*13fbcb42Sjoerg }
5363*13fbcb42Sjoerg
536406f32e7eSjoerg // Perform the swifterror writeback.
536506f32e7eSjoerg if (swiftErrorTemp.isValid()) {
536606f32e7eSjoerg llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
536706f32e7eSjoerg Builder.CreateStore(errorResult, swiftErrorArg);
536806f32e7eSjoerg }
536906f32e7eSjoerg
537006f32e7eSjoerg // Emit any call-associated writebacks immediately. Arguably this
537106f32e7eSjoerg // should happen after any return-value munging.
537206f32e7eSjoerg if (CallArgs.hasWritebacks())
537306f32e7eSjoerg emitWritebacks(*this, CallArgs);
537406f32e7eSjoerg
537506f32e7eSjoerg // The stack cleanup for inalloca arguments has to run out of the normal
537606f32e7eSjoerg // lexical order, so deactivate it and run it manually here.
537706f32e7eSjoerg CallArgs.freeArgumentMemory(*this);
537806f32e7eSjoerg
537906f32e7eSjoerg // Extract the return value.
538006f32e7eSjoerg RValue Ret = [&] {
538106f32e7eSjoerg switch (RetAI.getKind()) {
538206f32e7eSjoerg case ABIArgInfo::CoerceAndExpand: {
538306f32e7eSjoerg auto coercionType = RetAI.getCoerceAndExpandType();
538406f32e7eSjoerg
538506f32e7eSjoerg Address addr = SRetPtr;
538606f32e7eSjoerg addr = Builder.CreateElementBitCast(addr, coercionType);
538706f32e7eSjoerg
538806f32e7eSjoerg assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
538906f32e7eSjoerg bool requiresExtract = isa<llvm::StructType>(CI->getType());
539006f32e7eSjoerg
539106f32e7eSjoerg unsigned unpaddedIndex = 0;
539206f32e7eSjoerg for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
539306f32e7eSjoerg llvm::Type *eltType = coercionType->getElementType(i);
539406f32e7eSjoerg if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
539506f32e7eSjoerg Address eltAddr = Builder.CreateStructGEP(addr, i);
539606f32e7eSjoerg llvm::Value *elt = CI;
539706f32e7eSjoerg if (requiresExtract)
539806f32e7eSjoerg elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
539906f32e7eSjoerg else
540006f32e7eSjoerg assert(unpaddedIndex == 0);
540106f32e7eSjoerg Builder.CreateStore(elt, eltAddr);
540206f32e7eSjoerg }
540306f32e7eSjoerg // FALLTHROUGH
540406f32e7eSjoerg LLVM_FALLTHROUGH;
540506f32e7eSjoerg }
540606f32e7eSjoerg
540706f32e7eSjoerg case ABIArgInfo::InAlloca:
540806f32e7eSjoerg case ABIArgInfo::Indirect: {
540906f32e7eSjoerg RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
541006f32e7eSjoerg if (UnusedReturnSizePtr)
541106f32e7eSjoerg PopCleanupBlock();
541206f32e7eSjoerg return ret;
541306f32e7eSjoerg }
541406f32e7eSjoerg
541506f32e7eSjoerg case ABIArgInfo::Ignore:
541606f32e7eSjoerg // If we are ignoring an argument that had a result, make sure to
541706f32e7eSjoerg // construct the appropriate return value for our caller.
541806f32e7eSjoerg return GetUndefRValue(RetTy);
541906f32e7eSjoerg
542006f32e7eSjoerg case ABIArgInfo::Extend:
542106f32e7eSjoerg case ABIArgInfo::Direct: {
542206f32e7eSjoerg llvm::Type *RetIRTy = ConvertType(RetTy);
542306f32e7eSjoerg if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
542406f32e7eSjoerg switch (getEvaluationKind(RetTy)) {
542506f32e7eSjoerg case TEK_Complex: {
542606f32e7eSjoerg llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
542706f32e7eSjoerg llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
542806f32e7eSjoerg return RValue::getComplex(std::make_pair(Real, Imag));
542906f32e7eSjoerg }
543006f32e7eSjoerg case TEK_Aggregate: {
543106f32e7eSjoerg Address DestPtr = ReturnValue.getValue();
543206f32e7eSjoerg bool DestIsVolatile = ReturnValue.isVolatile();
543306f32e7eSjoerg
543406f32e7eSjoerg if (!DestPtr.isValid()) {
543506f32e7eSjoerg DestPtr = CreateMemTemp(RetTy, "agg.tmp");
543606f32e7eSjoerg DestIsVolatile = false;
543706f32e7eSjoerg }
5438*13fbcb42Sjoerg EmitAggregateStore(CI, DestPtr, DestIsVolatile);
543906f32e7eSjoerg return RValue::getAggregate(DestPtr);
544006f32e7eSjoerg }
544106f32e7eSjoerg case TEK_Scalar: {
544206f32e7eSjoerg // If the argument doesn't match, perform a bitcast to coerce it. This
544306f32e7eSjoerg // can happen due to trivial type mismatches.
544406f32e7eSjoerg llvm::Value *V = CI;
544506f32e7eSjoerg if (V->getType() != RetIRTy)
544606f32e7eSjoerg V = Builder.CreateBitCast(V, RetIRTy);
544706f32e7eSjoerg return RValue::get(V);
544806f32e7eSjoerg }
544906f32e7eSjoerg }
545006f32e7eSjoerg llvm_unreachable("bad evaluation kind");
545106f32e7eSjoerg }
545206f32e7eSjoerg
545306f32e7eSjoerg Address DestPtr = ReturnValue.getValue();
545406f32e7eSjoerg bool DestIsVolatile = ReturnValue.isVolatile();
545506f32e7eSjoerg
545606f32e7eSjoerg if (!DestPtr.isValid()) {
545706f32e7eSjoerg DestPtr = CreateMemTemp(RetTy, "coerce");
545806f32e7eSjoerg DestIsVolatile = false;
545906f32e7eSjoerg }
546006f32e7eSjoerg
546106f32e7eSjoerg // If the value is offset in memory, apply the offset now.
546206f32e7eSjoerg Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
546306f32e7eSjoerg CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
546406f32e7eSjoerg
546506f32e7eSjoerg return convertTempToRValue(DestPtr, RetTy, SourceLocation());
546606f32e7eSjoerg }
546706f32e7eSjoerg
546806f32e7eSjoerg case ABIArgInfo::Expand:
5469*13fbcb42Sjoerg case ABIArgInfo::IndirectAliased:
547006f32e7eSjoerg llvm_unreachable("Invalid ABI kind for return argument");
547106f32e7eSjoerg }
547206f32e7eSjoerg
547306f32e7eSjoerg llvm_unreachable("Unhandled ABIArgInfo::Kind");
547406f32e7eSjoerg } ();
547506f32e7eSjoerg
547606f32e7eSjoerg // Emit the assume_aligned check on the return value.
547706f32e7eSjoerg if (Ret.isScalar() && TargetDecl) {
5478*13fbcb42Sjoerg AssumeAlignedAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
5479*13fbcb42Sjoerg AllocAlignAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
548006f32e7eSjoerg }
548106f32e7eSjoerg
548206f32e7eSjoerg // Explicitly call CallLifetimeEnd::Emit just to re-use the code even though
548306f32e7eSjoerg // we can't use the full cleanup mechanism.
548406f32e7eSjoerg for (CallLifetimeEnd &LifetimeEnd : CallLifetimeEndAfterCall)
548506f32e7eSjoerg LifetimeEnd.Emit(*this, /*Flags=*/{});
548606f32e7eSjoerg
5487*13fbcb42Sjoerg if (!ReturnValue.isExternallyDestructed() &&
5488*13fbcb42Sjoerg RetTy.isDestructedType() == QualType::DK_nontrivial_c_struct)
5489*13fbcb42Sjoerg pushDestroy(QualType::DK_nontrivial_c_struct, Ret.getAggregateAddress(),
5490*13fbcb42Sjoerg RetTy);
5491*13fbcb42Sjoerg
549206f32e7eSjoerg return Ret;
549306f32e7eSjoerg }
549406f32e7eSjoerg
prepareConcreteCallee(CodeGenFunction & CGF) const549506f32e7eSjoerg CGCallee CGCallee::prepareConcreteCallee(CodeGenFunction &CGF) const {
549606f32e7eSjoerg if (isVirtual()) {
549706f32e7eSjoerg const CallExpr *CE = getVirtualCallExpr();
549806f32e7eSjoerg return CGF.CGM.getCXXABI().getVirtualFunctionPointer(
549906f32e7eSjoerg CGF, getVirtualMethodDecl(), getThisAddress(), getVirtualFunctionType(),
550006f32e7eSjoerg CE ? CE->getBeginLoc() : SourceLocation());
550106f32e7eSjoerg }
550206f32e7eSjoerg
550306f32e7eSjoerg return *this;
550406f32e7eSjoerg }
550506f32e7eSjoerg
550606f32e7eSjoerg /* VarArg handling */
550706f32e7eSjoerg
EmitVAArg(VAArgExpr * VE,Address & VAListAddr)550806f32e7eSjoerg Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
550906f32e7eSjoerg VAListAddr = VE->isMicrosoftABI()
551006f32e7eSjoerg ? EmitMSVAListRef(VE->getSubExpr())
551106f32e7eSjoerg : EmitVAListRef(VE->getSubExpr());
551206f32e7eSjoerg QualType Ty = VE->getType();
551306f32e7eSjoerg if (VE->isMicrosoftABI())
551406f32e7eSjoerg return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
551506f32e7eSjoerg return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
551606f32e7eSjoerg }
5517