blob: d0712e7d030999198c98e2830b40e9a44529ee5b [file] [log] [blame]
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001//===--- CGCall.cpp - Encapsulate calling convention details --------------===//
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CGCall.h"
Chris Lattnere70a0072010-06-29 16:40:28 +000016#include "ABIInfo.h"
Akira Hatanaka9d8ac612016-02-17 21:09:50 +000017#include "CGBlocks.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CGCXXABI.h"
David Majnemer4e52d6f2015-12-12 05:39:21 +000019#include "CGCleanup.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000020#include "CodeGenFunction.h"
Daniel Dunbarc68897d2008-09-10 00:41:16 +000021#include "CodeGenModule.h"
John McCalla729c622012-02-17 03:33:10 +000022#include "TargetInfo.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000023#include "clang/AST/Decl.h"
Anders Carlssonb15b55c2009-04-03 22:48:58 +000024#include "clang/AST/DeclCXX.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000025#include "clang/AST/DeclObjC.h"
Saleem Abdulrasool94cfc602016-04-07 17:49:44 +000026#include "clang/Basic/CodeGenOptions.h"
Eric Christopher15709992015-10-15 23:47:11 +000027#include "clang/Basic/TargetBuiltins.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000029#include "clang/CodeGen/CGFunctionInfo.h"
John McCall12f23522016-04-04 18:33:08 +000030#include "clang/CodeGen/SwiftCallingConv.h"
Bill Wendling706469b2013-02-28 22:49:57 +000031#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/Attributes.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000033#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000034#include "llvm/IR/DataLayout.h"
35#include "llvm/IR/InlineAsm.h"
David Majnemerdc012fa2015-04-22 21:38:15 +000036#include "llvm/IR/IntrinsicInst.h"
Saleem Abdulrasool94cfc602016-04-07 17:49:44 +000037#include "llvm/IR/Intrinsics.h"
Eli Friedmanf7456192011-06-15 22:09:18 +000038#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000039using namespace clang;
40using namespace CodeGen;
41
42/***/
43
John McCallab26cfa2010-02-05 21:31:56 +000044static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) {
45 switch (CC) {
46 default: return llvm::CallingConv::C;
47 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
48 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
Douglas Gregora941dca2010-05-18 16:57:00 +000049 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Charles Davisb5a214e2013-08-30 04:39:01 +000050 case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64;
51 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
Anton Korobeynikov231e8752011-04-14 20:06:49 +000052 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
53 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Guy Benyeif0a014b2012-12-25 08:53:55 +000054 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Reid Klecknerd7857f02014-10-24 17:42:17 +000055 // TODO: Add support for __pascal to LLVM.
56 case CC_X86Pascal: return llvm::CallingConv::C;
57 // TODO: Add support for __vectorcall to LLVM.
Reid Kleckner80944df2014-10-31 22:00:51 +000058 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
Alexander Kornienko21de0ae2015-01-20 11:20:41 +000059 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
60 case CC_SpirKernel: return llvm::CallingConv::SPIR_KERNEL;
Roman Levenstein35aa5ce2016-03-16 18:00:46 +000061 case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
62 case CC_PreserveAll: return llvm::CallingConv::PreserveAll;
John McCall12f23522016-04-04 18:33:08 +000063 case CC_Swift: return llvm::CallingConv::Swift;
John McCallab26cfa2010-02-05 21:31:56 +000064 }
65}
66
John McCall8ee376f2010-02-24 07:14:12 +000067/// Derives the 'this' type for codegen purposes, i.e. ignoring method
68/// qualification.
69/// FIXME: address space qualification?
John McCall2da83a32010-02-26 00:48:12 +000070static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
71 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
72 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000073}
74
John McCall8ee376f2010-02-24 07:14:12 +000075/// Returns the canonical formal type of the given C++ method.
John McCall2da83a32010-02-26 00:48:12 +000076static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
77 return MD->getType()->getCanonicalTypeUnqualified()
78 .getAs<FunctionProtoType>();
John McCall8ee376f2010-02-24 07:14:12 +000079}
80
81/// Returns the "extra-canonicalized" return type, which discards
82/// qualifiers on the return type. Codegen doesn't care about them,
83/// and it makes ABI code a little easier to be able to assume that
84/// all parameter and return types are top-level unqualified.
John McCall2da83a32010-02-26 00:48:12 +000085static CanQualType GetReturnType(QualType RetTy) {
86 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall8ee376f2010-02-24 07:14:12 +000087}
88
John McCall8dda7b22012-07-07 06:41:13 +000089/// Arrange the argument and result information for a value of the given
90/// unprototyped freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +000091const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +000092CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCalla729c622012-02-17 03:33:10 +000093 // When translating an unprototyped function type, always use a
94 // variadic type.
Alp Toker314cc812014-01-25 16:55:45 +000095 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
Peter Collingbournef7706832014-12-12 23:41:25 +000096 /*instanceMethod=*/false,
97 /*chainCall=*/false, None,
John McCallc56a8b32016-03-11 04:30:31 +000098 FTNP->getExtInfo(), {}, RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +000099}
100
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000101/// Adds the formal paramaters in FPT to the given prefix. If any parameter in
102/// FPT has pass_object_size attrs, then we'll add parameters for those, too.
103static void appendParameterTypes(const CodeGenTypes &CGT,
104 SmallVectorImpl<CanQualType> &prefix,
John McCallc56a8b32016-03-11 04:30:31 +0000105 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
106 CanQual<FunctionProtoType> FPT,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000107 const FunctionDecl *FD) {
John McCallc56a8b32016-03-11 04:30:31 +0000108 // Fill out paramInfos.
109 if (FPT->hasExtParameterInfos() || !paramInfos.empty()) {
110 assert(paramInfos.size() <= prefix.size());
111 auto protoParamInfos = FPT->getExtParameterInfos();
112 paramInfos.reserve(prefix.size() + protoParamInfos.size());
113 paramInfos.resize(prefix.size());
John McCall12f23522016-04-04 18:33:08 +0000114 paramInfos.append(protoParamInfos.begin(), protoParamInfos.end());
John McCallc56a8b32016-03-11 04:30:31 +0000115 }
116
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000117 // Fast path: unknown target.
118 if (FD == nullptr) {
119 prefix.append(FPT->param_type_begin(), FPT->param_type_end());
120 return;
121 }
122
123 // In the vast majority cases, we'll have precisely FPT->getNumParams()
124 // parameters; the only thing that can change this is the presence of
125 // pass_object_size. So, we preallocate for the common case.
126 prefix.reserve(prefix.size() + FPT->getNumParams());
127
128 assert(FD->getNumParams() == FPT->getNumParams());
129 for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
130 prefix.push_back(FPT->getParamType(I));
131 if (FD->getParamDecl(I)->hasAttr<PassObjectSizeAttr>())
132 prefix.push_back(CGT.getContext().getSizeType());
133 }
134}
135
John McCall8dda7b22012-07-07 06:41:13 +0000136/// Arrange the LLVM function layout for a value of the given function
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000137/// type, on top of any implicit parameters already stored.
138static const CGFunctionInfo &
Peter Collingbournef7706832014-12-12 23:41:25 +0000139arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000140 SmallVectorImpl<CanQualType> &prefix,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000141 CanQual<FunctionProtoType> FTP,
142 const FunctionDecl *FD) {
John McCallc56a8b32016-03-11 04:30:31 +0000143 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
John McCall8dda7b22012-07-07 06:41:13 +0000144 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000145 // FIXME: Kill copy.
John McCallc56a8b32016-03-11 04:30:31 +0000146 appendParameterTypes(CGT, prefix, paramInfos, FTP, FD);
Alp Toker314cc812014-01-25 16:55:45 +0000147 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
John McCallc56a8b32016-03-11 04:30:31 +0000148
Peter Collingbournef7706832014-12-12 23:41:25 +0000149 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
150 /*chainCall=*/false, prefix,
John McCallc56a8b32016-03-11 04:30:31 +0000151 FTP->getExtInfo(), paramInfos,
152 required);
John McCall8ee376f2010-02-24 07:14:12 +0000153}
154
John McCalla729c622012-02-17 03:33:10 +0000155/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000156/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000157const CGFunctionInfo &
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000158CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP,
159 const FunctionDecl *FD) {
John McCalla729c622012-02-17 03:33:10 +0000160 SmallVector<CanQualType, 16> argTypes;
Peter Collingbournef7706832014-12-12 23:41:25 +0000161 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000162 FTP, FD);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000163}
164
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000165static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000166 // Set the appropriate calling convention for the Function.
167 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000168 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000169
170 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000171 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000172
Douglas Gregora941dca2010-05-18 16:57:00 +0000173 if (D->hasAttr<ThisCallAttr>())
174 return CC_X86ThisCall;
175
Reid Klecknerd7857f02014-10-24 17:42:17 +0000176 if (D->hasAttr<VectorCallAttr>())
177 return CC_X86VectorCall;
178
Dawn Perchik335e16b2010-09-03 01:29:35 +0000179 if (D->hasAttr<PascalAttr>())
180 return CC_X86Pascal;
181
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000182 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
183 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
184
Guy Benyeif0a014b2012-12-25 08:53:55 +0000185 if (D->hasAttr<IntelOclBiccAttr>())
186 return CC_IntelOclBicc;
187
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000188 if (D->hasAttr<MSABIAttr>())
189 return IsWindows ? CC_C : CC_X86_64Win64;
190
191 if (D->hasAttr<SysVABIAttr>())
192 return IsWindows ? CC_X86_64SysV : CC_C;
193
Roman Levenstein35aa5ce2016-03-16 18:00:46 +0000194 if (D->hasAttr<PreserveMostAttr>())
195 return CC_PreserveMost;
196
197 if (D->hasAttr<PreserveAllAttr>())
198 return CC_PreserveAll;
199
John McCallab26cfa2010-02-05 21:31:56 +0000200 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000201}
202
John McCalla729c622012-02-17 03:33:10 +0000203/// Arrange the argument and result information for a call to an
204/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000205/// (Zero value of RD means we don't have any meaningful "this" argument type,
206/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000207/// The member function must be an ordinary function, i.e. not a
208/// constructor or destructor.
209const CGFunctionInfo &
210CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000211 const FunctionProtoType *FTP,
212 const CXXMethodDecl *MD) {
John McCalla729c622012-02-17 03:33:10 +0000213 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000214
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000215 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000216 if (RD)
217 argTypes.push_back(GetThisType(Context, RD));
218 else
219 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000220
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000221 return ::arrangeLLVMFunctionInfo(
222 *this, true, argTypes,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000223 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>(), MD);
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000224}
225
John McCalla729c622012-02-17 03:33:10 +0000226/// Arrange the argument and result information for a declaration or
227/// definition of the given C++ non-static member function. The
228/// member function must be an ordinary function, i.e. not a
229/// constructor or destructor.
230const CGFunctionInfo &
231CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000232 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000233 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
234
John McCalla729c622012-02-17 03:33:10 +0000235 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000236
John McCalla729c622012-02-17 03:33:10 +0000237 if (MD->isInstance()) {
238 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000239 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000240 return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
John McCalla729c622012-02-17 03:33:10 +0000241 }
242
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000243 return arrangeFreeFunctionType(prototype, MD);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000244}
245
John McCalla729c622012-02-17 03:33:10 +0000246const CGFunctionInfo &
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000247CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
248 StructorType Type) {
249
John McCalla729c622012-02-17 03:33:10 +0000250 SmallVector<CanQualType, 16> argTypes;
John McCallc56a8b32016-03-11 04:30:31 +0000251 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000252 argTypes.push_back(GetThisType(Context, MD->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000253
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000254 GlobalDecl GD;
255 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
256 GD = GlobalDecl(CD, toCXXCtorType(Type));
257 } else {
258 auto *DD = dyn_cast<CXXDestructorDecl>(MD);
259 GD = GlobalDecl(DD, toCXXDtorType(Type));
260 }
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000261
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000262 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
John McCall5d865c322010-08-31 07:33:07 +0000263
264 // Add the formal parameters.
John McCallc56a8b32016-03-11 04:30:31 +0000265 appendParameterTypes(*this, argTypes, paramInfos, FTP, MD);
John McCall5d865c322010-08-31 07:33:07 +0000266
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000267 TheCXXABI.buildStructorSignature(MD, Type, argTypes);
Reid Kleckner89077a12013-12-17 19:46:40 +0000268
269 RequiredArgs required =
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000270 (MD->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All);
Reid Kleckner89077a12013-12-17 19:46:40 +0000271
John McCall8dda7b22012-07-07 06:41:13 +0000272 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000273 CanQualType resultType = TheCXXABI.HasThisReturn(GD)
274 ? argTypes.front()
275 : TheCXXABI.hasMostDerivedReturn(GD)
276 ? CGM.getContext().VoidPtrTy
277 : Context.VoidTy;
Peter Collingbournef7706832014-12-12 23:41:25 +0000278 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
279 /*chainCall=*/false, argTypes, extInfo,
John McCallc56a8b32016-03-11 04:30:31 +0000280 paramInfos, required);
281}
282
283static SmallVector<CanQualType, 16>
284getArgTypesForCall(ASTContext &ctx, const CallArgList &args) {
285 SmallVector<CanQualType, 16> argTypes;
286 for (auto &arg : args)
287 argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
288 return argTypes;
289}
290
291static SmallVector<CanQualType, 16>
292getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) {
293 SmallVector<CanQualType, 16> argTypes;
294 for (auto &arg : args)
295 argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
296 return argTypes;
297}
298
299static void addExtParameterInfosForCall(
300 llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
301 const FunctionProtoType *proto,
302 unsigned prefixArgs,
303 unsigned totalArgs) {
304 assert(proto->hasExtParameterInfos());
305 assert(paramInfos.size() <= prefixArgs);
306 assert(proto->getNumParams() + prefixArgs <= totalArgs);
307
308 // Add default infos for any prefix args that don't already have infos.
309 paramInfos.resize(prefixArgs);
310
311 // Add infos for the prototype.
312 auto protoInfos = proto->getExtParameterInfos();
313 paramInfos.append(protoInfos.begin(), protoInfos.end());
314
315 // Add default infos for the variadic arguments.
316 paramInfos.resize(totalArgs);
317}
318
319static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16>
320getExtParameterInfosForCall(const FunctionProtoType *proto,
321 unsigned prefixArgs, unsigned totalArgs) {
322 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result;
323 if (proto->hasExtParameterInfos()) {
324 addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
325 }
326 return result;
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000327}
328
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000329/// Arrange a call to a C++ method, passing the given arguments.
330const CGFunctionInfo &
331CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
332 const CXXConstructorDecl *D,
333 CXXCtorType CtorKind,
334 unsigned ExtraArgs) {
335 // FIXME: Kill copy.
336 SmallVector<CanQualType, 16> ArgTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000337 for (const auto &Arg : args)
338 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000339
340 CanQual<FunctionProtoType> FPT = GetFormalType(D);
341 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs);
342 GlobalDecl GD(D, CtorKind);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000343 CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
344 ? ArgTypes.front()
345 : TheCXXABI.hasMostDerivedReturn(GD)
346 ? CGM.getContext().VoidPtrTy
347 : Context.VoidTy;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000348
349 FunctionType::ExtInfo Info = FPT->getExtInfo();
John McCallc56a8b32016-03-11 04:30:31 +0000350 auto ParamInfos = getExtParameterInfosForCall(FPT.getTypePtr(), 1 + ExtraArgs,
351 ArgTypes.size());
Peter Collingbournef7706832014-12-12 23:41:25 +0000352 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
353 /*chainCall=*/false, ArgTypes, Info,
John McCallc56a8b32016-03-11 04:30:31 +0000354 ParamInfos, Required);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000355}
356
John McCalla729c622012-02-17 03:33:10 +0000357/// Arrange the argument and result information for the declaration or
358/// definition of the given function.
359const CGFunctionInfo &
360CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000361 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000362 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000363 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000364
John McCall2da83a32010-02-26 00:48:12 +0000365 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000366
John McCall2da83a32010-02-26 00:48:12 +0000367 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000368
369 // When declaring a function without a prototype, always use a
370 // non-variadic type.
371 if (isa<FunctionNoProtoType>(FTy)) {
372 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Peter Collingbournef7706832014-12-12 23:41:25 +0000373 return arrangeLLVMFunctionInfo(
374 noProto->getReturnType(), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000375 /*chainCall=*/false, None, noProto->getExtInfo(), {},RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000376 }
377
John McCall2da83a32010-02-26 00:48:12 +0000378 assert(isa<FunctionProtoType>(FTy));
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000379 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>(), FD);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000380}
381
John McCalla729c622012-02-17 03:33:10 +0000382/// Arrange the argument and result information for the declaration or
383/// definition of an Objective-C method.
384const CGFunctionInfo &
385CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
386 // It happens that this is the same as a call with no optional
387 // arguments, except also using the formal 'self' type.
388 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
389}
390
391/// Arrange the argument and result information for the function type
392/// through which to perform a send to the given Objective-C method,
393/// using the given receiver type. The receiver type is not always
394/// the 'self' type of the method or even an Objective-C pointer type.
395/// This is *not* the right method for actually performing such a
396/// message send, due to the possibility of optional arguments.
397const CGFunctionInfo &
398CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
399 QualType receiverType) {
400 SmallVector<CanQualType, 16> argTys;
401 argTys.push_back(Context.getCanonicalParamType(receiverType));
402 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000403 // FIXME: Kill copy?
Aaron Ballman43b68be2014-03-07 17:50:17 +0000404 for (const auto *I : MD->params()) {
405 argTys.push_back(Context.getCanonicalParamType(I->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000406 }
John McCall31168b02011-06-15 23:02:42 +0000407
408 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000409 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
410 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000411
David Blaikiebbafb8a2012-03-11 07:00:24 +0000412 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000413 MD->hasAttr<NSReturnsRetainedAttr>())
414 einfo = einfo.withProducesResult(true);
415
John McCalla729c622012-02-17 03:33:10 +0000416 RequiredArgs required =
417 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
418
Peter Collingbournef7706832014-12-12 23:41:25 +0000419 return arrangeLLVMFunctionInfo(
420 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000421 /*chainCall=*/false, argTys, einfo, {}, required);
422}
423
424const CGFunctionInfo &
425CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType,
426 const CallArgList &args) {
427 auto argTypes = getArgTypesForCall(Context, args);
428 FunctionType::ExtInfo einfo;
429
430 return arrangeLLVMFunctionInfo(
431 GetReturnType(returnType), /*instanceMethod=*/false,
432 /*chainCall=*/false, argTypes, einfo, {}, RequiredArgs::All);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000433}
434
John McCalla729c622012-02-17 03:33:10 +0000435const CGFunctionInfo &
436CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000437 // FIXME: Do we need to handle ObjCMethodDecl?
438 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000439
Anders Carlsson6710c532010-02-06 02:44:09 +0000440 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000441 return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
Anders Carlsson6710c532010-02-06 02:44:09 +0000442
443 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000444 return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000445
John McCalla729c622012-02-17 03:33:10 +0000446 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000447}
448
Reid Klecknerc3473512014-08-29 21:43:29 +0000449/// Arrange a thunk that takes 'this' as the first parameter followed by
450/// varargs. Return a void pointer, regardless of the actual return type.
451/// The body of the thunk will end in a musttail call to a function of the
452/// correct type, and the caller will bitcast the function to the correct
453/// prototype.
454const CGFunctionInfo &
455CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) {
456 assert(MD->isVirtual() && "only virtual memptrs have thunks");
457 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
458 CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
Peter Collingbournef7706832014-12-12 23:41:25 +0000459 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
460 /*chainCall=*/false, ArgTys,
John McCallc56a8b32016-03-11 04:30:31 +0000461 FTP->getExtInfo(), {}, RequiredArgs(1));
Reid Klecknerc3473512014-08-29 21:43:29 +0000462}
463
David Majnemerdfa6d202015-03-11 18:36:39 +0000464const CGFunctionInfo &
David Majnemer37fd66e2015-03-13 22:36:55 +0000465CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
466 CXXCtorType CT) {
467 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
468
David Majnemerdfa6d202015-03-11 18:36:39 +0000469 CanQual<FunctionProtoType> FTP = GetFormalType(CD);
470 SmallVector<CanQualType, 2> ArgTys;
471 const CXXRecordDecl *RD = CD->getParent();
472 ArgTys.push_back(GetThisType(Context, RD));
David Majnemer37fd66e2015-03-13 22:36:55 +0000473 if (CT == Ctor_CopyingClosure)
474 ArgTys.push_back(*FTP->param_type_begin());
David Majnemerdfa6d202015-03-11 18:36:39 +0000475 if (RD->getNumVBases() > 0)
476 ArgTys.push_back(Context.IntTy);
477 CallingConv CC = Context.getDefaultCallingConvention(
478 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
479 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
480 /*chainCall=*/false, ArgTys,
John McCallc56a8b32016-03-11 04:30:31 +0000481 FunctionType::ExtInfo(CC), {},
482 RequiredArgs::All);
David Majnemerdfa6d202015-03-11 18:36:39 +0000483}
484
John McCallc818bbb2012-12-07 07:03:17 +0000485/// Arrange a call as unto a free function, except possibly with an
486/// additional number of formal parameters considered required.
487static const CGFunctionInfo &
488arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000489 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000490 const CallArgList &args,
491 const FunctionType *fnType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000492 unsigned numExtraRequiredArgs,
493 bool chainCall) {
John McCallc818bbb2012-12-07 07:03:17 +0000494 assert(args.size() >= numExtraRequiredArgs);
495
John McCallc56a8b32016-03-11 04:30:31 +0000496 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
497
John McCallc818bbb2012-12-07 07:03:17 +0000498 // In most cases, there are no optional arguments.
499 RequiredArgs required = RequiredArgs::All;
500
501 // If we have a variadic prototype, the required arguments are the
502 // extra prefix plus the arguments in the prototype.
503 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
504 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000505 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000506
John McCallc56a8b32016-03-11 04:30:31 +0000507 if (proto->hasExtParameterInfos())
508 addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
509 args.size());
510
John McCallc818bbb2012-12-07 07:03:17 +0000511 // If we don't have a prototype at all, but we're supposed to
512 // explicitly use the variadic convention for unprototyped calls,
513 // treat all of the arguments as required but preserve the nominal
514 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000515 } else if (CGM.getTargetCodeGenInfo()
516 .isNoProtoCallVariadic(args,
517 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000518 required = RequiredArgs(args.size());
519 }
520
Peter Collingbournef7706832014-12-12 23:41:25 +0000521 // FIXME: Kill copy.
522 SmallVector<CanQualType, 16> argTypes;
523 for (const auto &arg : args)
524 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
525 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
526 /*instanceMethod=*/false, chainCall,
John McCallc56a8b32016-03-11 04:30:31 +0000527 argTypes, fnType->getExtInfo(), paramInfos,
528 required);
John McCallc818bbb2012-12-07 07:03:17 +0000529}
530
John McCalla729c622012-02-17 03:33:10 +0000531/// Figure out the rules for calling a function with the given formal
532/// type using the given arguments. The arguments are necessary
533/// because the function might be unprototyped, in which case it's
534/// target-dependent in crazy ways.
535const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000536CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
Peter Collingbournef7706832014-12-12 23:41:25 +0000537 const FunctionType *fnType,
538 bool chainCall) {
539 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
540 chainCall ? 1 : 0, chainCall);
John McCallc818bbb2012-12-07 07:03:17 +0000541}
John McCalla729c622012-02-17 03:33:10 +0000542
John McCallc56a8b32016-03-11 04:30:31 +0000543/// A block function is essentially a free function with an
John McCallc818bbb2012-12-07 07:03:17 +0000544/// extra implicit argument.
545const CGFunctionInfo &
546CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
547 const FunctionType *fnType) {
Peter Collingbournef7706832014-12-12 23:41:25 +0000548 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
549 /*chainCall=*/false);
John McCalla729c622012-02-17 03:33:10 +0000550}
551
552const CGFunctionInfo &
John McCallc56a8b32016-03-11 04:30:31 +0000553CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto,
554 const FunctionArgList &params) {
555 auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
556 auto argTypes = getArgTypesForDeclaration(Context, params);
557
558 return arrangeLLVMFunctionInfo(GetReturnType(proto->getReturnType()),
559 /*instanceMethod*/ false, /*chainCall*/ false,
560 argTypes, proto->getExtInfo(), paramInfos,
561 RequiredArgs::forPrototypePlus(proto, 1));
562}
563
564const CGFunctionInfo &
565CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType,
566 const CallArgList &args) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000567 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000568 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000569 for (const auto &Arg : args)
570 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Peter Collingbournef7706832014-12-12 23:41:25 +0000571 return arrangeLLVMFunctionInfo(
572 GetReturnType(resultType), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000573 /*chainCall=*/false, argTypes, FunctionType::ExtInfo(),
574 /*paramInfos=*/ {}, RequiredArgs::All);
John McCall8dda7b22012-07-07 06:41:13 +0000575}
576
John McCallc56a8b32016-03-11 04:30:31 +0000577const CGFunctionInfo &
578CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType,
579 const FunctionArgList &args) {
580 auto argTypes = getArgTypesForDeclaration(Context, args);
581
582 return arrangeLLVMFunctionInfo(
583 GetReturnType(resultType), /*instanceMethod=*/false, /*chainCall=*/false,
584 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
585}
586
587const CGFunctionInfo &
588CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType,
589 ArrayRef<CanQualType> argTypes) {
590 return arrangeLLVMFunctionInfo(
591 resultType, /*instanceMethod=*/false, /*chainCall=*/false,
592 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
593}
594
John McCall8dda7b22012-07-07 06:41:13 +0000595/// Arrange a call to a C++ method, passing the given arguments.
596const CGFunctionInfo &
597CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
John McCallc56a8b32016-03-11 04:30:31 +0000598 const FunctionProtoType *proto,
John McCall8dda7b22012-07-07 06:41:13 +0000599 RequiredArgs required) {
John McCallc56a8b32016-03-11 04:30:31 +0000600 unsigned numRequiredArgs =
601 (proto->isVariadic() ? required.getNumRequiredArgs() : args.size());
602 unsigned numPrefixArgs = numRequiredArgs - proto->getNumParams();
603 auto paramInfos =
604 getExtParameterInfosForCall(proto, numPrefixArgs, args.size());
605
John McCall8dda7b22012-07-07 06:41:13 +0000606 // FIXME: Kill copy.
John McCallc56a8b32016-03-11 04:30:31 +0000607 auto argTypes = getArgTypesForCall(Context, args);
John McCall8dda7b22012-07-07 06:41:13 +0000608
John McCallc56a8b32016-03-11 04:30:31 +0000609 FunctionType::ExtInfo info = proto->getExtInfo();
Peter Collingbournef7706832014-12-12 23:41:25 +0000610 return arrangeLLVMFunctionInfo(
John McCallc56a8b32016-03-11 04:30:31 +0000611 GetReturnType(proto->getReturnType()), /*instanceMethod=*/true,
612 /*chainCall=*/false, argTypes, info, paramInfos, required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000613}
614
John McCalla729c622012-02-17 03:33:10 +0000615const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Peter Collingbournef7706832014-12-12 23:41:25 +0000616 return arrangeLLVMFunctionInfo(
617 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000618 None, FunctionType::ExtInfo(), {}, RequiredArgs::All);
619}
620
621const CGFunctionInfo &
622CodeGenTypes::arrangeCall(const CGFunctionInfo &signature,
623 const CallArgList &args) {
624 assert(signature.arg_size() <= args.size());
625 if (signature.arg_size() == args.size())
626 return signature;
627
628 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
629 auto sigParamInfos = signature.getExtParameterInfos();
630 if (!sigParamInfos.empty()) {
631 paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
632 paramInfos.resize(args.size());
633 }
634
635 auto argTypes = getArgTypesForCall(Context, args);
636
637 assert(signature.getRequiredArgs().allowsOptionalArgs());
638 return arrangeLLVMFunctionInfo(signature.getReturnType(),
639 signature.isInstanceMethod(),
640 signature.isChainCall(),
641 argTypes,
642 signature.getExtInfo(),
643 paramInfos,
644 signature.getRequiredArgs());
John McCalla738c252011-03-09 04:27:21 +0000645}
646
John McCalla729c622012-02-17 03:33:10 +0000647/// Arrange the argument and result information for an abstract value
648/// of a given function type. This is the method which all of the
649/// above functions ultimately defer to.
650const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000651CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000652 bool instanceMethod,
653 bool chainCall,
John McCall8dda7b22012-07-07 06:41:13 +0000654 ArrayRef<CanQualType> argTypes,
655 FunctionType::ExtInfo info,
John McCallc56a8b32016-03-11 04:30:31 +0000656 ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
John McCall8dda7b22012-07-07 06:41:13 +0000657 RequiredArgs required) {
Saleem Abdulrasool32d1a962014-11-25 03:49:50 +0000658 assert(std::all_of(argTypes.begin(), argTypes.end(),
659 std::mem_fun_ref(&CanQualType::isCanonicalAsParam)));
John McCall2da83a32010-02-26 00:48:12 +0000660
Daniel Dunbare0be8292009-02-03 00:07:12 +0000661 // Lookup or create unique function info.
662 llvm::FoldingSetNodeID ID;
John McCallc56a8b32016-03-11 04:30:31 +0000663 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos,
664 required, resultType, argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000665
Craig Topper8a13c412014-05-21 05:09:00 +0000666 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000667 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000668 if (FI)
669 return *FI;
670
John McCallc56a8b32016-03-11 04:30:31 +0000671 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
672
John McCalla729c622012-02-17 03:33:10 +0000673 // Construct the function info. We co-allocate the ArgInfos.
Peter Collingbournef7706832014-12-12 23:41:25 +0000674 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
John McCallc56a8b32016-03-11 04:30:31 +0000675 paramInfos, resultType, argTypes, required);
John McCalla729c622012-02-17 03:33:10 +0000676 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000677
David Blaikie82e95a32014-11-19 07:49:47 +0000678 bool inserted = FunctionsBeingProcessed.insert(FI).second;
679 (void)inserted;
John McCalla729c622012-02-17 03:33:10 +0000680 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000681
Daniel Dunbar313321e2009-02-03 05:31:23 +0000682 // Compute ABI information.
John McCall12f23522016-04-04 18:33:08 +0000683 if (info.getCC() != CC_Swift) {
684 getABIInfo().computeInfo(*FI);
685 } else {
686 swiftcall::computeABIInfo(CGM, *FI);
687 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000688
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000689 // Loop over all of the computed argument and return value info. If any of
690 // them are direct or extend without a specified coerce type, specify the
691 // default now.
John McCalla729c622012-02-17 03:33:10 +0000692 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000693 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000694 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000695
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000696 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000697 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000698 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000699
John McCalla729c622012-02-17 03:33:10 +0000700 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
701 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000702
Daniel Dunbare0be8292009-02-03 00:07:12 +0000703 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000704}
705
John McCalla729c622012-02-17 03:33:10 +0000706CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Peter Collingbournef7706832014-12-12 23:41:25 +0000707 bool instanceMethod,
708 bool chainCall,
John McCalla729c622012-02-17 03:33:10 +0000709 const FunctionType::ExtInfo &info,
John McCallc56a8b32016-03-11 04:30:31 +0000710 ArrayRef<ExtParameterInfo> paramInfos,
John McCalla729c622012-02-17 03:33:10 +0000711 CanQualType resultType,
712 ArrayRef<CanQualType> argTypes,
713 RequiredArgs required) {
John McCallc56a8b32016-03-11 04:30:31 +0000714 assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
715
716 void *buffer =
717 operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
718 argTypes.size() + 1, paramInfos.size()));
719
John McCalla729c622012-02-17 03:33:10 +0000720 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
721 FI->CallingConvention = llvmCC;
722 FI->EffectiveCallingConvention = llvmCC;
723 FI->ASTCallingConvention = info.getCC();
Peter Collingbournef7706832014-12-12 23:41:25 +0000724 FI->InstanceMethod = instanceMethod;
725 FI->ChainCall = chainCall;
John McCalla729c622012-02-17 03:33:10 +0000726 FI->NoReturn = info.getNoReturn();
727 FI->ReturnsRetained = info.getProducesResult();
728 FI->Required = required;
729 FI->HasRegParm = info.getHasRegParm();
730 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000731 FI->ArgStruct = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +0000732 FI->ArgStructAlign = 0;
John McCalla729c622012-02-17 03:33:10 +0000733 FI->NumArgs = argTypes.size();
John McCallc56a8b32016-03-11 04:30:31 +0000734 FI->HasExtParameterInfos = !paramInfos.empty();
John McCalla729c622012-02-17 03:33:10 +0000735 FI->getArgsBuffer()[0].type = resultType;
736 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
737 FI->getArgsBuffer()[i + 1].type = argTypes[i];
John McCallc56a8b32016-03-11 04:30:31 +0000738 for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
739 FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
John McCalla729c622012-02-17 03:33:10 +0000740 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000741}
742
743/***/
744
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000745namespace {
746// ABIArgInfo::Expand implementation.
747
748// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
749struct TypeExpansion {
750 enum TypeExpansionKind {
751 // Elements of constant arrays are expanded recursively.
752 TEK_ConstantArray,
753 // Record fields are expanded recursively (but if record is a union, only
754 // the field with the largest size is expanded).
755 TEK_Record,
756 // For complex types, real and imaginary parts are expanded recursively.
757 TEK_Complex,
758 // All other types are not expandable.
759 TEK_None
760 };
761
762 const TypeExpansionKind Kind;
763
764 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000765 virtual ~TypeExpansion() {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000766};
767
768struct ConstantArrayExpansion : TypeExpansion {
769 QualType EltTy;
770 uint64_t NumElts;
771
772 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
773 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
774 static bool classof(const TypeExpansion *TE) {
775 return TE->Kind == TEK_ConstantArray;
776 }
777};
778
779struct RecordExpansion : TypeExpansion {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000780 SmallVector<const CXXBaseSpecifier *, 1> Bases;
781
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000782 SmallVector<const FieldDecl *, 1> Fields;
783
Reid Klecknere9f6a712014-10-31 17:10:41 +0000784 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
785 SmallVector<const FieldDecl *, 1> &&Fields)
Benjamin Kramer0bb97742016-02-13 16:00:13 +0000786 : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
787 Fields(std::move(Fields)) {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000788 static bool classof(const TypeExpansion *TE) {
789 return TE->Kind == TEK_Record;
790 }
791};
792
793struct ComplexExpansion : TypeExpansion {
794 QualType EltTy;
795
796 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
797 static bool classof(const TypeExpansion *TE) {
798 return TE->Kind == TEK_Complex;
799 }
800};
801
802struct NoExpansion : TypeExpansion {
803 NoExpansion() : TypeExpansion(TEK_None) {}
804 static bool classof(const TypeExpansion *TE) {
805 return TE->Kind == TEK_None;
806 }
807};
808} // namespace
809
810static std::unique_ptr<TypeExpansion>
811getTypeExpansion(QualType Ty, const ASTContext &Context) {
812 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
813 return llvm::make_unique<ConstantArrayExpansion>(
814 AT->getElementType(), AT->getSize().getZExtValue());
815 }
816 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000817 SmallVector<const CXXBaseSpecifier *, 1> Bases;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000818 SmallVector<const FieldDecl *, 1> Fields;
Bob Wilsone826a2a2011-08-03 05:58:22 +0000819 const RecordDecl *RD = RT->getDecl();
820 assert(!RD->hasFlexibleArrayMember() &&
821 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000822 if (RD->isUnion()) {
823 // Unions can be here only in degenerative cases - all the fields are same
824 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000825 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000826 CharUnits UnionSize = CharUnits::Zero();
827
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000828 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000829 // Skip zero length bitfields.
830 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
831 continue;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000832 assert(!FD->isBitField() &&
833 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000834 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000835 if (UnionSize < FieldSize) {
836 UnionSize = FieldSize;
837 LargestFD = FD;
838 }
839 }
840 if (LargestFD)
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000841 Fields.push_back(LargestFD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000842 } else {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000843 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
844 assert(!CXXRD->isDynamicClass() &&
845 "cannot expand vtable pointers in dynamic classes");
846 for (const CXXBaseSpecifier &BS : CXXRD->bases())
847 Bases.push_back(&BS);
848 }
849
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000850 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000851 // Skip zero length bitfields.
852 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
853 continue;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000854 assert(!FD->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000855 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000856 Fields.push_back(FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000857 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000858 }
Reid Klecknere9f6a712014-10-31 17:10:41 +0000859 return llvm::make_unique<RecordExpansion>(std::move(Bases),
860 std::move(Fields));
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000861 }
862 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
863 return llvm::make_unique<ComplexExpansion>(CT->getElementType());
864 }
865 return llvm::make_unique<NoExpansion>();
866}
867
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000868static int getExpansionSize(QualType Ty, const ASTContext &Context) {
869 auto Exp = getTypeExpansion(Ty, Context);
870 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
871 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
872 }
873 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
874 int Res = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +0000875 for (auto BS : RExp->Bases)
876 Res += getExpansionSize(BS->getType(), Context);
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000877 for (auto FD : RExp->Fields)
878 Res += getExpansionSize(FD->getType(), Context);
879 return Res;
880 }
881 if (isa<ComplexExpansion>(Exp.get()))
882 return 2;
883 assert(isa<NoExpansion>(Exp.get()));
884 return 1;
885}
886
Alexey Samsonov153004f2014-09-29 22:08:00 +0000887void
888CodeGenTypes::getExpandedTypes(QualType Ty,
889 SmallVectorImpl<llvm::Type *>::iterator &TI) {
890 auto Exp = getTypeExpansion(Ty, Context);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000891 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
892 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
Alexey Samsonov153004f2014-09-29 22:08:00 +0000893 getExpandedTypes(CAExp->EltTy, TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000894 }
895 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000896 for (auto BS : RExp->Bases)
897 getExpandedTypes(BS->getType(), TI);
898 for (auto FD : RExp->Fields)
Alexey Samsonov153004f2014-09-29 22:08:00 +0000899 getExpandedTypes(FD->getType(), TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000900 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
901 llvm::Type *EltTy = ConvertType(CExp->EltTy);
Alexey Samsonov153004f2014-09-29 22:08:00 +0000902 *TI++ = EltTy;
903 *TI++ = EltTy;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000904 } else {
905 assert(isa<NoExpansion>(Exp.get()));
Alexey Samsonov153004f2014-09-29 22:08:00 +0000906 *TI++ = ConvertType(Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000907 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000908}
909
John McCall7f416cc2015-09-08 08:05:57 +0000910static void forConstantArrayExpansion(CodeGenFunction &CGF,
911 ConstantArrayExpansion *CAE,
912 Address BaseAddr,
913 llvm::function_ref<void(Address)> Fn) {
914 CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
915 CharUnits EltAlign =
916 BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
917
918 for (int i = 0, n = CAE->NumElts; i < n; i++) {
919 llvm::Value *EltAddr =
920 CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i);
921 Fn(Address(EltAddr, EltAlign));
922 }
923}
924
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000925void CodeGenFunction::ExpandTypeFromArgs(
John McCall12f23522016-04-04 18:33:08 +0000926 QualType Ty, LValue LV, SmallVectorImpl<llvm::Value *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000927 assert(LV.isSimple() &&
928 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000929
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000930 auto Exp = getTypeExpansion(Ty, getContext());
931 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000932 forConstantArrayExpansion(*this, CAExp, LV.getAddress(),
933 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000934 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
935 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
John McCall7f416cc2015-09-08 08:05:57 +0000936 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000937 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000938 Address This = LV.getAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +0000939 for (const CXXBaseSpecifier *BS : RExp->Bases) {
940 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +0000941 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +0000942 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
943 /*NullCheckValue=*/false, SourceLocation());
944 LValue SubLV = MakeAddrLValue(Base, BS->getType());
945
946 // Recurse onto bases.
947 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
948 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000949 for (auto FD : RExp->Fields) {
950 // FIXME: What are the right qualifiers here?
951 LValue SubLV = EmitLValueForField(LV, FD);
952 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000953 }
John McCall7f416cc2015-09-08 08:05:57 +0000954 } else if (isa<ComplexExpansion>(Exp.get())) {
955 auto realValue = *AI++;
956 auto imagValue = *AI++;
957 EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000958 } else {
959 assert(isa<NoExpansion>(Exp.get()));
960 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000961 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000962}
963
964void CodeGenFunction::ExpandTypeToArgs(
965 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
966 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
967 auto Exp = getTypeExpansion(Ty, getContext());
968 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000969 forConstantArrayExpansion(*this, CAExp, RV.getAggregateAddress(),
970 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000971 RValue EltRV =
972 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
973 ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
John McCall7f416cc2015-09-08 08:05:57 +0000974 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000975 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000976 Address This = RV.getAggregateAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +0000977 for (const CXXBaseSpecifier *BS : RExp->Bases) {
978 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +0000979 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +0000980 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
981 /*NullCheckValue=*/false, SourceLocation());
982 RValue BaseRV = RValue::getAggregate(Base);
983
984 // Recurse onto bases.
985 ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
986 IRCallArgPos);
987 }
988
989 LValue LV = MakeAddrLValue(This, Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000990 for (auto FD : RExp->Fields) {
991 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
992 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
993 IRCallArgPos);
994 }
995 } else if (isa<ComplexExpansion>(Exp.get())) {
996 ComplexPairTy CV = RV.getComplexVal();
997 IRCallArgs[IRCallArgPos++] = CV.first;
998 IRCallArgs[IRCallArgPos++] = CV.second;
999 } else {
1000 assert(isa<NoExpansion>(Exp.get()));
1001 assert(RV.isScalar() &&
1002 "Unexpected non-scalar rvalue during struct expansion.");
1003
1004 // Insert a bitcast as needed.
1005 llvm::Value *V = RV.getScalarVal();
1006 if (IRCallArgPos < IRFuncTy->getNumParams() &&
1007 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
1008 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
1009
1010 IRCallArgs[IRCallArgPos++] = V;
1011 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001012}
1013
John McCall7f416cc2015-09-08 08:05:57 +00001014/// Create a temporary allocation for the purposes of coercion.
1015static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
1016 CharUnits MinAlign) {
1017 // Don't use an alignment that's worse than what LLVM would prefer.
1018 auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty);
1019 CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
1020
1021 return CGF.CreateTempAlloca(Ty, Align);
1022}
1023
Chris Lattner895c52b2010-06-27 06:04:18 +00001024/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +00001025/// accessing some number of bytes out of it, try to gep into the struct to get
1026/// at its inner goodness. Dive as deep as possible without entering an element
1027/// with an in-memory size smaller than DstSize.
John McCall7f416cc2015-09-08 08:05:57 +00001028static Address
1029EnterStructPointerForCoercedAccess(Address SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +00001030 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +00001031 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +00001032 // We can't dive into a zero-element struct.
1033 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001034
Chris Lattner2192fe52011-07-18 04:24:23 +00001035 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001036
Chris Lattner1cd66982010-06-27 05:56:15 +00001037 // If the first elt is at least as large as what we're looking for, or if the
James Molloy90d61012014-08-29 10:17:52 +00001038 // first element is the same size as the whole struct, we can enter it. The
1039 // comparison must be made on the store size and not the alloca size. Using
1040 // the alloca size may overstate the size of the load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001041 uint64_t FirstEltSize =
James Molloy90d61012014-08-29 10:17:52 +00001042 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001043 if (FirstEltSize < DstSize &&
James Molloy90d61012014-08-29 10:17:52 +00001044 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +00001045 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001046
Chris Lattner1cd66982010-06-27 05:56:15 +00001047 // GEP into the first element.
John McCall7f416cc2015-09-08 08:05:57 +00001048 SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, CharUnits(), "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001049
Chris Lattner1cd66982010-06-27 05:56:15 +00001050 // If the first element is a struct, recurse.
John McCall7f416cc2015-09-08 08:05:57 +00001051 llvm::Type *SrcTy = SrcPtr.getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001052 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +00001053 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +00001054
1055 return SrcPtr;
1056}
1057
Chris Lattner055097f2010-06-27 06:26:04 +00001058/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
1059/// are either integers or pointers. This does a truncation of the value if it
1060/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001061///
1062/// This behaves as if the value were coerced through memory, so on big-endian
1063/// targets the high bits are preserved in a truncation, while little-endian
1064/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +00001065static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +00001066 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +00001067 CodeGenFunction &CGF) {
1068 if (Val->getType() == Ty)
1069 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001070
Chris Lattner055097f2010-06-27 06:26:04 +00001071 if (isa<llvm::PointerType>(Val->getType())) {
1072 // If this is Pointer->Pointer avoid conversion to and from int.
1073 if (isa<llvm::PointerType>(Ty))
1074 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001075
Chris Lattner055097f2010-06-27 06:26:04 +00001076 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +00001077 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +00001078 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001079
Chris Lattner2192fe52011-07-18 04:24:23 +00001080 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +00001081 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +00001082 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001083
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001084 if (Val->getType() != DestIntTy) {
1085 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
1086 if (DL.isBigEndian()) {
1087 // Preserve the high bits on big-endian targets.
1088 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +00001089 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
1090 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
1091
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001092 if (SrcSize > DstSize) {
1093 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
1094 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
1095 } else {
1096 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
1097 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
1098 }
1099 } else {
1100 // Little-endian targets preserve the low bits. No shifts required.
1101 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
1102 }
1103 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001104
Chris Lattner055097f2010-06-27 06:26:04 +00001105 if (isa<llvm::PointerType>(Ty))
1106 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
1107 return Val;
1108}
1109
Chris Lattner1cd66982010-06-27 05:56:15 +00001110
1111
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001112/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001113/// a pointer to an object of type \arg Ty, known to be aligned to
1114/// \arg SrcAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001115///
1116/// This safely handles the case when the src type is smaller than the
1117/// destination type; in this situation the values of bits which not
1118/// present in the src are undefined.
John McCall7f416cc2015-09-08 08:05:57 +00001119static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001120 CodeGenFunction &CGF) {
John McCall7f416cc2015-09-08 08:05:57 +00001121 llvm::Type *SrcTy = Src.getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001122
Chris Lattnerd200eda2010-06-28 22:51:39 +00001123 // If SrcTy and Ty are the same, just do a load.
1124 if (SrcTy == Ty)
John McCall7f416cc2015-09-08 08:05:57 +00001125 return CGF.Builder.CreateLoad(Src);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001126
Micah Villmowdd31ca12012-10-08 16:25:52 +00001127 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001128
Chris Lattner2192fe52011-07-18 04:24:23 +00001129 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001130 Src = EnterStructPointerForCoercedAccess(Src, SrcSTy, DstSize, CGF);
1131 SrcTy = Src.getType()->getElementType();
Chris Lattner1cd66982010-06-27 05:56:15 +00001132 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001133
Micah Villmowdd31ca12012-10-08 16:25:52 +00001134 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001135
Chris Lattner055097f2010-06-27 06:26:04 +00001136 // If the source and destination are integer or pointer types, just do an
1137 // extension or truncation to the desired type.
1138 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
1139 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
John McCall7f416cc2015-09-08 08:05:57 +00001140 llvm::Value *Load = CGF.Builder.CreateLoad(Src);
Chris Lattner055097f2010-06-27 06:26:04 +00001141 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
1142 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001143
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001144 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +00001145 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +00001146 // Generally SrcSize is never greater than DstSize, since this means we are
1147 // losing bits. However, this can happen in cases where the structure has
1148 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +00001149 //
Mike Stump18bb9282009-05-16 07:57:57 +00001150 // FIXME: Assert that we aren't truncating non-padding bits when have access
1151 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001152 Src = CGF.Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(Ty));
1153 return CGF.Builder.CreateLoad(Src);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001154 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001155
John McCall7f416cc2015-09-08 08:05:57 +00001156 // Otherwise do coercion through memory. This is stupid, but simple.
1157 Address Tmp = CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment());
1158 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1159 Address SrcCasted = CGF.Builder.CreateBitCast(Src, CGF.Int8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001160 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
1161 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
John McCall7f416cc2015-09-08 08:05:57 +00001162 false);
1163 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001164}
1165
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001166// Function to store a first-class aggregate into memory. We prefer to
1167// store the elements rather than the aggregate to be more friendly to
1168// fast-isel.
1169// FIXME: Do we need to recurse here?
1170static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
John McCall7f416cc2015-09-08 08:05:57 +00001171 Address Dest, bool DestIsVolatile) {
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001172 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +00001173 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001174 dyn_cast<llvm::StructType>(Val->getType())) {
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001175 const llvm::StructLayout *Layout =
1176 CGF.CGM.getDataLayout().getStructLayout(STy);
1177
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001178 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00001179 auto EltOffset = CharUnits::fromQuantity(Layout->getElementOffset(i));
1180 Address EltPtr = CGF.Builder.CreateStructGEP(Dest, i, EltOffset);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001181 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
John McCall7f416cc2015-09-08 08:05:57 +00001182 CGF.Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001183 }
1184 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001185 CGF.Builder.CreateStore(Val, Dest, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001186 }
1187}
1188
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001189/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001190/// where the source and destination may have different types. The
1191/// destination is known to be aligned to \arg DstAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001192///
1193/// This safely handles the case when the src type is larger than the
1194/// destination type; the upper bits of the src will be lost.
1195static void CreateCoercedStore(llvm::Value *Src,
John McCall7f416cc2015-09-08 08:05:57 +00001196 Address Dst,
Anders Carlsson17490832009-12-24 20:40:36 +00001197 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001198 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001199 llvm::Type *SrcTy = Src->getType();
John McCall7f416cc2015-09-08 08:05:57 +00001200 llvm::Type *DstTy = Dst.getType()->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +00001201 if (SrcTy == DstTy) {
John McCall7f416cc2015-09-08 08:05:57 +00001202 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattnerd200eda2010-06-28 22:51:39 +00001203 return;
1204 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001205
Micah Villmowdd31ca12012-10-08 16:25:52 +00001206 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001207
Chris Lattner2192fe52011-07-18 04:24:23 +00001208 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001209 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy, SrcSize, CGF);
1210 DstTy = Dst.getType()->getElementType();
Chris Lattner895c52b2010-06-27 06:04:18 +00001211 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001212
Chris Lattner055097f2010-06-27 06:26:04 +00001213 // If the source and destination are integer or pointer types, just do an
1214 // extension or truncation to the desired type.
1215 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1216 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1217 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
John McCall7f416cc2015-09-08 08:05:57 +00001218 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattner055097f2010-06-27 06:26:04 +00001219 return;
1220 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001221
Micah Villmowdd31ca12012-10-08 16:25:52 +00001222 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001223
Daniel Dunbar313321e2009-02-03 05:31:23 +00001224 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001225 if (SrcSize <= DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00001226 Dst = CGF.Builder.CreateBitCast(Dst, llvm::PointerType::getUnqual(SrcTy));
1227 BuildAggStore(CGF, Src, Dst, DstIsVolatile);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001228 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001229 // Otherwise do coercion through memory. This is stupid, but
1230 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001231
1232 // Generally SrcSize is never greater than DstSize, since this means we are
1233 // losing bits. However, this can happen in cases where the structure has
1234 // additional padding, for example due to a user specified alignment.
1235 //
1236 // FIXME: Assert that we aren't truncating non-padding bits when have access
1237 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001238 Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
1239 CGF.Builder.CreateStore(Src, Tmp);
1240 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1241 Address DstCasted = CGF.Builder.CreateBitCast(Dst, CGF.Int8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001242 CGF.Builder.CreateMemCpy(DstCasted, Casted,
1243 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
John McCall7f416cc2015-09-08 08:05:57 +00001244 false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001245 }
1246}
1247
John McCall7f416cc2015-09-08 08:05:57 +00001248static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
1249 const ABIArgInfo &info) {
1250 if (unsigned offset = info.getDirectOffset()) {
1251 addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
1252 addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
1253 CharUnits::fromQuantity(offset));
1254 addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
1255 }
1256 return addr;
1257}
1258
Alexey Samsonov153004f2014-09-29 22:08:00 +00001259namespace {
1260
1261/// Encapsulates information about the way function arguments from
1262/// CGFunctionInfo should be passed to actual LLVM IR function.
1263class ClangToLLVMArgMapping {
1264 static const unsigned InvalidIndex = ~0U;
1265 unsigned InallocaArgNo;
1266 unsigned SRetArgNo;
1267 unsigned TotalIRArgs;
1268
1269 /// Arguments of LLVM IR function corresponding to single Clang argument.
1270 struct IRArgs {
1271 unsigned PaddingArgIndex;
1272 // Argument is expanded to IR arguments at positions
1273 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1274 unsigned FirstArgIndex;
1275 unsigned NumberOfArgs;
1276
1277 IRArgs()
1278 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1279 NumberOfArgs(0) {}
1280 };
1281
1282 SmallVector<IRArgs, 8> ArgInfo;
1283
1284public:
1285 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1286 bool OnlyRequiredArgs = false)
1287 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1288 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1289 construct(Context, FI, OnlyRequiredArgs);
1290 }
1291
1292 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1293 unsigned getInallocaArgNo() const {
1294 assert(hasInallocaArg());
1295 return InallocaArgNo;
1296 }
1297
1298 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1299 unsigned getSRetArgNo() const {
1300 assert(hasSRetArg());
1301 return SRetArgNo;
1302 }
1303
1304 unsigned totalIRArgs() const { return TotalIRArgs; }
1305
1306 bool hasPaddingArg(unsigned ArgNo) const {
1307 assert(ArgNo < ArgInfo.size());
1308 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1309 }
1310 unsigned getPaddingArgNo(unsigned ArgNo) const {
1311 assert(hasPaddingArg(ArgNo));
1312 return ArgInfo[ArgNo].PaddingArgIndex;
1313 }
1314
1315 /// Returns index of first IR argument corresponding to ArgNo, and their
1316 /// quantity.
1317 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1318 assert(ArgNo < ArgInfo.size());
1319 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1320 ArgInfo[ArgNo].NumberOfArgs);
1321 }
1322
1323private:
1324 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1325 bool OnlyRequiredArgs);
1326};
1327
1328void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1329 const CGFunctionInfo &FI,
1330 bool OnlyRequiredArgs) {
1331 unsigned IRArgNo = 0;
1332 bool SwapThisWithSRet = false;
1333 const ABIArgInfo &RetAI = FI.getReturnInfo();
1334
1335 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1336 SwapThisWithSRet = RetAI.isSRetAfterThis();
1337 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1338 }
1339
1340 unsigned ArgNo = 0;
1341 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1342 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1343 ++I, ++ArgNo) {
1344 assert(I != FI.arg_end());
1345 QualType ArgType = I->type;
1346 const ABIArgInfo &AI = I->info;
1347 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1348 auto &IRArgs = ArgInfo[ArgNo];
1349
1350 if (AI.getPaddingType())
1351 IRArgs.PaddingArgIndex = IRArgNo++;
1352
1353 switch (AI.getKind()) {
1354 case ABIArgInfo::Extend:
1355 case ABIArgInfo::Direct: {
1356 // FIXME: handle sseregparm someday...
1357 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1358 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1359 IRArgs.NumberOfArgs = STy->getNumElements();
1360 } else {
1361 IRArgs.NumberOfArgs = 1;
1362 }
1363 break;
1364 }
1365 case ABIArgInfo::Indirect:
1366 IRArgs.NumberOfArgs = 1;
1367 break;
1368 case ABIArgInfo::Ignore:
1369 case ABIArgInfo::InAlloca:
1370 // ignore and inalloca doesn't have matching LLVM parameters.
1371 IRArgs.NumberOfArgs = 0;
1372 break;
John McCallf26e73d2016-03-11 04:30:43 +00001373 case ABIArgInfo::CoerceAndExpand:
1374 IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
1375 break;
1376 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001377 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1378 break;
1379 }
Alexey Samsonov153004f2014-09-29 22:08:00 +00001380
1381 if (IRArgs.NumberOfArgs > 0) {
1382 IRArgs.FirstArgIndex = IRArgNo;
1383 IRArgNo += IRArgs.NumberOfArgs;
1384 }
1385
1386 // Skip over the sret parameter when it comes second. We already handled it
1387 // above.
1388 if (IRArgNo == 1 && SwapThisWithSRet)
1389 IRArgNo++;
1390 }
1391 assert(ArgNo == ArgInfo.size());
1392
1393 if (FI.usesInAlloca())
1394 InallocaArgNo = IRArgNo++;
1395
1396 TotalIRArgs = IRArgNo;
1397}
1398} // namespace
1399
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001400/***/
1401
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001402bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001403 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00001404}
1405
Tim Northovere77cc392014-03-29 13:28:05 +00001406bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1407 return ReturnTypeUsesSRet(FI) &&
1408 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1409}
1410
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001411bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1412 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1413 switch (BT->getKind()) {
1414 default:
1415 return false;
1416 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +00001417 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001418 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +00001419 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001420 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +00001421 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001422 }
1423 }
1424
1425 return false;
1426}
1427
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001428bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1429 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1430 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1431 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +00001432 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001433 }
1434 }
1435
1436 return false;
1437}
1438
Chris Lattnera5f58b02011-07-09 17:41:47 +00001439llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +00001440 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1441 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +00001442}
1443
Chris Lattnera5f58b02011-07-09 17:41:47 +00001444llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +00001445CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001446
David Blaikie82e95a32014-11-19 07:49:47 +00001447 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1448 (void)Inserted;
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001449 assert(Inserted && "Recursively being processed?");
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001450
Alexey Samsonov153004f2014-09-29 22:08:00 +00001451 llvm::Type *resultType = nullptr;
John McCall85dd2c52011-05-15 02:19:42 +00001452 const ABIArgInfo &retAI = FI.getReturnInfo();
1453 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +00001454 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +00001455 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +00001456
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001457 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001458 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +00001459 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +00001460 break;
1461
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001462 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001463 if (retAI.getInAllocaSRet()) {
1464 // sret things on win32 aren't void, they return the sret pointer.
1465 QualType ret = FI.getReturnType();
1466 llvm::Type *ty = ConvertType(ret);
1467 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1468 resultType = llvm::PointerType::get(ty, addressSpace);
1469 } else {
1470 resultType = llvm::Type::getVoidTy(getLLVMContext());
1471 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001472 break;
1473
John McCall7f416cc2015-09-08 08:05:57 +00001474 case ABIArgInfo::Indirect:
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001475 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +00001476 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001477 break;
John McCallf26e73d2016-03-11 04:30:43 +00001478
1479 case ABIArgInfo::CoerceAndExpand:
1480 resultType = retAI.getUnpaddedCoerceAndExpandType();
1481 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001482 }
Mike Stump11289f42009-09-09 15:08:12 +00001483
Alexey Samsonov153004f2014-09-29 22:08:00 +00001484 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1485 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1486
1487 // Add type for sret argument.
1488 if (IRFunctionArgs.hasSRetArg()) {
1489 QualType Ret = FI.getReturnType();
1490 llvm::Type *Ty = ConvertType(Ret);
1491 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1492 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1493 llvm::PointerType::get(Ty, AddressSpace);
1494 }
1495
1496 // Add type for inalloca argument.
1497 if (IRFunctionArgs.hasInallocaArg()) {
1498 auto ArgStruct = FI.getArgStruct();
1499 assert(ArgStruct);
1500 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1501 }
1502
John McCallc818bbb2012-12-07 07:03:17 +00001503 // Add in all of the required arguments.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001504 unsigned ArgNo = 0;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00001505 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1506 ie = it + FI.getNumRequiredArgs();
Alexey Samsonov153004f2014-09-29 22:08:00 +00001507 for (; it != ie; ++it, ++ArgNo) {
1508 const ABIArgInfo &ArgInfo = it->info;
Mike Stump11289f42009-09-09 15:08:12 +00001509
Rafael Espindolafad28de2012-10-24 01:59:00 +00001510 // Insert a padding type to ensure proper alignment.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001511 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1512 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1513 ArgInfo.getPaddingType();
Rafael Espindolafad28de2012-10-24 01:59:00 +00001514
Alexey Samsonov153004f2014-09-29 22:08:00 +00001515 unsigned FirstIRArg, NumIRArgs;
1516 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1517
1518 switch (ArgInfo.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001519 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001520 case ABIArgInfo::InAlloca:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001521 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001522 break;
1523
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001524 case ABIArgInfo::Indirect: {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001525 assert(NumIRArgs == 1);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001526 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +00001527 llvm::Type *LTy = ConvertTypeForMem(it->type);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001528 ArgTypes[FirstIRArg] = LTy->getPointerTo();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001529 break;
1530 }
1531
1532 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +00001533 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001534 // Fast-isel and the optimizer generally like scalar values better than
1535 // FCAs, so we flatten them if this is safe to do for this argument.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001536 llvm::Type *argType = ArgInfo.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +00001537 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001538 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1539 assert(NumIRArgs == st->getNumElements());
John McCall85dd2c52011-05-15 02:19:42 +00001540 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
Alexey Samsonov153004f2014-09-29 22:08:00 +00001541 ArgTypes[FirstIRArg + i] = st->getElementType(i);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001542 } else {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001543 assert(NumIRArgs == 1);
1544 ArgTypes[FirstIRArg] = argType;
Chris Lattner3dd716c2010-06-28 23:44:11 +00001545 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001546 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001547 }
Mike Stump11289f42009-09-09 15:08:12 +00001548
John McCallf26e73d2016-03-11 04:30:43 +00001549 case ABIArgInfo::CoerceAndExpand: {
1550 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1551 for (auto EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
1552 *ArgTypesIter++ = EltTy;
1553 }
1554 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1555 break;
1556 }
1557
Daniel Dunbard3674e62008-09-11 01:48:57 +00001558 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001559 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1560 getExpandedTypes(it->type, ArgTypesIter);
1561 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001562 break;
1563 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001564 }
1565
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001566 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1567 assert(Erased && "Not in set?");
Alexey Samsonov153004f2014-09-29 22:08:00 +00001568
1569 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001570}
1571
Chris Lattner2192fe52011-07-18 04:24:23 +00001572llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001573 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001574 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001575
Chris Lattner8806e322011-07-10 00:18:59 +00001576 if (!isFuncTypeConvertible(FPT))
1577 return llvm::StructType::get(getLLVMContext());
1578
1579 const CGFunctionInfo *Info;
1580 if (isa<CXXDestructorDecl>(MD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001581 Info =
1582 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
Chris Lattner8806e322011-07-10 00:18:59 +00001583 else
John McCalla729c622012-02-17 03:33:10 +00001584 Info = &arrangeCXXMethodDeclaration(MD);
1585 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001586}
1587
Samuel Antao798f11c2015-11-23 22:04:44 +00001588static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
1589 llvm::AttrBuilder &FuncAttrs,
1590 const FunctionProtoType *FPT) {
1591 if (!FPT)
1592 return;
1593
1594 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
1595 FPT->isNothrow(Ctx))
1596 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1597}
1598
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00001599void CodeGenModule::ConstructAttributeList(
1600 StringRef Name, const CGFunctionInfo &FI, CGCalleeInfo CalleeInfo,
1601 AttributeListType &PAL, unsigned &CallingConv, bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001602 llvm::AttrBuilder FuncAttrs;
1603 llvm::AttrBuilder RetAttrs;
Paul Robinson08556952014-12-11 20:14:04 +00001604 bool HasOptnone = false;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001605
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001606 CallingConv = FI.getEffectiveCallingConvention();
1607
John McCallab26cfa2010-02-05 21:31:56 +00001608 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001609 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001610
Samuel Antao798f11c2015-11-23 22:04:44 +00001611 // If we have information about the function prototype, we can learn
1612 // attributes form there.
1613 AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
1614 CalleeInfo.getCalleeFunctionProtoType());
1615
1616 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
1617
Amjad Aboudfaea5602016-03-07 14:22:46 +00001618 bool HasAnyX86InterruptAttr = false;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001619 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001620 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001621 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001622 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001623 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001624 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001625 if (TargetDecl->hasAttr<NoReturnAttr>())
1626 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001627 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1628 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smithdebc59d2013-01-30 05:45:05 +00001629
1630 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
Samuel Antao798f11c2015-11-23 22:04:44 +00001631 AddAttributesFromFunctionProtoType(
1632 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
Richard Smith49af6292013-03-05 08:30:04 +00001633 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1634 // These attributes are not inherited by overloads.
1635 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1636 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001637 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001638 }
1639
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001640 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
Eric Christopherbf005ec2011-08-15 22:38:22 +00001641 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001642 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1643 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001644 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001645 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1646 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001647 } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
1648 FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
1649 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001650 }
David Majnemer631a90b2015-02-04 07:23:21 +00001651 if (TargetDecl->hasAttr<RestrictAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001652 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001653 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1654 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Paul Robinson08556952014-12-11 20:14:04 +00001655
Amjad Aboudfaea5602016-03-07 14:22:46 +00001656 HasAnyX86InterruptAttr = TargetDecl->hasAttr<AnyX86InterruptAttr>();
Paul Robinson08556952014-12-11 20:14:04 +00001657 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001658 }
1659
Paul Robinson08556952014-12-11 20:14:04 +00001660 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1661 if (!HasOptnone) {
1662 if (CodeGenOpts.OptimizeSize)
1663 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1664 if (CodeGenOpts.OptimizeSize == 2)
1665 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1666 }
1667
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001668 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001669 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001670 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001671 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001672 if (CodeGenOpts.EnableSegmentedStacks &&
1673 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001674 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001675
Bill Wendling2f81db62013-02-22 20:53:29 +00001676 if (AttrOnCallSite) {
1677 // Attributes that should go on the call site only.
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00001678 if (!CodeGenOpts.SimplifyLibCalls ||
1679 CodeGenOpts.isNoBuiltinFunc(Name.data()))
Bill Wendling2f81db62013-02-22 20:53:29 +00001680 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00001681 if (!CodeGenOpts.TrapFuncName.empty())
1682 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
Bill Wendling706469b2013-02-28 22:49:57 +00001683 } else {
1684 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001685 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001686 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001687 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001688 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001689 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001690 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001691 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001692 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001693 }
1694
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001695 bool DisableTailCalls =
Amjad Aboudfaea5602016-03-07 14:22:46 +00001696 CodeGenOpts.DisableTailCalls || HasAnyX86InterruptAttr ||
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001697 (TargetDecl && TargetDecl->hasAttr<DisableTailCallsAttr>());
Amjad Aboudfaea5602016-03-07 14:22:46 +00001698 FuncAttrs.addAttribute(
1699 "disable-tail-calls",
1700 llvm::toStringRef(DisableTailCalls));
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001701
Bill Wendlingdabafea2013-03-13 22:24:33 +00001702 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001703 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001704 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001705 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001706 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001707 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001708 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001709 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001710 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001711 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001712 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001713 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001714
Akira Hatanakaaecca042015-09-11 18:55:09 +00001715 if (CodeGenOpts.StackRealignment)
1716 FuncAttrs.addAttribute("stackrealign");
Eric Christopher70c16652015-03-25 23:14:47 +00001717
Eric Christopher11acf732015-06-12 01:35:52 +00001718 // Add target-cpu and target-features attributes to functions. If
1719 // we have a decl for the function and it has a target attribute then
1720 // parse that and add it to the feature set.
1721 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
Eric Christopher11acf732015-06-12 01:35:52 +00001722 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
Eric Christopherb57804a2015-09-01 22:03:56 +00001723 if (FD && FD->hasAttr<TargetAttr>()) {
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001724 llvm::StringMap<bool> FeatureMap;
Eric Christopher2b90a642015-11-11 23:05:08 +00001725 getFunctionFeatureMap(FeatureMap, FD);
Eric Christopher11acf732015-06-12 01:35:52 +00001726
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001727 // Produce the canonical string for this set of features.
1728 std::vector<std::string> Features;
1729 for (llvm::StringMap<bool>::const_iterator it = FeatureMap.begin(),
1730 ie = FeatureMap.end();
1731 it != ie; ++it)
1732 Features.push_back((it->second ? "+" : "-") + it->first().str());
Eric Christopher2249b812015-07-01 00:08:29 +00001733
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001734 // Now add the target-cpu and target-features to the function.
Eric Christopher2b90a642015-11-11 23:05:08 +00001735 // While we populated the feature map above, we still need to
1736 // get and parse the target attribute so we can get the cpu for
1737 // the function.
1738 const auto *TD = FD->getAttr<TargetAttr>();
1739 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
1740 if (ParsedAttr.second != "")
1741 TargetCPU = ParsedAttr.second;
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001742 if (TargetCPU != "")
1743 FuncAttrs.addAttribute("target-cpu", TargetCPU);
1744 if (!Features.empty()) {
1745 std::sort(Features.begin(), Features.end());
1746 FuncAttrs.addAttribute(
1747 "target-features",
1748 llvm::join(Features.begin(), Features.end(), ","));
1749 }
1750 } else {
1751 // Otherwise just add the existing target cpu and target features to the
1752 // function.
1753 std::vector<std::string> &Features = getTarget().getTargetOpts().Features;
1754 if (TargetCPU != "")
1755 FuncAttrs.addAttribute("target-cpu", TargetCPU);
1756 if (!Features.empty()) {
1757 std::sort(Features.begin(), Features.end());
1758 FuncAttrs.addAttribute(
1759 "target-features",
1760 llvm::join(Features.begin(), Features.end(), ","));
1761 }
Eric Christopher70c16652015-03-25 23:14:47 +00001762 }
Bill Wendling985d1c52013-02-15 21:30:01 +00001763 }
1764
Justin Lebarddd97fa2016-02-24 21:55:11 +00001765 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
1766 // Conservatively, mark all functions and calls in CUDA as convergent
1767 // (meaning, they may call an intrinsically convergent op, such as
1768 // __syncthreads(), and so can't have certain optimizations applied around
1769 // them). LLVM will remove this attribute where it safely can.
1770 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
Justin Lebard3a44f62016-04-05 18:26:20 +00001771
1772 // Respect -fcuda-flush-denormals-to-zero.
1773 if (getLangOpts().CUDADeviceFlushDenormalsToZero)
1774 FuncAttrs.addAttribute("nvptx-f32ftz", "true");
Justin Lebarddd97fa2016-02-24 21:55:11 +00001775 }
1776
Alexey Samsonov153004f2014-09-29 22:08:00 +00001777 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001778
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001779 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001780 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001781 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001782 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001783 if (RetTy->hasSignedIntegerRepresentation())
1784 RetAttrs.addAttribute(llvm::Attribute::SExt);
1785 else if (RetTy->hasUnsignedIntegerRepresentation())
1786 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001787 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001788 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001789 if (RetAI.getInReg())
1790 RetAttrs.addAttribute(llvm::Attribute::InReg);
1791 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001792 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001793 break;
1794
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001795 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001796 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001797 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001798 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1799 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001800 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001801 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001802
John McCallf26e73d2016-03-11 04:30:43 +00001803 case ABIArgInfo::CoerceAndExpand:
1804 break;
1805
Daniel Dunbard3674e62008-09-11 01:48:57 +00001806 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001807 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001808 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001809
Hal Finkela2347ba2014-07-18 15:52:10 +00001810 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1811 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00001812 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00001813 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1814 .getQuantity());
1815 else if (getContext().getTargetAddressSpace(PTy) == 0)
1816 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1817 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001818
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001819 // Attach return attributes.
1820 if (RetAttrs.hasAttributes()) {
1821 PAL.push_back(llvm::AttributeSet::get(
1822 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1823 }
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001824
John McCall12f23522016-04-04 18:33:08 +00001825 bool hasUsedSRet = false;
1826
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001827 // Attach attributes to sret.
1828 if (IRFunctionArgs.hasSRetArg()) {
1829 llvm::AttrBuilder SRETAttrs;
1830 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
John McCall12f23522016-04-04 18:33:08 +00001831 hasUsedSRet = true;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001832 if (RetAI.getInReg())
1833 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1834 PAL.push_back(llvm::AttributeSet::get(
1835 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1836 }
1837
1838 // Attach attributes to inalloca argument.
1839 if (IRFunctionArgs.hasInallocaArg()) {
1840 llvm::AttrBuilder Attrs;
1841 Attrs.addAttribute(llvm::Attribute::InAlloca);
1842 PAL.push_back(llvm::AttributeSet::get(
1843 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1844 }
1845
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001846 unsigned ArgNo = 0;
1847 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1848 E = FI.arg_end();
1849 I != E; ++I, ++ArgNo) {
1850 QualType ParamType = I->type;
1851 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001852 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001853
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001854 // Add attribute for padding argument, if necessary.
1855 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendling290d9522013-01-27 02:46:53 +00001856 if (AI.getPaddingInReg())
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001857 PAL.push_back(llvm::AttributeSet::get(
1858 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1859 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001860 }
1861
John McCall39ec71f2010-03-27 00:47:27 +00001862 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1863 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001864 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001865 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001866 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001867 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001868 Attrs.addAttribute(llvm::Attribute::SExt);
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00001869 else if (ParamType->isUnsignedIntegerOrEnumerationType()) {
1870 if (getTypes().getABIInfo().shouldSignExtUnsignedType(ParamType))
1871 Attrs.addAttribute(llvm::Attribute::SExt);
1872 else
1873 Attrs.addAttribute(llvm::Attribute::ZExt);
1874 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001875 // FALL THROUGH
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001876 case ABIArgInfo::Direct:
Peter Collingbournef7706832014-12-12 23:41:25 +00001877 if (ArgNo == 0 && FI.isChainCall())
1878 Attrs.addAttribute(llvm::Attribute::Nest);
1879 else if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001880 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001881 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001882
James Y Knight71608572015-08-21 18:19:06 +00001883 case ABIArgInfo::Indirect: {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001884 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001885 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001886
Anders Carlsson20759ad2009-09-16 15:53:40 +00001887 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001888 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001889
John McCall7f416cc2015-09-08 08:05:57 +00001890 CharUnits Align = AI.getIndirectAlign();
James Y Knight71608572015-08-21 18:19:06 +00001891
1892 // In a byval argument, it is important that the required
1893 // alignment of the type is honored, as LLVM might be creating a
1894 // *new* stack object, and needs to know what alignment to give
1895 // it. (Sometimes it can deduce a sensible alignment on its own,
1896 // but not if clang decides it must emit a packed struct, or the
1897 // user specifies increased alignment requirements.)
1898 //
1899 // This is different from indirect *not* byval, where the object
1900 // exists already, and the align attribute is purely
1901 // informative.
John McCall7f416cc2015-09-08 08:05:57 +00001902 assert(!Align.isZero());
James Y Knight71608572015-08-21 18:19:06 +00001903
John McCall7f416cc2015-09-08 08:05:57 +00001904 // For now, only add this when we have a byval argument.
1905 // TODO: be less lazy about updating test cases.
1906 if (AI.getIndirectByVal())
1907 Attrs.addAlignmentAttr(Align.getQuantity());
Bill Wendlinga7912f82012-10-10 07:36:56 +00001908
Daniel Dunbarc2304432009-03-18 19:51:01 +00001909 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001910 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1911 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001912 break;
James Y Knight71608572015-08-21 18:19:06 +00001913 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001914 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001915 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00001916 case ABIArgInfo::CoerceAndExpand:
1917 break;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001918
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001919 case ABIArgInfo::InAlloca:
1920 // inalloca disables readnone and readonly.
1921 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1922 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001923 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001924 }
Mike Stump11289f42009-09-09 15:08:12 +00001925
Hal Finkela2347ba2014-07-18 15:52:10 +00001926 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1927 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00001928 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00001929 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1930 .getQuantity());
1931 else if (getContext().getTargetAddressSpace(PTy) == 0)
1932 Attrs.addAttribute(llvm::Attribute::NonNull);
1933 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001934
John McCall12f23522016-04-04 18:33:08 +00001935 switch (FI.getExtParameterInfo(ArgNo).getABI()) {
1936 case ParameterABI::Ordinary:
1937 break;
1938
1939 case ParameterABI::SwiftIndirectResult: {
1940 // Add 'sret' if we haven't already used it for something, but
1941 // only if the result is void.
1942 if (!hasUsedSRet && RetTy->isVoidType()) {
1943 Attrs.addAttribute(llvm::Attribute::StructRet);
1944 hasUsedSRet = true;
1945 }
1946
1947 // Add 'noalias' in either case.
1948 Attrs.addAttribute(llvm::Attribute::NoAlias);
1949
1950 // Add 'dereferenceable' and 'alignment'.
1951 auto PTy = ParamType->getPointeeType();
1952 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
1953 auto info = getContext().getTypeInfoInChars(PTy);
1954 Attrs.addDereferenceableAttr(info.first.getQuantity());
1955 Attrs.addAttribute(llvm::Attribute::getWithAlignment(getLLVMContext(),
1956 info.second.getQuantity()));
1957 }
1958 break;
1959 }
1960
1961 case ParameterABI::SwiftErrorResult:
1962 Attrs.addAttribute(llvm::Attribute::SwiftError);
1963 break;
1964
1965 case ParameterABI::SwiftContext:
1966 Attrs.addAttribute(llvm::Attribute::SwiftSelf);
1967 break;
1968 }
1969
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001970 if (Attrs.hasAttributes()) {
1971 unsigned FirstIRArg, NumIRArgs;
1972 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1973 for (unsigned i = 0; i < NumIRArgs; i++)
1974 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
1975 FirstIRArg + i + 1, Attrs));
1976 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001977 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001978 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001979
Bill Wendlinga7912f82012-10-10 07:36:56 +00001980 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001981 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001982 AttributeSet::get(getLLVMContext(),
1983 llvm::AttributeSet::FunctionIndex,
1984 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001985}
1986
John McCalla738c252011-03-09 04:27:21 +00001987/// An argument came in as a promoted argument; demote it back to its
1988/// declared type.
1989static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1990 const VarDecl *var,
1991 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001992 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001993
1994 // This can happen with promotions that actually don't change the
1995 // underlying type, like the enum promotions.
1996 if (value->getType() == varType) return value;
1997
1998 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1999 && "unexpected promotion type");
2000
2001 if (isa<llvm::IntegerType>(varType))
2002 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
2003
2004 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
2005}
2006
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002007/// Returns the attribute (either parameter attribute, or function
2008/// attribute), which declares argument ArgNo to be non-null.
2009static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
2010 QualType ArgType, unsigned ArgNo) {
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002011 // FIXME: __attribute__((nonnull)) can also be applied to:
2012 // - references to pointers, where the pointee is known to be
2013 // nonnull (apparently a Clang extension)
2014 // - transparent unions containing pointers
2015 // In the former case, LLVM IR cannot represent the constraint. In
2016 // the latter case, we have no guarantee that the transparent union
2017 // is in fact passed as a pointer.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002018 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
2019 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002020 // First, check attribute on parameter itself.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002021 if (PVD) {
2022 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
2023 return ParmNNAttr;
2024 }
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002025 // Check function attributes.
2026 if (!FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002027 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002028 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002029 if (NNAttr->isNonNull(ArgNo))
2030 return NNAttr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002031 }
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002032 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002033}
2034
John McCall12f23522016-04-04 18:33:08 +00002035namespace {
2036 struct CopyBackSwiftError final : EHScopeStack::Cleanup {
2037 Address Temp;
2038 Address Arg;
2039 CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
2040 void Emit(CodeGenFunction &CGF, Flags flags) override {
2041 llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
2042 CGF.Builder.CreateStore(errorValue, Arg);
2043 }
2044 };
2045}
2046
Daniel Dunbard931a872009-02-02 22:03:45 +00002047void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
2048 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00002049 const FunctionArgList &Args) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002050 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
2051 // Naked functions don't have prologues.
2052 return;
2053
John McCallcaa19452009-07-28 01:00:58 +00002054 // If this is an implicit-return-zero function, go ahead and
2055 // initialize the return value. TODO: it might be nice to have
2056 // a more general mechanism for this that didn't require synthesized
2057 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00002058 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00002059 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00002060 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00002061 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00002062 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00002063 Builder.CreateStore(Zero, ReturnValue);
2064 }
2065 }
2066
Mike Stump18bb9282009-05-16 07:57:57 +00002067 // FIXME: We no longer need the types from FunctionArgList; lift up and
2068 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00002069
Alexey Samsonov153004f2014-09-29 22:08:00 +00002070 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002071 // Flattened function arguments.
John McCall12f23522016-04-04 18:33:08 +00002072 SmallVector<llvm::Value *, 16> FnArgs;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002073 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
2074 for (auto &Arg : Fn->args()) {
2075 FnArgs.push_back(&Arg);
2076 }
2077 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00002078
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002079 // If we're using inalloca, all the memory arguments are GEPs off of the last
2080 // parameter, which is a pointer to the complete memory area.
John McCall7f416cc2015-09-08 08:05:57 +00002081 Address ArgStruct = Address::invalid();
2082 const llvm::StructLayout *ArgStructLayout = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002083 if (IRFunctionArgs.hasInallocaArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00002084 ArgStructLayout = CGM.getDataLayout().getStructLayout(FI.getArgStruct());
2085 ArgStruct = Address(FnArgs[IRFunctionArgs.getInallocaArgNo()],
2086 FI.getArgStructAlignment());
2087
2088 assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002089 }
2090
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002091 // Name the struct return parameter.
2092 if (IRFunctionArgs.hasSRetArg()) {
John McCall12f23522016-04-04 18:33:08 +00002093 auto AI = cast<llvm::Argument>(FnArgs[IRFunctionArgs.getSRetArgNo()]);
Daniel Dunbar613855c2008-09-09 23:27:19 +00002094 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00002095 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00002096 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002097 }
Mike Stump11289f42009-09-09 15:08:12 +00002098
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002099 // Track if we received the parameter as a pointer (indirect, byval, or
2100 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
2101 // into a local alloca for us.
John McCall7f416cc2015-09-08 08:05:57 +00002102 SmallVector<ParamValue, 16> ArgVals;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002103 ArgVals.reserve(Args.size());
2104
Reid Kleckner739756c2013-12-04 19:23:12 +00002105 // Create a pointer value for every parameter declaration. This usually
2106 // entails copying one or more LLVM IR arguments into an alloca. Don't push
2107 // any cleanups or do anything that might unwind. We do that separately, so
2108 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002109 assert(FI.arg_size() == Args.size() &&
2110 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002111 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002112 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002113 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00002114 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00002115 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002116 QualType Ty = info_it->type;
2117 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002118
John McCalla738c252011-03-09 04:27:21 +00002119 bool isPromoted =
2120 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
2121
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002122 unsigned FirstIRArg, NumIRArgs;
2123 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002124
Daniel Dunbard3674e62008-09-11 01:48:57 +00002125 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002126 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002127 assert(NumIRArgs == 0);
John McCall7f416cc2015-09-08 08:05:57 +00002128 auto FieldIndex = ArgI.getInAllocaFieldIndex();
2129 CharUnits FieldOffset =
2130 CharUnits::fromQuantity(ArgStructLayout->getElementOffset(FieldIndex));
2131 Address V = Builder.CreateStructGEP(ArgStruct, FieldIndex, FieldOffset,
2132 Arg->getName());
2133 ArgVals.push_back(ParamValue::forIndirect(V));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002134 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002135 }
2136
Daniel Dunbar747865a2009-02-05 09:16:39 +00002137 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002138 assert(NumIRArgs == 1);
John McCall7f416cc2015-09-08 08:05:57 +00002139 Address ParamAddr = Address(FnArgs[FirstIRArg], ArgI.getIndirectAlign());
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002140
John McCall47fb9502013-03-07 21:37:08 +00002141 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002142 // Aggregates and complex variables are accessed by reference. All we
John McCall7f416cc2015-09-08 08:05:57 +00002143 // need to do is realign the value, if requested.
2144 Address V = ParamAddr;
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002145 if (ArgI.getIndirectRealign()) {
John McCall7f416cc2015-09-08 08:05:57 +00002146 Address AlignedTemp = CreateMemTemp(Ty, "coerce");
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002147
2148 // Copy from the incoming argument pointer to the temporary with the
2149 // appropriate alignment.
2150 //
2151 // FIXME: We should have a common utility for generating an aggregate
2152 // copy.
Ken Dyck705ba072011-01-19 01:58:38 +00002153 CharUnits Size = getContext().getTypeSizeInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002154 auto SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity());
2155 Address Dst = Builder.CreateBitCast(AlignedTemp, Int8PtrTy);
2156 Address Src = Builder.CreateBitCast(ParamAddr, Int8PtrTy);
2157 Builder.CreateMemCpy(Dst, Src, SizeVal, false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002158 V = AlignedTemp;
2159 }
John McCall7f416cc2015-09-08 08:05:57 +00002160 ArgVals.push_back(ParamValue::forIndirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00002161 } else {
2162 // Load scalar value from indirect argument.
John McCall7f416cc2015-09-08 08:05:57 +00002163 llvm::Value *V =
2164 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00002165
2166 if (isPromoted)
2167 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002168 ArgVals.push_back(ParamValue::forDirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00002169 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002170 break;
2171 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002172
2173 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00002174 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00002175
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002176 // If we have the trivial case, handle it with no muss and fuss.
2177 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002178 ArgI.getCoerceToType() == ConvertType(Ty) &&
2179 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002180 assert(NumIRArgs == 1);
John McCall12f23522016-04-04 18:33:08 +00002181 llvm::Value *V = FnArgs[FirstIRArg];
2182 auto AI = cast<llvm::Argument>(V);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002183
Hal Finkel48d53e22014-07-19 01:41:07 +00002184 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002185 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
2186 PVD->getFunctionScopeIndex()))
Hal Finkel82504f02014-07-11 17:35:21 +00002187 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2188 AI->getArgNo() + 1,
2189 llvm::Attribute::NonNull));
2190
Hal Finkel48d53e22014-07-19 01:41:07 +00002191 QualType OTy = PVD->getOriginalType();
2192 if (const auto *ArrTy =
2193 getContext().getAsConstantArrayType(OTy)) {
2194 // A C99 array parameter declaration with the static keyword also
2195 // indicates dereferenceability, and if the size is constant we can
2196 // use the dereferenceable attribute (which requires the size in
2197 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00002198 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00002199 QualType ETy = ArrTy->getElementType();
2200 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
2201 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
2202 ArrSize) {
2203 llvm::AttrBuilder Attrs;
2204 Attrs.addDereferenceableAttr(
2205 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
2206 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2207 AI->getArgNo() + 1, Attrs));
2208 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
2209 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2210 AI->getArgNo() + 1,
2211 llvm::Attribute::NonNull));
2212 }
2213 }
2214 } else if (const auto *ArrTy =
2215 getContext().getAsVariableArrayType(OTy)) {
2216 // For C99 VLAs with the static keyword, we don't know the size so
2217 // we can't use the dereferenceable attribute, but in addrspace(0)
2218 // we know that it must be nonnull.
2219 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
2220 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
2221 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2222 AI->getArgNo() + 1,
2223 llvm::Attribute::NonNull));
2224 }
Hal Finkel1b0d24e2014-10-02 21:21:25 +00002225
2226 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
2227 if (!AVAttr)
2228 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
2229 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
2230 if (AVAttr) {
2231 llvm::Value *AlignmentValue =
2232 EmitScalarExpr(AVAttr->getAlignment());
2233 llvm::ConstantInt *AlignmentCI =
2234 cast<llvm::ConstantInt>(AlignmentValue);
2235 unsigned Alignment =
2236 std::min((unsigned) AlignmentCI->getZExtValue(),
2237 +llvm::Value::MaximumAlignment);
2238
2239 llvm::AttrBuilder Attrs;
2240 Attrs.addAlignmentAttr(Alignment);
2241 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2242 AI->getArgNo() + 1, Attrs));
2243 }
Hal Finkel48d53e22014-07-19 01:41:07 +00002244 }
2245
Bill Wendling507c3512012-10-16 05:23:44 +00002246 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00002247 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2248 AI->getArgNo() + 1,
2249 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00002250
John McCall12f23522016-04-04 18:33:08 +00002251 // LLVM expects swifterror parameters to be used in very restricted
2252 // ways. Copy the value into a less-restricted temporary.
2253 if (FI.getExtParameterInfo(ArgNo).getABI()
2254 == ParameterABI::SwiftErrorResult) {
2255 QualType pointeeTy = Ty->getPointeeType();
2256 assert(pointeeTy->isPointerType());
2257 Address temp =
2258 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
2259 Address arg = Address(V, getContext().getTypeAlignInChars(pointeeTy));
2260 llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
2261 Builder.CreateStore(incomingErrorValue, temp);
2262 V = temp.getPointer();
2263
2264 // Push a cleanup to copy the value back at the end of the function.
2265 // The convention does not guarantee that the value will be written
2266 // back if the function exits with an unwind exception.
2267 EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
2268 }
2269
Chris Lattner7369c142011-07-20 06:29:00 +00002270 // Ensure the argument is the correct type.
2271 if (V->getType() != ArgI.getCoerceToType())
2272 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
2273
John McCalla738c252011-03-09 04:27:21 +00002274 if (isPromoted)
2275 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00002276
Nick Lewycky5fa40c32013-10-01 21:51:38 +00002277 if (const CXXMethodDecl *MD =
2278 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00002279 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00002280 V = CGM.getCXXABI().
2281 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00002282 }
2283
Rafael Espindola8778c282012-11-29 16:09:03 +00002284 // Because of merging of function types from multiple decls it is
2285 // possible for the type of an argument to not match the corresponding
2286 // type in the function type. Since we are codegening the callee
2287 // in here, add a cast to the argument type.
2288 llvm::Type *LTy = ConvertType(Arg->getType());
2289 if (V->getType() != LTy)
2290 V = Builder.CreateBitCast(V, LTy);
2291
John McCall7f416cc2015-09-08 08:05:57 +00002292 ArgVals.push_back(ParamValue::forDirect(V));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002293 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00002294 }
Mike Stump11289f42009-09-09 15:08:12 +00002295
John McCall7f416cc2015-09-08 08:05:57 +00002296 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
2297 Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002298
John McCall7f416cc2015-09-08 08:05:57 +00002299 // Pointer to store into.
2300 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002301
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002302 // Fast-isel and the optimizer generally like scalar values better than
2303 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002304 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002305 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
2306 STy->getNumElements() > 1) {
John McCall7f416cc2015-09-08 08:05:57 +00002307 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Micah Villmowdd31ca12012-10-08 16:25:52 +00002308 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
John McCall7f416cc2015-09-08 08:05:57 +00002309 llvm::Type *DstTy = Ptr.getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002310 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002311
John McCall7f416cc2015-09-08 08:05:57 +00002312 Address AddrToStoreInto = Address::invalid();
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002313 if (SrcSize <= DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00002314 AddrToStoreInto =
2315 Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002316 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002317 AddrToStoreInto =
2318 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
Chris Lattner15ec3612010-06-29 00:06:42 +00002319 }
John McCall7f416cc2015-09-08 08:05:57 +00002320
2321 assert(STy->getNumElements() == NumIRArgs);
2322 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2323 auto AI = FnArgs[FirstIRArg + i];
2324 AI->setName(Arg->getName() + ".coerce" + Twine(i));
2325 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
2326 Address EltPtr =
2327 Builder.CreateStructGEP(AddrToStoreInto, i, Offset);
2328 Builder.CreateStore(AI, EltPtr);
2329 }
2330
2331 if (SrcSize > DstSize) {
2332 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
2333 }
2334
Chris Lattner15ec3612010-06-29 00:06:42 +00002335 } else {
2336 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002337 assert(NumIRArgs == 1);
2338 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00002339 AI->setName(Arg->getName() + ".coerce");
John McCall7f416cc2015-09-08 08:05:57 +00002340 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00002341 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002342
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002343 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00002344 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002345 llvm::Value *V =
2346 EmitLoadOfScalar(Alloca, false, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00002347 if (isPromoted)
2348 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002349 ArgVals.push_back(ParamValue::forDirect(V));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002350 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002351 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00002352 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002353 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002354 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002355
John McCallf26e73d2016-03-11 04:30:43 +00002356 case ABIArgInfo::CoerceAndExpand: {
2357 // Reconstruct into a temporary.
2358 Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2359 ArgVals.push_back(ParamValue::forIndirect(alloca));
2360
2361 auto coercionType = ArgI.getCoerceAndExpandType();
2362 alloca = Builder.CreateElementBitCast(alloca, coercionType);
2363 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
2364
2365 unsigned argIndex = FirstIRArg;
2366 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2367 llvm::Type *eltType = coercionType->getElementType(i);
2368 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
2369 continue;
2370
2371 auto eltAddr = Builder.CreateStructGEP(alloca, i, layout);
2372 auto elt = FnArgs[argIndex++];
2373 Builder.CreateStore(elt, eltAddr);
2374 }
2375 assert(argIndex == FirstIRArg + NumIRArgs);
2376 break;
2377 }
2378
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002379 case ABIArgInfo::Expand: {
2380 // If this structure was expanded into multiple arguments then
2381 // we need to create a temporary and reconstruct it from the
2382 // arguments.
John McCall7f416cc2015-09-08 08:05:57 +00002383 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2384 LValue LV = MakeAddrLValue(Alloca, Ty);
2385 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002386
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002387 auto FnArgIter = FnArgs.begin() + FirstIRArg;
2388 ExpandTypeFromArgs(Ty, LV, FnArgIter);
2389 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
2390 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
2391 auto AI = FnArgs[FirstIRArg + i];
2392 AI->setName(Arg->getName() + "." + Twine(i));
2393 }
2394 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002395 }
2396
2397 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002398 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002399 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002400 if (!hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002401 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002402 } else {
2403 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002404 ArgVals.push_back(ParamValue::forDirect(U));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002405 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002406 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002407 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002408 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002409
Reid Kleckner739756c2013-12-04 19:23:12 +00002410 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2411 for (int I = Args.size() - 1; I >= 0; --I)
John McCall7f416cc2015-09-08 08:05:57 +00002412 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002413 } else {
2414 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall7f416cc2015-09-08 08:05:57 +00002415 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002416 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002417}
2418
John McCallffa2c1a2012-01-29 07:46:59 +00002419static void eraseUnusedBitCasts(llvm::Instruction *insn) {
2420 while (insn->use_empty()) {
2421 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
2422 if (!bitcast) return;
2423
2424 // This is "safe" because we would have used a ConstantExpr otherwise.
2425 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
2426 bitcast->eraseFromParent();
2427 }
2428}
2429
John McCall31168b02011-06-15 23:02:42 +00002430/// Try to emit a fused autorelease of a return result.
2431static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
2432 llvm::Value *result) {
2433 // We must be immediately followed the cast.
2434 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002435 if (BB->empty()) return nullptr;
2436 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002437
Chris Lattner2192fe52011-07-18 04:24:23 +00002438 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00002439
2440 // result is in a BasicBlock and is therefore an Instruction.
2441 llvm::Instruction *generator = cast<llvm::Instruction>(result);
2442
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002443 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00002444
2445 // Look for:
2446 // %generator = bitcast %type1* %generator2 to %type2*
2447 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2448 // We would have emitted this as a constant if the operand weren't
2449 // an Instruction.
2450 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2451
2452 // Require the generator to be immediately followed by the cast.
2453 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00002454 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002455
2456 insnsToKill.push_back(bitcast);
2457 }
2458
2459 // Look for:
2460 // %generator = call i8* @objc_retain(i8* %originalResult)
2461 // or
2462 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2463 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00002464 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002465
2466 bool doRetainAutorelease;
2467
John McCallb04ecb72015-10-21 18:06:43 +00002468 if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints().objc_retain) {
John McCall31168b02011-06-15 23:02:42 +00002469 doRetainAutorelease = true;
John McCallb04ecb72015-10-21 18:06:43 +00002470 } else if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints()
John McCall31168b02011-06-15 23:02:42 +00002471 .objc_retainAutoreleasedReturnValue) {
2472 doRetainAutorelease = false;
2473
John McCallcfa4e9b2012-09-07 23:30:50 +00002474 // If we emitted an assembly marker for this call (and the
2475 // ARCEntrypoints field should have been set if so), go looking
2476 // for that call. If we can't find it, we can't do this
2477 // optimization. But it should always be the immediately previous
2478 // instruction, unless we needed bitcasts around the call.
John McCallb04ecb72015-10-21 18:06:43 +00002479 if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
John McCallcfa4e9b2012-09-07 23:30:50 +00002480 llvm::Instruction *prev = call->getPrevNode();
2481 assert(prev);
2482 if (isa<llvm::BitCastInst>(prev)) {
2483 prev = prev->getPrevNode();
2484 assert(prev);
2485 }
2486 assert(isa<llvm::CallInst>(prev));
2487 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
John McCallb04ecb72015-10-21 18:06:43 +00002488 CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
John McCallcfa4e9b2012-09-07 23:30:50 +00002489 insnsToKill.push_back(prev);
2490 }
John McCall31168b02011-06-15 23:02:42 +00002491 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002492 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002493 }
2494
2495 result = call->getArgOperand(0);
2496 insnsToKill.push_back(call);
2497
2498 // Keep killing bitcasts, for sanity. Note that we no longer care
2499 // about precise ordering as long as there's exactly one use.
2500 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2501 if (!bitcast->hasOneUse()) break;
2502 insnsToKill.push_back(bitcast);
2503 result = bitcast->getOperand(0);
2504 }
2505
2506 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002507 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00002508 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
2509 (*i)->eraseFromParent();
2510
2511 // Do the fused retain/autorelease if we were asked to.
2512 if (doRetainAutorelease)
2513 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2514
2515 // Cast back to the result type.
2516 return CGF.Builder.CreateBitCast(result, resultType);
2517}
2518
John McCallffa2c1a2012-01-29 07:46:59 +00002519/// If this is a +1 of the value of an immutable 'self', remove it.
2520static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2521 llvm::Value *result) {
2522 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00002523 const ObjCMethodDecl *method =
2524 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002525 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002526 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00002527 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002528
2529 // Look for a retain call.
2530 llvm::CallInst *retainCall =
2531 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2532 if (!retainCall ||
John McCallb04ecb72015-10-21 18:06:43 +00002533 retainCall->getCalledValue() != CGF.CGM.getObjCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00002534 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002535
2536 // Look for an ordinary load of 'self'.
2537 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2538 llvm::LoadInst *load =
2539 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2540 if (!load || load->isAtomic() || load->isVolatile() ||
John McCall7f416cc2015-09-08 08:05:57 +00002541 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
Craig Topper8a13c412014-05-21 05:09:00 +00002542 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002543
2544 // Okay! Burn it all down. This relies for correctness on the
2545 // assumption that the retain is emitted as part of the return and
2546 // that thereafter everything is used "linearly".
2547 llvm::Type *resultType = result->getType();
2548 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2549 assert(retainCall->use_empty());
2550 retainCall->eraseFromParent();
2551 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2552
2553 return CGF.Builder.CreateBitCast(load, resultType);
2554}
2555
John McCall31168b02011-06-15 23:02:42 +00002556/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00002557///
2558/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00002559static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2560 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00002561 // If we're returning 'self', kill the initial retain. This is a
2562 // heuristic attempt to "encourage correctness" in the really unfortunate
2563 // case where we have a return of self during a dealloc and we desperately
2564 // need to avoid the possible autorelease.
2565 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2566 return self;
2567
John McCall31168b02011-06-15 23:02:42 +00002568 // At -O0, try to emit a fused retain/autorelease.
2569 if (CGF.shouldUseFusedARCCalls())
2570 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2571 return fused;
2572
2573 return CGF.EmitARCAutoreleaseReturnValue(result);
2574}
2575
John McCall6e1c0122012-01-29 02:35:02 +00002576/// Heuristically search for a dominating store to the return-value slot.
2577static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002578 // Check if a User is a store which pointerOperand is the ReturnValue.
2579 // We are looking for stores to the ReturnValue, not for stores of the
2580 // ReturnValue to some other location.
2581 auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
2582 auto *SI = dyn_cast<llvm::StoreInst>(U);
2583 if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer())
2584 return nullptr;
2585 // These aren't actually possible for non-coerced returns, and we
2586 // only care about non-coerced returns on this code path.
2587 assert(!SI->isAtomic() && !SI->isVolatile());
2588 return SI;
2589 };
John McCall6e1c0122012-01-29 02:35:02 +00002590 // If there are multiple uses of the return-value slot, just check
2591 // for something immediately preceding the IP. Sometimes this can
2592 // happen with how we generate implicit-returns; it can also happen
2593 // with noreturn cleanups.
John McCall7f416cc2015-09-08 08:05:57 +00002594 if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
John McCall6e1c0122012-01-29 02:35:02 +00002595 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002596 if (IP->empty()) return nullptr;
David Majnemerdc012fa2015-04-22 21:38:15 +00002597 llvm::Instruction *I = &IP->back();
2598
2599 // Skip lifetime markers
2600 for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
2601 IE = IP->rend();
2602 II != IE; ++II) {
2603 if (llvm::IntrinsicInst *Intrinsic =
2604 dyn_cast<llvm::IntrinsicInst>(&*II)) {
2605 if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
2606 const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
2607 ++II;
Alexey Samsonov10544202015-06-12 21:05:32 +00002608 if (II == IE)
2609 break;
2610 if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
2611 continue;
David Majnemerdc012fa2015-04-22 21:38:15 +00002612 }
2613 }
2614 I = &*II;
2615 break;
2616 }
2617
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002618 return GetStoreIfValid(I);
John McCall6e1c0122012-01-29 02:35:02 +00002619 }
2620
2621 llvm::StoreInst *store =
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002622 GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00002623 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002624
John McCall6e1c0122012-01-29 02:35:02 +00002625 // Now do a first-and-dirty dominance check: just walk up the
2626 // single-predecessors chain from the current insertion point.
2627 llvm::BasicBlock *StoreBB = store->getParent();
2628 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2629 while (IP != StoreBB) {
2630 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00002631 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002632 }
2633
2634 // Okay, the store's basic block dominates the insertion point; we
2635 // can do our thing.
2636 return store;
2637}
2638
Adrian Prantl3be10542013-05-02 17:30:20 +00002639void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002640 bool EmitRetDbgLoc,
2641 SourceLocation EndLoc) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002642 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2643 // Naked functions don't have epilogues.
2644 Builder.CreateUnreachable();
2645 return;
2646 }
2647
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002648 // Functions with no result always return void.
John McCall7f416cc2015-09-08 08:05:57 +00002649 if (!ReturnValue.isValid()) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002650 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00002651 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002652 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00002653
Dan Gohman481e40c2010-07-20 20:13:52 +00002654 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00002655 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00002656 QualType RetTy = FI.getReturnType();
2657 const ABIArgInfo &RetAI = FI.getReturnInfo();
2658
2659 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002660 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00002661 // Aggregrates get evaluated directly into the destination. Sometimes we
2662 // need to return the sret value in a register, though.
2663 assert(hasAggregateEvaluationKind(RetTy));
2664 if (RetAI.getInAllocaSRet()) {
2665 llvm::Function::arg_iterator EI = CurFn->arg_end();
2666 --EI;
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002667 llvm::Value *ArgStruct = &*EI;
David Blaikie2e804282015-04-05 22:47:07 +00002668 llvm::Value *SRet = Builder.CreateStructGEP(
2669 nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
John McCall7f416cc2015-09-08 08:05:57 +00002670 RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret");
Reid Klecknerfab1e892014-02-25 00:59:14 +00002671 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002672 break;
2673
Daniel Dunbar03816342010-08-21 02:24:36 +00002674 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002675 auto AI = CurFn->arg_begin();
2676 if (RetAI.isSRetAfterThis())
2677 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002678 switch (getEvaluationKind(RetTy)) {
2679 case TEK_Complex: {
2680 ComplexPairTy RT =
John McCall7f416cc2015-09-08 08:05:57 +00002681 EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002682 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002683 /*isInit*/ true);
2684 break;
2685 }
2686 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002687 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002688 break;
2689 case TEK_Scalar:
2690 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002691 MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002692 /*isInit*/ true);
2693 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002694 }
2695 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002696 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002697
2698 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002699 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002700 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2701 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002702 // The internal return value temp always will have pointer-to-return-type
2703 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002704
John McCall6e1c0122012-01-29 02:35:02 +00002705 // If there is a dominating store to ReturnValue, we can elide
2706 // the load, zap the store, and usually zap the alloca.
David Majnemerdc012fa2015-04-22 21:38:15 +00002707 if (llvm::StoreInst *SI =
2708 findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002709 // Reuse the debug location from the store unless there is
2710 // cleanup code to be emitted between the store and return
2711 // instruction.
2712 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002713 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002714 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002715 RV = SI->getValueOperand();
2716 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002717
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002718 // If that was the only use of the return value, nuke it as well now.
John McCall7f416cc2015-09-08 08:05:57 +00002719 auto returnValueInst = ReturnValue.getPointer();
2720 if (returnValueInst->use_empty()) {
2721 if (auto alloca = dyn_cast<llvm::AllocaInst>(returnValueInst)) {
2722 alloca->eraseFromParent();
2723 ReturnValue = Address::invalid();
2724 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002725 }
John McCall6e1c0122012-01-29 02:35:02 +00002726
2727 // Otherwise, we have to do a simple load.
2728 } else {
2729 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002730 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002731 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002732 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00002733 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002734
John McCall7f416cc2015-09-08 08:05:57 +00002735 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002736 }
John McCall31168b02011-06-15 23:02:42 +00002737
2738 // In ARC, end functions that return a retainable type with a call
2739 // to objc_autoreleaseReturnValue.
2740 if (AutoreleaseResult) {
Akira Hatanaka9d8ac612016-02-17 21:09:50 +00002741#ifndef NDEBUG
2742 // Type::isObjCRetainabletype has to be called on a QualType that hasn't
2743 // been stripped of the typedefs, so we cannot use RetTy here. Get the
2744 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
2745 // CurCodeDecl or BlockInfo.
2746 QualType RT;
2747
2748 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
2749 RT = FD->getReturnType();
2750 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
2751 RT = MD->getReturnType();
2752 else if (isa<BlockDecl>(CurCodeDecl))
2753 RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
2754 else
2755 llvm_unreachable("Unexpected function/method type");
2756
David Blaikiebbafb8a2012-03-11 07:00:24 +00002757 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002758 !FI.isReturnsRetained() &&
Akira Hatanaka9d8ac612016-02-17 21:09:50 +00002759 RT->isObjCRetainableType());
2760#endif
John McCall31168b02011-06-15 23:02:42 +00002761 RV = emitAutoreleaseOfResult(*this, RV);
2762 }
2763
Chris Lattner726b3d02010-06-26 23:13:19 +00002764 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002765
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002766 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002767 break;
2768
John McCallf26e73d2016-03-11 04:30:43 +00002769 case ABIArgInfo::CoerceAndExpand: {
2770 auto coercionType = RetAI.getCoerceAndExpandType();
2771 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
2772
2773 // Load all of the coerced elements out into results.
2774 llvm::SmallVector<llvm::Value*, 4> results;
2775 Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType);
2776 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2777 auto coercedEltType = coercionType->getElementType(i);
2778 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
2779 continue;
2780
2781 auto eltAddr = Builder.CreateStructGEP(addr, i, layout);
2782 auto elt = Builder.CreateLoad(eltAddr);
2783 results.push_back(elt);
2784 }
2785
2786 // If we have one result, it's the single direct result type.
2787 if (results.size() == 1) {
2788 RV = results[0];
2789
2790 // Otherwise, we need to make a first-class aggregate.
2791 } else {
2792 // Construct a return type that lacks padding elements.
2793 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
2794
2795 RV = llvm::UndefValue::get(returnType);
2796 for (unsigned i = 0, e = results.size(); i != e; ++i) {
2797 RV = Builder.CreateInsertValue(RV, results[i], i);
2798 }
2799 }
2800 break;
2801 }
2802
Chris Lattner726b3d02010-06-26 23:13:19 +00002803 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002804 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002805 }
2806
Alexey Samsonovde443c52014-08-13 00:26:40 +00002807 llvm::Instruction *Ret;
2808 if (RV) {
John McCall9a2c1c92015-09-10 00:57:46 +00002809 if (CurCodeDecl && SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) {
2810 if (auto RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>()) {
Alexey Samsonov90452df2014-09-08 20:17:19 +00002811 SanitizerScope SanScope(this);
2812 llvm::Value *Cond = Builder.CreateICmpNE(
2813 RV, llvm::Constant::getNullValue(RV->getType()));
2814 llvm::Constant *StaticData[] = {
2815 EmitCheckSourceLocation(EndLoc),
2816 EmitCheckSourceLocation(RetNNAttr->getLocation()),
2817 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002818 EmitCheck(std::make_pair(Cond, SanitizerKind::ReturnsNonnullAttribute),
2819 "nonnull_return", StaticData, None);
Alexey Samsonov90452df2014-09-08 20:17:19 +00002820 }
Alexey Samsonovde443c52014-08-13 00:26:40 +00002821 }
2822 Ret = Builder.CreateRet(RV);
2823 } else {
2824 Ret = Builder.CreateRetVoid();
2825 }
2826
Duncan P. N. Exon Smith2809cc72015-03-30 20:01:41 +00002827 if (RetDbgLoc)
Benjamin Kramer03278662015-02-07 13:15:54 +00002828 Ret->setDebugLoc(std::move(RetDbgLoc));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002829}
2830
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002831static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2832 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2833 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2834}
2835
John McCall7f416cc2015-09-08 08:05:57 +00002836static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
2837 QualType Ty) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002838 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2839 // placeholders.
2840 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2841 llvm::Value *Placeholder =
John McCall7f416cc2015-09-08 08:05:57 +00002842 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2843 Placeholder = CGF.Builder.CreateDefaultAlignedLoad(Placeholder);
2844
2845 // FIXME: When we generate this IR in one pass, we shouldn't need
2846 // this win32-specific alignment hack.
2847 CharUnits Align = CharUnits::fromQuantity(4);
2848
2849 return AggValueSlot::forAddr(Address(Placeholder, Align),
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002850 Ty.getQualifiers(),
2851 AggValueSlot::IsNotDestructed,
2852 AggValueSlot::DoesNotNeedGCBarriers,
2853 AggValueSlot::IsNotAliased);
2854}
2855
John McCall32ea9692011-03-11 20:59:21 +00002856void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002857 const VarDecl *param,
2858 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002859 // StartFunction converted the ABI-lowered parameter(s) into a
2860 // local alloca. We need to turn that into an r-value suitable
2861 // for EmitCall.
John McCall7f416cc2015-09-08 08:05:57 +00002862 Address local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002863
John McCall32ea9692011-03-11 20:59:21 +00002864 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002865
John McCall23f66262010-05-26 22:34:26 +00002866 // For the most part, we just need to load the alloca, except:
2867 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall47fb9502013-03-07 21:37:08 +00002868 // 2) references to non-scalars are pointers directly to the aggregate.
2869 // I don't know why references to scalars are different here.
John McCall32ea9692011-03-11 20:59:21 +00002870 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall47fb9502013-03-07 21:37:08 +00002871 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall32ea9692011-03-11 20:59:21 +00002872 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00002873
2874 // Locals which are references to scalars are represented
2875 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00002876 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00002877 }
2878
Reid Klecknerab2090d2014-07-26 01:34:32 +00002879 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2880 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002881
Nick Lewycky2d84e842013-10-02 02:29:49 +00002882 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00002883}
2884
John McCall31168b02011-06-15 23:02:42 +00002885static bool isProvablyNull(llvm::Value *addr) {
2886 return isa<llvm::ConstantPointerNull>(addr);
2887}
2888
2889static bool isProvablyNonNull(llvm::Value *addr) {
2890 return isa<llvm::AllocaInst>(addr);
2891}
2892
2893/// Emit the actual writing-back of a writeback.
2894static void emitWriteback(CodeGenFunction &CGF,
2895 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002896 const LValue &srcLV = writeback.Source;
John McCall7f416cc2015-09-08 08:05:57 +00002897 Address srcAddr = srcLV.getAddress();
2898 assert(!isProvablyNull(srcAddr.getPointer()) &&
John McCall31168b02011-06-15 23:02:42 +00002899 "shouldn't have writeback for provably null argument");
2900
Craig Topper8a13c412014-05-21 05:09:00 +00002901 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002902
2903 // If the argument wasn't provably non-null, we need to null check
2904 // before doing the store.
John McCall7f416cc2015-09-08 08:05:57 +00002905 bool provablyNonNull = isProvablyNonNull(srcAddr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002906 if (!provablyNonNull) {
2907 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2908 contBB = CGF.createBasicBlock("icr.done");
2909
John McCall7f416cc2015-09-08 08:05:57 +00002910 llvm::Value *isNull =
2911 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00002912 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2913 CGF.EmitBlock(writebackBB);
2914 }
2915
2916 // Load the value to writeback.
2917 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2918
2919 // Cast it back, in case we're writing an id to a Foo* or something.
John McCall7f416cc2015-09-08 08:05:57 +00002920 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
2921 "icr.writeback-cast");
John McCall31168b02011-06-15 23:02:42 +00002922
2923 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00002924
2925 // If we have a "to use" value, it's something we need to emit a use
2926 // of. This has to be carefully threaded in: if it's done after the
2927 // release it's potentially undefined behavior (and the optimizer
2928 // will ignore it), and if it happens before the retain then the
2929 // optimizer could move the release there.
2930 if (writeback.ToUse) {
2931 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2932
2933 // Retain the new value. No need to block-copy here: the block's
2934 // being passed up the stack.
2935 value = CGF.EmitARCRetainNonBlock(value);
2936
2937 // Emit the intrinsic use here.
2938 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2939
2940 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00002941 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00002942
2943 // Put the new value in place (primitively).
2944 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2945
2946 // Release the old value.
2947 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2948
2949 // Otherwise, we can just do a normal lvalue store.
2950 } else {
2951 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2952 }
John McCall31168b02011-06-15 23:02:42 +00002953
2954 // Jump to the continuation block.
2955 if (!provablyNonNull)
2956 CGF.EmitBlock(contBB);
2957}
2958
2959static void emitWritebacks(CodeGenFunction &CGF,
2960 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00002961 for (const auto &I : args.writebacks())
2962 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00002963}
2964
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002965static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2966 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002967 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002968 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2969 CallArgs.getCleanupsToDeactivate();
2970 // Iterate in reverse to increase the likelihood of popping the cleanup.
Pete Cooper57d3f142015-07-30 17:22:52 +00002971 for (const auto &I : llvm::reverse(Cleanups)) {
2972 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
2973 I.IsActiveIP->eraseFromParent();
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002974 }
2975}
2976
John McCalleff18842013-03-23 02:35:54 +00002977static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2978 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2979 if (uop->getOpcode() == UO_AddrOf)
2980 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002981 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00002982}
2983
John McCall31168b02011-06-15 23:02:42 +00002984/// Emit an argument that's being passed call-by-writeback. That is,
John McCall7f416cc2015-09-08 08:05:57 +00002985/// we are passing the address of an __autoreleased temporary; it
2986/// might be copy-initialized with the current value of the given
2987/// address, but it will definitely be copied out of after the call.
John McCall31168b02011-06-15 23:02:42 +00002988static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2989 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00002990 LValue srcLV;
2991
2992 // Make an optimistic effort to emit the address as an l-value.
Eric Christopher2c4555a2015-06-19 01:52:53 +00002993 // This can fail if the argument expression is more complicated.
John McCalleff18842013-03-23 02:35:54 +00002994 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2995 srcLV = CGF.EmitLValue(lvExpr);
2996
2997 // Otherwise, just emit it as a scalar.
2998 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002999 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
John McCalleff18842013-03-23 02:35:54 +00003000
3001 QualType srcAddrType =
3002 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003003 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
John McCalleff18842013-03-23 02:35:54 +00003004 }
John McCall7f416cc2015-09-08 08:05:57 +00003005 Address srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00003006
3007 // The dest and src types don't necessarily match in LLVM terms
3008 // because of the crazy ObjC compatibility rules.
3009
Chris Lattner2192fe52011-07-18 04:24:23 +00003010 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00003011 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
3012
3013 // If the address is a constant null, just pass the appropriate null.
John McCall7f416cc2015-09-08 08:05:57 +00003014 if (isProvablyNull(srcAddr.getPointer())) {
John McCall31168b02011-06-15 23:02:42 +00003015 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
3016 CRE->getType());
3017 return;
3018 }
3019
John McCall31168b02011-06-15 23:02:42 +00003020 // Create the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003021 Address temp = CGF.CreateTempAlloca(destType->getElementType(),
3022 CGF.getPointerAlign(),
3023 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003024 // Loading an l-value can introduce a cleanup if the l-value is __weak,
3025 // and that cleanup will be conditional if we can't prove that the l-value
3026 // isn't null, so we need to register a dominating point so that the cleanups
3027 // system will make valid IR.
3028 CodeGenFunction::ConditionalEvaluation condEval(CGF);
3029
John McCall31168b02011-06-15 23:02:42 +00003030 // Zero-initialize it if we're not doing a copy-initialization.
3031 bool shouldCopy = CRE->shouldCopy();
3032 if (!shouldCopy) {
3033 llvm::Value *null =
3034 llvm::ConstantPointerNull::get(
3035 cast<llvm::PointerType>(destType->getElementType()));
3036 CGF.Builder.CreateStore(null, temp);
3037 }
Craig Topper8a13c412014-05-21 05:09:00 +00003038
3039 llvm::BasicBlock *contBB = nullptr;
3040 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00003041
3042 // If the address is *not* known to be non-null, we need to switch.
3043 llvm::Value *finalArgument;
3044
John McCall7f416cc2015-09-08 08:05:57 +00003045 bool provablyNonNull = isProvablyNonNull(srcAddr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00003046 if (provablyNonNull) {
John McCall7f416cc2015-09-08 08:05:57 +00003047 finalArgument = temp.getPointer();
John McCall31168b02011-06-15 23:02:42 +00003048 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003049 llvm::Value *isNull =
3050 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00003051
3052 finalArgument = CGF.Builder.CreateSelect(isNull,
3053 llvm::ConstantPointerNull::get(destType),
John McCall7f416cc2015-09-08 08:05:57 +00003054 temp.getPointer(), "icr.argument");
John McCall31168b02011-06-15 23:02:42 +00003055
3056 // If we need to copy, then the load has to be conditional, which
3057 // means we need control flow.
3058 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00003059 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00003060 contBB = CGF.createBasicBlock("icr.cont");
3061 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
3062 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
3063 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003064 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00003065 }
3066 }
3067
Craig Topper8a13c412014-05-21 05:09:00 +00003068 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00003069
John McCall31168b02011-06-15 23:02:42 +00003070 // Perform a copy if necessary.
3071 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00003072 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00003073 assert(srcRV.isScalar());
3074
3075 llvm::Value *src = srcRV.getScalarVal();
3076 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
3077 "icr.cast");
3078
3079 // Use an ordinary store, not a store-to-lvalue.
3080 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00003081
3082 // If optimization is enabled, and the value was held in a
3083 // __strong variable, we need to tell the optimizer that this
3084 // value has to stay alive until we're doing the store back.
3085 // This is because the temporary is effectively unretained,
3086 // and so otherwise we can violate the high-level semantics.
3087 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3088 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
3089 valueToUse = src;
3090 }
John McCall31168b02011-06-15 23:02:42 +00003091 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003092
John McCall31168b02011-06-15 23:02:42 +00003093 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003094 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00003095 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00003096 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00003097
3098 // Make a phi for the value to intrinsically use.
3099 if (valueToUse) {
3100 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
3101 "icr.to-use");
3102 phiToUse->addIncoming(valueToUse, copyBB);
3103 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
3104 originBB);
3105 valueToUse = phiToUse;
3106 }
3107
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003108 condEval.end(CGF);
3109 }
John McCall31168b02011-06-15 23:02:42 +00003110
John McCalleff18842013-03-23 02:35:54 +00003111 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00003112 args.add(RValue::get(finalArgument), CRE->getType());
3113}
3114
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003115void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
3116 assert(!StackBase && !StackCleanup.isValid());
3117
3118 // Save the stack.
3119 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie43f9bb72015-05-18 22:14:03 +00003120 StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003121}
3122
Nico Weber8cdb3f92015-08-25 18:43:32 +00003123void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
3124 if (StackBase) {
Reid Kleckner7c2f9e82015-10-08 00:17:45 +00003125 // Restore the stack after the call.
Nico Weber8cdb3f92015-08-25 18:43:32 +00003126 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
Nico Weber8cdb3f92015-08-25 18:43:32 +00003127 CGF.Builder.CreateCall(F, StackBase);
3128 }
3129}
3130
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003131void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
3132 SourceLocation ArgLoc,
3133 const FunctionDecl *FD,
3134 unsigned ParmNum) {
3135 if (!SanOpts.has(SanitizerKind::NonnullAttribute) || !FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003136 return;
3137 auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
3138 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
3139 auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
3140 if (!NNAttr)
3141 return;
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003142 SanitizerScope SanScope(this);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003143 assert(RV.isScalar());
3144 llvm::Value *V = RV.getScalarVal();
3145 llvm::Value *Cond =
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003146 Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003147 llvm::Constant *StaticData[] = {
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003148 EmitCheckSourceLocation(ArgLoc),
3149 EmitCheckSourceLocation(NNAttr->getLocation()),
3150 llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003151 };
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003152 EmitCheck(std::make_pair(Cond, SanitizerKind::NonnullAttribute),
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003153 "nonnull_arg", StaticData, None);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003154}
3155
David Blaikief05779e2015-07-21 18:37:18 +00003156void CodeGenFunction::EmitCallArgs(
3157 CallArgList &Args, ArrayRef<QualType> ArgTypes,
3158 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
3159 const FunctionDecl *CalleeDecl, unsigned ParamsToSkip) {
3160 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003161
3162 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg) {
3163 if (CalleeDecl == nullptr || I >= CalleeDecl->getNumParams())
3164 return;
3165 auto *PS = CalleeDecl->getParamDecl(I)->getAttr<PassObjectSizeAttr>();
3166 if (PS == nullptr)
3167 return;
3168
3169 const auto &Context = getContext();
3170 auto SizeTy = Context.getSizeType();
3171 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
3172 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T);
3173 Args.add(RValue::get(V), SizeTy);
3174 };
3175
Reid Kleckner739756c2013-12-04 19:23:12 +00003176 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
3177 // because arguments are destroyed left to right in the callee.
3178 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003179 // Insert a stack save if we're going to need any inalloca args.
3180 bool HasInAllocaArgs = false;
3181 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
3182 I != E && !HasInAllocaArgs; ++I)
3183 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
3184 if (HasInAllocaArgs) {
3185 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3186 Args.allocateArgumentMemory(*this);
3187 }
3188
3189 // Evaluate each argument.
Reid Kleckner739756c2013-12-04 19:23:12 +00003190 size_t CallArgsStart = Args.size();
3191 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
David Blaikief05779e2015-07-21 18:37:18 +00003192 CallExpr::const_arg_iterator Arg = ArgRange.begin() + I;
Reid Kleckner739756c2013-12-04 19:23:12 +00003193 EmitCallArg(Args, *Arg, ArgTypes[I]);
Benjamin Kramerf48ee442015-07-18 14:35:53 +00003194 EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], (*Arg)->getExprLoc(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003195 CalleeDecl, ParamsToSkip + I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003196 MaybeEmitImplicitObjectSize(I, *Arg);
Reid Kleckner739756c2013-12-04 19:23:12 +00003197 }
3198
3199 // Un-reverse the arguments we just evaluated so they match up with the LLVM
3200 // IR function.
3201 std::reverse(Args.begin() + CallArgsStart, Args.end());
3202 return;
3203 }
3204
3205 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
David Blaikief05779e2015-07-21 18:37:18 +00003206 CallExpr::const_arg_iterator Arg = ArgRange.begin() + I;
3207 assert(Arg != ArgRange.end());
Reid Kleckner739756c2013-12-04 19:23:12 +00003208 EmitCallArg(Args, *Arg, ArgTypes[I]);
Benjamin Kramerf48ee442015-07-18 14:35:53 +00003209 EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], (*Arg)->getExprLoc(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003210 CalleeDecl, ParamsToSkip + I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003211 MaybeEmitImplicitObjectSize(I, *Arg);
Reid Kleckner739756c2013-12-04 19:23:12 +00003212 }
3213}
3214
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003215namespace {
3216
David Blaikie7e70d682015-08-18 22:40:54 +00003217struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +00003218 DestroyUnpassedArg(Address Addr, QualType Ty)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003219 : Addr(Addr), Ty(Ty) {}
3220
John McCall7f416cc2015-09-08 08:05:57 +00003221 Address Addr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003222 QualType Ty;
3223
Craig Topper4f12f102014-03-12 06:41:41 +00003224 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003225 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
3226 assert(!Dtor->isTrivial());
3227 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
3228 /*Delegating=*/false, Addr);
3229 }
3230};
3231
David Blaikie38b25912015-02-09 19:13:51 +00003232struct DisableDebugLocationUpdates {
3233 CodeGenFunction &CGF;
3234 bool disabledDebugInfo;
3235 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
3236 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
3237 CGF.disableDebugInfo();
3238 }
3239 ~DisableDebugLocationUpdates() {
3240 if (disabledDebugInfo)
3241 CGF.enableDebugInfo();
3242 }
3243};
3244
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00003245} // end anonymous namespace
3246
John McCall32ea9692011-03-11 20:59:21 +00003247void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
3248 QualType type) {
David Blaikie38b25912015-02-09 19:13:51 +00003249 DisableDebugLocationUpdates Dis(*this, E);
John McCall31168b02011-06-15 23:02:42 +00003250 if (const ObjCIndirectCopyRestoreExpr *CRE
3251 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00003252 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00003253 assert(getContext().hasSameType(E->getType(), type));
3254 return emitWritebackArg(*this, args, CRE);
3255 }
3256
John McCall0a76c0c2011-08-26 18:42:59 +00003257 assert(type->isReferenceType() == E->isGLValue() &&
3258 "reference binding to unmaterialized r-value!");
3259
John McCall17054bd62011-08-26 21:08:13 +00003260 if (E->isGLValue()) {
3261 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00003262 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00003263 }
Mike Stump11289f42009-09-09 15:08:12 +00003264
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003265 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
3266
3267 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
3268 // However, we still have to push an EH-only cleanup in case we unwind before
3269 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00003270 if (HasAggregateEvalKind &&
3271 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
3272 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00003273 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00003274 AggValueSlot Slot;
3275 if (args.isUsingInAlloca())
3276 Slot = createPlaceholderSlot(*this, type);
3277 else
3278 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00003279
3280 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
3281 bool DestroyedInCallee =
3282 RD && RD->hasNonTrivialDestructor() &&
3283 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
3284 if (DestroyedInCallee)
3285 Slot.setExternallyDestructed();
3286
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003287 EmitAggExpr(E, Slot);
3288 RValue RV = Slot.asRValue();
3289 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003290
Reid Klecknere39ee212014-05-03 00:33:28 +00003291 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003292 // Create a no-op GEP between the placeholder and the cleanup so we can
3293 // RAUW it successfully. It also serves as a marker of the first
3294 // instruction where the cleanup is active.
John McCall7f416cc2015-09-08 08:05:57 +00003295 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
3296 type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003297 // This unreachable is a temporary marker which will be removed later.
3298 llvm::Instruction *IsActive = Builder.CreateUnreachable();
3299 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003300 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003301 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003302 }
3303
3304 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00003305 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
3306 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
3307 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00003308 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
3309 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
3310 } else {
3311 // We can't represent a misaligned lvalue in the CallArgList, so copy
3312 // to an aligned temporary now.
John McCall7f416cc2015-09-08 08:05:57 +00003313 Address tmp = CreateMemTemp(type);
3314 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile());
Eli Friedman61f615a2013-06-11 01:08:22 +00003315 args.add(RValue::getAggregate(tmp), type);
3316 }
Eli Friedmandf968192011-05-26 00:10:27 +00003317 return;
3318 }
3319
John McCall32ea9692011-03-11 20:59:21 +00003320 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00003321}
3322
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003323QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
3324 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
3325 // implicitly widens null pointer constants that are arguments to varargs
3326 // functions to pointer-sized ints.
3327 if (!getTarget().getTriple().isOSWindows())
3328 return Arg->getType();
3329
3330 if (Arg->getType()->isIntegerType() &&
3331 getContext().getTypeSize(Arg->getType()) <
3332 getContext().getTargetInfo().getPointerWidth(0) &&
3333 Arg->isNullPointerConstant(getContext(),
3334 Expr::NPC_ValueDependentIsNotNull)) {
3335 return getContext().getIntPtrType();
3336 }
3337
3338 return Arg->getType();
3339}
3340
Dan Gohman515a60d2012-02-16 00:57:37 +00003341// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3342// optimizer it can aggressively ignore unwind edges.
3343void
3344CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
3345 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3346 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
3347 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
3348 CGM.getNoObjCARCExceptionsMetadata());
3349}
3350
John McCall882987f2013-02-28 19:01:20 +00003351/// Emits a call to the given no-arguments nounwind runtime function.
3352llvm::CallInst *
3353CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3354 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003355 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003356}
3357
3358/// Emits a call to the given nounwind runtime function.
3359llvm::CallInst *
3360CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3361 ArrayRef<llvm::Value*> args,
3362 const llvm::Twine &name) {
3363 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
3364 call->setDoesNotThrow();
3365 return call;
3366}
3367
3368/// Emits a simple call (never an invoke) to the given no-arguments
3369/// runtime function.
3370llvm::CallInst *
3371CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3372 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003373 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003374}
3375
David Majnemer0b17d442015-12-15 21:27:59 +00003376// Calls which may throw must have operand bundles indicating which funclet
3377// they are nested within.
3378static void
Sanjay Patel846b63b2016-01-18 22:15:33 +00003379getBundlesForFunclet(llvm::Value *Callee, llvm::Instruction *CurrentFuncletPad,
David Majnemer0b17d442015-12-15 21:27:59 +00003380 SmallVectorImpl<llvm::OperandBundleDef> &BundleList) {
Sanjay Patel846b63b2016-01-18 22:15:33 +00003381 // There is no need for a funclet operand bundle if we aren't inside a
3382 // funclet.
David Majnemer0b17d442015-12-15 21:27:59 +00003383 if (!CurrentFuncletPad)
3384 return;
3385
3386 // Skip intrinsics which cannot throw.
3387 auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts());
3388 if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow())
3389 return;
3390
3391 BundleList.emplace_back("funclet", CurrentFuncletPad);
3392}
3393
David Majnemer971d31b2016-02-24 17:02:45 +00003394/// Emits a simple call (never an invoke) to the given runtime function.
3395llvm::CallInst *
3396CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3397 ArrayRef<llvm::Value*> args,
3398 const llvm::Twine &name) {
3399 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3400 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList);
3401
3402 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList, name);
3403 call->setCallingConv(getRuntimeCC());
3404 return call;
3405}
3406
John McCall882987f2013-02-28 19:01:20 +00003407/// Emits a call or invoke to the given noreturn runtime function.
3408void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
3409 ArrayRef<llvm::Value*> args) {
David Majnemer0b17d442015-12-15 21:27:59 +00003410 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3411 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList);
3412
John McCall882987f2013-02-28 19:01:20 +00003413 if (getInvokeDest()) {
3414 llvm::InvokeInst *invoke =
3415 Builder.CreateInvoke(callee,
3416 getUnreachableBlock(),
3417 getInvokeDest(),
David Majnemer0b17d442015-12-15 21:27:59 +00003418 args,
3419 BundleList);
John McCall882987f2013-02-28 19:01:20 +00003420 invoke->setDoesNotReturn();
3421 invoke->setCallingConv(getRuntimeCC());
3422 } else {
David Majnemer0b17d442015-12-15 21:27:59 +00003423 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
John McCall882987f2013-02-28 19:01:20 +00003424 call->setDoesNotReturn();
3425 call->setCallingConv(getRuntimeCC());
3426 Builder.CreateUnreachable();
3427 }
3428}
3429
Sanjay Patel846b63b2016-01-18 22:15:33 +00003430/// Emits a call or invoke instruction to the given nullary runtime function.
John McCall882987f2013-02-28 19:01:20 +00003431llvm::CallSite
3432CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3433 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003434 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003435}
3436
3437/// Emits a call or invoke instruction to the given runtime function.
3438llvm::CallSite
3439CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3440 ArrayRef<llvm::Value*> args,
3441 const Twine &name) {
3442 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
3443 callSite.setCallingConv(getRuntimeCC());
3444 return callSite;
3445}
3446
John McCallbd309292010-07-06 01:34:17 +00003447/// Emits a call or invoke instruction to the given function, depending
3448/// on the current state of the EH stack.
3449llvm::CallSite
3450CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00003451 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003452 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00003453 llvm::BasicBlock *InvokeDest = getInvokeDest();
David Majnemer3df77bc2016-01-26 23:14:47 +00003454 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3455 getBundlesForFunclet(Callee, CurrentFuncletPad, BundleList);
John McCallbd309292010-07-06 01:34:17 +00003456
Dan Gohman515a60d2012-02-16 00:57:37 +00003457 llvm::Instruction *Inst;
3458 if (!InvokeDest)
David Majnemer3df77bc2016-01-26 23:14:47 +00003459 Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
Dan Gohman515a60d2012-02-16 00:57:37 +00003460 else {
3461 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
David Majnemer3df77bc2016-01-26 23:14:47 +00003462 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
3463 Name);
Dan Gohman515a60d2012-02-16 00:57:37 +00003464 EmitBlock(ContBB);
3465 }
3466
3467 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3468 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003469 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003470 AddObjCARCExceptionMetadata(Inst);
3471
Benjamin Kramerc19cde12015-04-10 14:49:31 +00003472 return llvm::CallSite(Inst);
John McCallbd309292010-07-06 01:34:17 +00003473}
3474
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003475/// \brief Store a non-aggregate value to an address to initialize it. For
3476/// initialization, a non-atomic store will be used.
3477static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
3478 LValue Dst) {
3479 if (Src.isScalar())
3480 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
3481 else
3482 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
3483}
3484
3485void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
3486 llvm::Value *New) {
3487 DeferredReplacements.push_back(std::make_pair(Old, New));
3488}
Chris Lattnerd59d8672011-07-12 06:29:11 +00003489
Daniel Dunbard931a872009-02-02 22:03:45 +00003490RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00003491 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00003492 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003493 const CallArgList &CallArgs,
Samuel Antao798f11c2015-11-23 22:04:44 +00003494 CGCalleeInfo CalleeInfo,
David Chisnallff5f88c2010-05-02 13:41:58 +00003495 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00003496 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00003497
3498 // Handle struct-return functions by passing a pointer to the
3499 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00003500 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003501 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003502
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003503 llvm::FunctionType *IRFuncTy =
3504 cast<llvm::FunctionType>(
3505 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00003506
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003507 // If we're using inalloca, insert the allocation after the stack save.
3508 // FIXME: Do this earlier rather than hacking it in here!
John McCall7f416cc2015-09-08 08:05:57 +00003509 Address ArgMemory = Address::invalid();
3510 const llvm::StructLayout *ArgMemoryLayout = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003511 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
John McCall7f416cc2015-09-08 08:05:57 +00003512 ArgMemoryLayout = CGM.getDataLayout().getStructLayout(ArgStruct);
Reid Kleckner9df1d972014-04-10 01:40:15 +00003513 llvm::Instruction *IP = CallArgs.getStackBase();
3514 llvm::AllocaInst *AI;
3515 if (IP) {
3516 IP = IP->getNextNode();
3517 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
3518 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00003519 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00003520 }
John McCall7f416cc2015-09-08 08:05:57 +00003521 auto Align = CallInfo.getArgStructAlignment();
3522 AI->setAlignment(Align.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003523 AI->setUsedWithInAlloca(true);
3524 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
John McCall7f416cc2015-09-08 08:05:57 +00003525 ArgMemory = Address(AI, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003526 }
3527
John McCall7f416cc2015-09-08 08:05:57 +00003528 // Helper function to drill into the inalloca allocation.
3529 auto createInAllocaStructGEP = [&](unsigned FieldIndex) -> Address {
3530 auto FieldOffset =
3531 CharUnits::fromQuantity(ArgMemoryLayout->getElementOffset(FieldIndex));
3532 return Builder.CreateStructGEP(ArgMemory, FieldIndex, FieldOffset);
3533 };
3534
Alexey Samsonov153004f2014-09-29 22:08:00 +00003535 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003536 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
3537
Chris Lattner4ca97c32009-06-13 00:26:38 +00003538 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00003539 // alloca to hold the result, unless one is given to us.
John McCall7f416cc2015-09-08 08:05:57 +00003540 Address SRetPtr = Address::invalid();
Leny Kholodov6aab1112015-06-08 10:23:49 +00003541 size_t UnusedReturnSize = 0;
John McCallf26e73d2016-03-11 04:30:43 +00003542 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
John McCall7f416cc2015-09-08 08:05:57 +00003543 if (!ReturnValue.isNull()) {
3544 SRetPtr = ReturnValue.getValue();
3545 } else {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003546 SRetPtr = CreateMemTemp(RetTy);
Leny Kholodov6aab1112015-06-08 10:23:49 +00003547 if (HaveInsertPoint() && ReturnValue.isUnused()) {
3548 uint64_t size =
3549 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
John McCall7f416cc2015-09-08 08:05:57 +00003550 if (EmitLifetimeStart(size, SRetPtr.getPointer()))
Leny Kholodov6aab1112015-06-08 10:23:49 +00003551 UnusedReturnSize = size;
3552 }
3553 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003554 if (IRFunctionArgs.hasSRetArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00003555 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
John McCallf26e73d2016-03-11 04:30:43 +00003556 } else if (RetAI.isInAlloca()) {
John McCall7f416cc2015-09-08 08:05:57 +00003557 Address Addr = createInAllocaStructGEP(RetAI.getInAllocaFieldIndex());
3558 Builder.CreateStore(SRetPtr.getPointer(), Addr);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003559 }
Anders Carlsson17490832009-12-24 20:40:36 +00003560 }
Mike Stump11289f42009-09-09 15:08:12 +00003561
John McCall12f23522016-04-04 18:33:08 +00003562 Address swiftErrorTemp = Address::invalid();
3563 Address swiftErrorArg = Address::invalid();
3564
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00003565 assert(CallInfo.arg_size() == CallArgs.size() &&
3566 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003567 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003568 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00003569 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003570 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003571 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003572 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003573
Rafael Espindolafad28de2012-10-24 01:59:00 +00003574 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003575 if (IRFunctionArgs.hasPaddingArg(ArgNo))
3576 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
3577 llvm::UndefValue::get(ArgInfo.getPaddingType());
3578
3579 unsigned FirstIRArg, NumIRArgs;
3580 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003581
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003582 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003583 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003584 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003585 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3586 if (RV.isAggregate()) {
3587 // Replace the placeholder with the appropriate argument slot GEP.
3588 llvm::Instruction *Placeholder =
John McCall7f416cc2015-09-08 08:05:57 +00003589 cast<llvm::Instruction>(RV.getAggregatePointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003590 CGBuilderTy::InsertPoint IP = Builder.saveIP();
3591 Builder.SetInsertPoint(Placeholder);
John McCall7f416cc2015-09-08 08:05:57 +00003592 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003593 Builder.restoreIP(IP);
John McCall7f416cc2015-09-08 08:05:57 +00003594 deferPlaceholderReplacement(Placeholder, Addr.getPointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003595 } else {
3596 // Store the RValue into the argument struct.
John McCall7f416cc2015-09-08 08:05:57 +00003597 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
3598 unsigned AS = Addr.getType()->getPointerAddressSpace();
David Majnemer32b57b02014-03-31 16:12:47 +00003599 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3600 // There are some cases where a trivial bitcast is not avoidable. The
3601 // definition of a type later in a translation unit may change it's type
3602 // from {}* to (%struct.foo*)*.
John McCall7f416cc2015-09-08 08:05:57 +00003603 if (Addr.getType() != MemType)
David Majnemer32b57b02014-03-31 16:12:47 +00003604 Addr = Builder.CreateBitCast(Addr, MemType);
John McCall7f416cc2015-09-08 08:05:57 +00003605 LValue argLV = MakeAddrLValue(Addr, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003606 EmitInitStoreOfNonAggregate(*this, RV, argLV);
3607 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003608 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003609 }
3610
Daniel Dunbar03816342010-08-21 02:24:36 +00003611 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003612 assert(NumIRArgs == 1);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003613 if (RV.isScalar() || RV.isComplex()) {
3614 // Make a temporary alloca to pass the argument.
John McCall7f416cc2015-09-08 08:05:57 +00003615 Address Addr = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3616 IRCallArgs[FirstIRArg] = Addr.getPointer();
John McCall47fb9502013-03-07 21:37:08 +00003617
John McCall7f416cc2015-09-08 08:05:57 +00003618 LValue argLV = MakeAddrLValue(Addr, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003619 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003620 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003621 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00003622 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003623 // 1. If the argument is not byval, and we are required to copy the
3624 // source. (This case doesn't occur on any common architecture.)
3625 // 2. If the argument is byval, RV is not sufficiently aligned, and
3626 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00003627 // 3. If the argument is byval, but RV is located in an address space
3628 // different than that of the argument (0).
John McCall7f416cc2015-09-08 08:05:57 +00003629 Address Addr = RV.getAggregateAddress();
3630 CharUnits Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003631 const llvm::DataLayout *TD = &CGM.getDataLayout();
John McCall7f416cc2015-09-08 08:05:57 +00003632 const unsigned RVAddrSpace = Addr.getType()->getAddressSpace();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003633 const unsigned ArgAddrSpace =
3634 (FirstIRArg < IRFuncTy->getNumParams()
3635 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
3636 : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00003637 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall7f416cc2015-09-08 08:05:57 +00003638 (ArgInfo.getIndirectByVal() && Addr.getAlignment() < Align &&
3639 llvm::getOrEnforceKnownAlignment(Addr.getPointer(),
3640 Align.getQuantity(), *TD)
3641 < Align.getQuantity()) ||
Mehdi Aminib3d52092015-03-10 02:36:43 +00003642 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003643 // Create an aligned temporary, and copy to it.
John McCall7f416cc2015-09-08 08:05:57 +00003644 Address AI = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3645 IRCallArgs[FirstIRArg] = AI.getPointer();
Chad Rosier615ed1a2012-03-29 17:37:10 +00003646 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003647 } else {
3648 // Skip the extra memcpy call.
John McCall7f416cc2015-09-08 08:05:57 +00003649 IRCallArgs[FirstIRArg] = Addr.getPointer();
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003650 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003651 }
3652 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00003653 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003654
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003655 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003656 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003657 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003658
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003659 case ABIArgInfo::Extend:
3660 case ABIArgInfo::Direct: {
3661 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003662 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3663 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003664 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003665 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003666 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003667 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003668 else
John McCall7f416cc2015-09-08 08:05:57 +00003669 V = Builder.CreateLoad(RV.getAggregateAddress());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003670
John McCall12f23522016-04-04 18:33:08 +00003671 // Implement swifterror by copying into a new swifterror argument.
3672 // We'll write back in the normal path out of the call.
3673 if (CallInfo.getExtParameterInfo(ArgNo).getABI()
3674 == ParameterABI::SwiftErrorResult) {
3675 assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
3676
3677 QualType pointeeTy = I->Ty->getPointeeType();
3678 swiftErrorArg =
3679 Address(V, getContext().getTypeAlignInChars(pointeeTy));
3680
3681 swiftErrorTemp =
3682 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
3683 V = swiftErrorTemp.getPointer();
3684 cast<llvm::AllocaInst>(V)->setSwiftError(true);
3685
3686 llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
3687 Builder.CreateStore(errorValue, swiftErrorTemp);
3688 }
3689
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003690 // We might have to widen integers, but we should never truncate.
3691 if (ArgInfo.getCoerceToType() != V->getType() &&
3692 V->getType()->isIntegerTy())
3693 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
3694
Chris Lattner3ce86682011-07-12 04:53:39 +00003695 // If the argument doesn't match, perform a bitcast to coerce it. This
3696 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003697 if (FirstIRArg < IRFuncTy->getNumParams() &&
3698 V->getType() != IRFuncTy->getParamType(FirstIRArg))
3699 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
John McCall12f23522016-04-04 18:33:08 +00003700
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003701 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003702 break;
3703 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003704
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003705 // FIXME: Avoid the conversion through memory if possible.
John McCall7f416cc2015-09-08 08:05:57 +00003706 Address Src = Address::invalid();
John McCall47fb9502013-03-07 21:37:08 +00003707 if (RV.isScalar() || RV.isComplex()) {
John McCall7f416cc2015-09-08 08:05:57 +00003708 Src = CreateMemTemp(I->Ty, "coerce");
3709 LValue SrcLV = MakeAddrLValue(Src, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003710 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00003711 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003712 Src = RV.getAggregateAddress();
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00003713 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003714
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003715 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00003716 Src = emitAddressAtOffset(*this, Src, ArgInfo);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003717
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003718 // Fast-isel and the optimizer generally like scalar values better than
3719 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00003720 llvm::StructType *STy =
3721 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003722 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
John McCall7f416cc2015-09-08 08:05:57 +00003723 llvm::Type *SrcTy = Src.getType()->getElementType();
Chandler Carrutha6399a52012-10-10 11:29:08 +00003724 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
3725 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
3726
3727 // If the source type is smaller than the destination type of the
3728 // coerce-to logic, copy the source value into a temp alloca the size
3729 // of the destination type to allow loading all of it. The bits past
3730 // the source value are left undef.
3731 if (SrcSize < DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00003732 Address TempAlloca
3733 = CreateTempAlloca(STy, Src.getAlignment(),
3734 Src.getName() + ".coerce");
3735 Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
3736 Src = TempAlloca;
Chandler Carrutha6399a52012-10-10 11:29:08 +00003737 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003738 Src = Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(STy));
Chandler Carrutha6399a52012-10-10 11:29:08 +00003739 }
3740
John McCall7f416cc2015-09-08 08:05:57 +00003741 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003742 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00003743 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00003744 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
3745 Address EltPtr = Builder.CreateStructGEP(Src, i, Offset);
3746 llvm::Value *LI = Builder.CreateLoad(EltPtr);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003747 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00003748 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00003749 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00003750 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003751 assert(NumIRArgs == 1);
3752 IRCallArgs[FirstIRArg] =
John McCall7f416cc2015-09-08 08:05:57 +00003753 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00003754 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003755
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003756 break;
3757 }
3758
John McCallf26e73d2016-03-11 04:30:43 +00003759 case ABIArgInfo::CoerceAndExpand: {
John McCallf26e73d2016-03-11 04:30:43 +00003760 auto coercionType = ArgInfo.getCoerceAndExpandType();
3761 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
3762
John McCall12f23522016-04-04 18:33:08 +00003763 llvm::Value *tempSize = nullptr;
3764 Address addr = Address::invalid();
3765 if (RV.isAggregate()) {
3766 addr = RV.getAggregateAddress();
3767 } else {
3768 assert(RV.isScalar()); // complex should always just be direct
3769
3770 llvm::Type *scalarType = RV.getScalarVal()->getType();
3771 auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
3772 auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType);
3773
3774 tempSize = llvm::ConstantInt::get(CGM.Int64Ty, scalarSize);
3775
3776 // Materialize to a temporary.
3777 addr = CreateTempAlloca(RV.getScalarVal()->getType(),
3778 CharUnits::fromQuantity(std::max(layout->getAlignment(),
3779 scalarAlign)));
3780 EmitLifetimeStart(scalarSize, addr.getPointer());
3781
3782 Builder.CreateStore(RV.getScalarVal(), addr);
3783 }
3784
John McCallf26e73d2016-03-11 04:30:43 +00003785 addr = Builder.CreateElementBitCast(addr, coercionType);
3786
3787 unsigned IRArgPos = FirstIRArg;
3788 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3789 llvm::Type *eltType = coercionType->getElementType(i);
3790 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
3791 Address eltAddr = Builder.CreateStructGEP(addr, i, layout);
3792 llvm::Value *elt = Builder.CreateLoad(eltAddr);
3793 IRCallArgs[IRArgPos++] = elt;
3794 }
3795 assert(IRArgPos == FirstIRArg + NumIRArgs);
3796
John McCall12f23522016-04-04 18:33:08 +00003797 if (tempSize) {
3798 EmitLifetimeEnd(tempSize, addr.getPointer());
3799 }
3800
John McCallf26e73d2016-03-11 04:30:43 +00003801 break;
3802 }
3803
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003804 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003805 unsigned IRArgPos = FirstIRArg;
3806 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
3807 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003808 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003809 }
3810 }
Mike Stump11289f42009-09-09 15:08:12 +00003811
John McCall7f416cc2015-09-08 08:05:57 +00003812 if (ArgMemory.isValid()) {
3813 llvm::Value *Arg = ArgMemory.getPointer();
Reid Klecknerafba553e2014-07-08 02:24:27 +00003814 if (CallInfo.isVariadic()) {
3815 // When passing non-POD arguments by value to variadic functions, we will
3816 // end up with a variadic prototype and an inalloca call site. In such
3817 // cases, we can't do any parameter mismatch checks. Give up and bitcast
3818 // the callee.
3819 unsigned CalleeAS =
3820 cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
3821 Callee = Builder.CreateBitCast(
3822 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
3823 } else {
3824 llvm::Type *LastParamTy =
3825 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
3826 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003827#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00003828 // Assert that these structs have equivalent element types.
3829 llvm::StructType *FullTy = CallInfo.getArgStruct();
3830 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3831 cast<llvm::PointerType>(LastParamTy)->getElementType());
3832 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3833 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3834 DE = DeclaredTy->element_end(),
3835 FI = FullTy->element_begin();
3836 DI != DE; ++DI, ++FI)
3837 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003838#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00003839 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3840 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003841 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003842 assert(IRFunctionArgs.hasInallocaArg());
3843 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003844 }
3845
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003846 if (!CallArgs.getCleanupsToDeactivate().empty())
3847 deactivateArgCleanupsBeforeCall(*this, CallArgs);
3848
Chris Lattner4ca97c32009-06-13 00:26:38 +00003849 // If the callee is a bitcast of a function to a varargs pointer to function
3850 // type, check to see if we can remove the bitcast. This handles some cases
3851 // with unprototyped functions.
3852 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
3853 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003854 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
3855 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00003856 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00003857 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00003858
Chris Lattner4ca97c32009-06-13 00:26:38 +00003859 if (CE->getOpcode() == llvm::Instruction::BitCast &&
3860 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00003861 ActualFT->getNumParams() == CurFT->getNumParams() &&
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003862 ActualFT->getNumParams() == IRCallArgs.size() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00003863 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00003864 bool ArgsMatch = true;
3865 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
3866 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
3867 ArgsMatch = false;
3868 break;
3869 }
Mike Stump11289f42009-09-09 15:08:12 +00003870
Chris Lattner4ca97c32009-06-13 00:26:38 +00003871 // Strip the cast if we can get away with it. This is a nice cleanup,
3872 // but also allows us to inline the function at -O0 if it is marked
3873 // always_inline.
3874 if (ArgsMatch)
3875 Callee = CalleeF;
3876 }
3877 }
Mike Stump11289f42009-09-09 15:08:12 +00003878
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003879 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
3880 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
3881 // Inalloca argument can have different type.
3882 if (IRFunctionArgs.hasInallocaArg() &&
3883 i == IRFunctionArgs.getInallocaArgNo())
3884 continue;
3885 if (i < IRFuncTy->getNumParams())
3886 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
3887 }
3888
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003889 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00003890 CodeGen::AttributeListType AttributeList;
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00003891 CGM.ConstructAttributeList(Callee->getName(), CallInfo, CalleeInfo,
3892 AttributeList, CallingConv,
3893 /*AttrOnCallSite=*/true);
Bill Wendling3087d022012-12-07 23:17:26 +00003894 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003895 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00003896
David Majnemer4e52d6f2015-12-12 05:39:21 +00003897 bool CannotThrow;
3898 if (currentFunctionUsesSEHTry()) {
3899 // SEH cares about asynchronous exceptions, everything can "throw."
3900 CannotThrow = false;
3901 } else if (isCleanupPadScope() &&
3902 EHPersonality::get(*this).isMSVCXXPersonality()) {
3903 // The MSVC++ personality will implicitly terminate the program if an
3904 // exception is thrown. An unwind edge cannot be reached.
3905 CannotThrow = true;
3906 } else {
3907 // Otherwise, nowunind callsites will never throw.
3908 CannotThrow = Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
3909 llvm::Attribute::NoUnwind);
3910 }
3911 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00003912
David Majnemer0b17d442015-12-15 21:27:59 +00003913 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3914 getBundlesForFunclet(Callee, CurrentFuncletPad, BundleList);
3915
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003916 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00003917 if (!InvokeDest) {
David Majnemer0b17d442015-12-15 21:27:59 +00003918 CS = Builder.CreateCall(Callee, IRCallArgs, BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00003919 } else {
3920 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
David Majnemer0b17d442015-12-15 21:27:59 +00003921 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs,
3922 BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00003923 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003924 }
Chris Lattnere70a0072010-06-29 16:40:28 +00003925 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00003926 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003927
Peter Collingbourne41af7c22014-05-20 17:12:51 +00003928 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
3929 !CS.hasFnAttr(llvm::Attribute::NoInline))
3930 Attrs =
3931 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3932 llvm::Attribute::AlwaysInline);
3933
David Majnemer4e52d6f2015-12-12 05:39:21 +00003934 // Disable inlining inside SEH __try blocks.
3935 if (isSEHTryScope())
Reid Klecknera5930002015-02-11 21:40:48 +00003936 Attrs =
3937 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3938 llvm::Attribute::NoInline);
3939
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003940 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003941 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003942
Adam Nemet1e217bc2016-03-28 22:18:53 +00003943 // Insert instrumentation or attach profile metadata at indirect call sites.
3944 // For more details, see the comment before the definition of
3945 // IPVK_IndirectCallTarget in InstrProfData.inc.
Betul Buyukkurt518276a2016-01-23 22:50:44 +00003946 if (!CS.getCalledFunction())
3947 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
3948 CS.getInstruction(), Callee);
3949
Dan Gohman515a60d2012-02-16 00:57:37 +00003950 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3951 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003952 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003953 AddObjCARCExceptionMetadata(CS.getInstruction());
3954
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003955 // If the call doesn't return, finish the basic block and clear the
3956 // insertion point; this allows the rest of IRgen to discard
3957 // unreachable code.
3958 if (CS.doesNotReturn()) {
Leny Kholodov6aab1112015-06-08 10:23:49 +00003959 if (UnusedReturnSize)
3960 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
John McCall7f416cc2015-09-08 08:05:57 +00003961 SRetPtr.getPointer());
Leny Kholodov6aab1112015-06-08 10:23:49 +00003962
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003963 Builder.CreateUnreachable();
3964 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003965
Mike Stump18bb9282009-05-16 07:57:57 +00003966 // FIXME: For now, emit a dummy basic block because expr emitters in
3967 // generally are not ready to handle emitting expressions at unreachable
3968 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003969 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003970
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003971 // Return a reasonable RValue.
3972 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00003973 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003974
3975 llvm::Instruction *CI = CS.getInstruction();
Mehdi Amini557c20a2016-03-13 21:05:23 +00003976 if (!CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00003977 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003978
John McCall12f23522016-04-04 18:33:08 +00003979 // Perform the swifterror writeback.
3980 if (swiftErrorTemp.isValid()) {
3981 llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
3982 Builder.CreateStore(errorResult, swiftErrorArg);
3983 }
3984
John McCall31168b02011-06-15 23:02:42 +00003985 // Emit any writebacks immediately. Arguably this should happen
3986 // after any return-value munging.
3987 if (CallArgs.hasWritebacks())
3988 emitWritebacks(*this, CallArgs);
3989
Nico Weber8cdb3f92015-08-25 18:43:32 +00003990 // The stack cleanup for inalloca arguments has to run out of the normal
3991 // lexical order, so deactivate it and run it manually here.
3992 CallArgs.freeArgumentMemory(*this);
3993
Samuel Antao798f11c2015-11-23 22:04:44 +00003994 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
3995 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
Akira Hatanakac8667622015-11-06 23:56:15 +00003996 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
3997 Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
Samuel Antao798f11c2015-11-23 22:04:44 +00003998 }
Akira Hatanakac8667622015-11-06 23:56:15 +00003999
Hal Finkelee90a222014-09-26 05:04:30 +00004000 RValue Ret = [&] {
4001 switch (RetAI.getKind()) {
John McCallf26e73d2016-03-11 04:30:43 +00004002 case ABIArgInfo::CoerceAndExpand: {
4003 auto coercionType = RetAI.getCoerceAndExpandType();
4004 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
4005
4006 Address addr = SRetPtr;
4007 addr = Builder.CreateElementBitCast(addr, coercionType);
4008
John McCall12f23522016-04-04 18:33:08 +00004009 assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
4010 bool requiresExtract = isa<llvm::StructType>(CI->getType());
4011
John McCallf26e73d2016-03-11 04:30:43 +00004012 unsigned unpaddedIndex = 0;
4013 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
4014 llvm::Type *eltType = coercionType->getElementType(i);
4015 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
4016 Address eltAddr = Builder.CreateStructGEP(addr, i, layout);
John McCall12f23522016-04-04 18:33:08 +00004017 llvm::Value *elt = CI;
4018 if (requiresExtract)
4019 elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
4020 else
4021 assert(unpaddedIndex == 0);
John McCallf26e73d2016-03-11 04:30:43 +00004022 Builder.CreateStore(elt, eltAddr);
4023 }
John McCall12f23522016-04-04 18:33:08 +00004024 // FALLTHROUGH
4025 }
4026
4027 case ABIArgInfo::InAlloca:
4028 case ABIArgInfo::Indirect: {
4029 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
4030 if (UnusedReturnSize)
4031 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
4032 SRetPtr.getPointer());
4033 return ret;
John McCallf26e73d2016-03-11 04:30:43 +00004034 }
4035
Hal Finkelee90a222014-09-26 05:04:30 +00004036 case ABIArgInfo::Ignore:
4037 // If we are ignoring an argument that had a result, make sure to
4038 // construct the appropriate return value for our caller.
4039 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004040
Hal Finkelee90a222014-09-26 05:04:30 +00004041 case ABIArgInfo::Extend:
4042 case ABIArgInfo::Direct: {
4043 llvm::Type *RetIRTy = ConvertType(RetTy);
4044 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
4045 switch (getEvaluationKind(RetTy)) {
4046 case TEK_Complex: {
4047 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
4048 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
4049 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004050 }
Hal Finkelee90a222014-09-26 05:04:30 +00004051 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +00004052 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00004053 bool DestIsVolatile = ReturnValue.isVolatile();
4054
John McCall7f416cc2015-09-08 08:05:57 +00004055 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00004056 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
4057 DestIsVolatile = false;
4058 }
John McCall7f416cc2015-09-08 08:05:57 +00004059 BuildAggStore(*this, CI, DestPtr, DestIsVolatile);
Hal Finkelee90a222014-09-26 05:04:30 +00004060 return RValue::getAggregate(DestPtr);
4061 }
4062 case TEK_Scalar: {
4063 // If the argument doesn't match, perform a bitcast to coerce it. This
4064 // can happen due to trivial type mismatches.
4065 llvm::Value *V = CI;
4066 if (V->getType() != RetIRTy)
4067 V = Builder.CreateBitCast(V, RetIRTy);
4068 return RValue::get(V);
4069 }
4070 }
4071 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004072 }
Hal Finkelee90a222014-09-26 05:04:30 +00004073
John McCall7f416cc2015-09-08 08:05:57 +00004074 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00004075 bool DestIsVolatile = ReturnValue.isVolatile();
4076
John McCall7f416cc2015-09-08 08:05:57 +00004077 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00004078 DestPtr = CreateMemTemp(RetTy, "coerce");
4079 DestIsVolatile = false;
John McCall47fb9502013-03-07 21:37:08 +00004080 }
Hal Finkelee90a222014-09-26 05:04:30 +00004081
4082 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00004083 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
4084 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Hal Finkelee90a222014-09-26 05:04:30 +00004085
4086 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004087 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004088
Hal Finkelee90a222014-09-26 05:04:30 +00004089 case ABIArgInfo::Expand:
4090 llvm_unreachable("Invalid ABI kind for return argument");
Anders Carlsson17490832009-12-24 20:40:36 +00004091 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004092
Hal Finkelee90a222014-09-26 05:04:30 +00004093 llvm_unreachable("Unhandled ABIArgInfo::Kind");
4094 } ();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004095
Samuel Antao798f11c2015-11-23 22:04:44 +00004096 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
4097
Hal Finkelee90a222014-09-26 05:04:30 +00004098 if (Ret.isScalar() && TargetDecl) {
4099 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
4100 llvm::Value *OffsetValue = nullptr;
4101 if (const auto *Offset = AA->getOffset())
4102 OffsetValue = EmitScalarExpr(Offset);
4103
4104 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
4105 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
4106 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
4107 OffsetValue);
4108 }
Daniel Dunbar573884e2008-09-10 07:04:09 +00004109 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00004110
Hal Finkelee90a222014-09-26 05:04:30 +00004111 return Ret;
Daniel Dunbar613855c2008-09-09 23:27:19 +00004112}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00004113
4114/* VarArg handling */
4115
Charles Davisc7d5c942015-09-17 20:55:33 +00004116Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
4117 VAListAddr = VE->isMicrosoftABI()
4118 ? EmitMSVAListRef(VE->getSubExpr())
4119 : EmitVAListRef(VE->getSubExpr());
4120 QualType Ty = VE->getType();
4121 if (VE->isMicrosoftABI())
4122 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004123 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00004124}