blob: 0693949e4366ee6f340669d7ccdcf08f74717046 [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"
Eric Christopher15709992015-10-15 23:47:11 +000026#include "clang/Basic/TargetBuiltins.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000028#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth85098242010-06-15 23:19:56 +000029#include "clang/Frontend/CodeGenOptions.h"
Bill Wendling706469b2013-02-28 22:49:57 +000030#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000031#include "llvm/IR/Attributes.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000032#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000033#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/InlineAsm.h"
Reid Kleckner314ef7b2014-02-01 00:04:45 +000035#include "llvm/IR/Intrinsics.h"
David Majnemerdc012fa2015-04-22 21:38:15 +000036#include "llvm/IR/IntrinsicInst.h"
Eli Friedmanf7456192011-06-15 22:09:18 +000037#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000038using namespace clang;
39using namespace CodeGen;
40
41/***/
42
John McCallab26cfa2010-02-05 21:31:56 +000043static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) {
44 switch (CC) {
45 default: return llvm::CallingConv::C;
46 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
47 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
Douglas Gregora941dca2010-05-18 16:57:00 +000048 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Charles Davisb5a214e2013-08-30 04:39:01 +000049 case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64;
50 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
Anton Korobeynikov231e8752011-04-14 20:06:49 +000051 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
52 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Guy Benyeif0a014b2012-12-25 08:53:55 +000053 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Reid Klecknerd7857f02014-10-24 17:42:17 +000054 // TODO: Add support for __pascal to LLVM.
55 case CC_X86Pascal: return llvm::CallingConv::C;
56 // TODO: Add support for __vectorcall to LLVM.
Reid Kleckner80944df2014-10-31 22:00:51 +000057 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
Alexander Kornienko21de0ae2015-01-20 11:20:41 +000058 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
59 case CC_SpirKernel: return llvm::CallingConv::SPIR_KERNEL;
Roman Levenstein35aa5ce2016-03-16 18:00:46 +000060 case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
61 case CC_PreserveAll: return llvm::CallingConv::PreserveAll;
John McCallab26cfa2010-02-05 21:31:56 +000062 }
63}
64
John McCall8ee376f2010-02-24 07:14:12 +000065/// Derives the 'this' type for codegen purposes, i.e. ignoring method
66/// qualification.
67/// FIXME: address space qualification?
John McCall2da83a32010-02-26 00:48:12 +000068static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
69 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
70 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000071}
72
John McCall8ee376f2010-02-24 07:14:12 +000073/// Returns the canonical formal type of the given C++ method.
John McCall2da83a32010-02-26 00:48:12 +000074static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
75 return MD->getType()->getCanonicalTypeUnqualified()
76 .getAs<FunctionProtoType>();
John McCall8ee376f2010-02-24 07:14:12 +000077}
78
79/// Returns the "extra-canonicalized" return type, which discards
80/// qualifiers on the return type. Codegen doesn't care about them,
81/// and it makes ABI code a little easier to be able to assume that
82/// all parameter and return types are top-level unqualified.
John McCall2da83a32010-02-26 00:48:12 +000083static CanQualType GetReturnType(QualType RetTy) {
84 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall8ee376f2010-02-24 07:14:12 +000085}
86
John McCall8dda7b22012-07-07 06:41:13 +000087/// Arrange the argument and result information for a value of the given
88/// unprototyped freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +000089const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +000090CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCalla729c622012-02-17 03:33:10 +000091 // When translating an unprototyped function type, always use a
92 // variadic type.
Alp Toker314cc812014-01-25 16:55:45 +000093 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
Peter Collingbournef7706832014-12-12 23:41:25 +000094 /*instanceMethod=*/false,
95 /*chainCall=*/false, None,
John McCallc56a8b32016-03-11 04:30:31 +000096 FTNP->getExtInfo(), {}, RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +000097}
98
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000099/// Adds the formal paramaters in FPT to the given prefix. If any parameter in
100/// FPT has pass_object_size attrs, then we'll add parameters for those, too.
101static void appendParameterTypes(const CodeGenTypes &CGT,
102 SmallVectorImpl<CanQualType> &prefix,
John McCallc56a8b32016-03-11 04:30:31 +0000103 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
104 CanQual<FunctionProtoType> FPT,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000105 const FunctionDecl *FD) {
John McCallc56a8b32016-03-11 04:30:31 +0000106 // Fill out paramInfos.
107 if (FPT->hasExtParameterInfos() || !paramInfos.empty()) {
108 assert(paramInfos.size() <= prefix.size());
109 auto protoParamInfos = FPT->getExtParameterInfos();
110 paramInfos.reserve(prefix.size() + protoParamInfos.size());
111 paramInfos.resize(prefix.size());
112 paramInfos.append(paramInfos.begin(), paramInfos.end());
113 }
114
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000115 // Fast path: unknown target.
116 if (FD == nullptr) {
117 prefix.append(FPT->param_type_begin(), FPT->param_type_end());
118 return;
119 }
120
121 // In the vast majority cases, we'll have precisely FPT->getNumParams()
122 // parameters; the only thing that can change this is the presence of
123 // pass_object_size. So, we preallocate for the common case.
124 prefix.reserve(prefix.size() + FPT->getNumParams());
125
126 assert(FD->getNumParams() == FPT->getNumParams());
127 for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
128 prefix.push_back(FPT->getParamType(I));
129 if (FD->getParamDecl(I)->hasAttr<PassObjectSizeAttr>())
130 prefix.push_back(CGT.getContext().getSizeType());
131 }
132}
133
John McCall8dda7b22012-07-07 06:41:13 +0000134/// Arrange the LLVM function layout for a value of the given function
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000135/// type, on top of any implicit parameters already stored.
136static const CGFunctionInfo &
Peter Collingbournef7706832014-12-12 23:41:25 +0000137arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000138 SmallVectorImpl<CanQualType> &prefix,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000139 CanQual<FunctionProtoType> FTP,
140 const FunctionDecl *FD) {
John McCallc56a8b32016-03-11 04:30:31 +0000141 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
John McCall8dda7b22012-07-07 06:41:13 +0000142 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000143 // FIXME: Kill copy.
John McCallc56a8b32016-03-11 04:30:31 +0000144 appendParameterTypes(CGT, prefix, paramInfos, FTP, FD);
Alp Toker314cc812014-01-25 16:55:45 +0000145 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
John McCallc56a8b32016-03-11 04:30:31 +0000146
Peter Collingbournef7706832014-12-12 23:41:25 +0000147 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
148 /*chainCall=*/false, prefix,
John McCallc56a8b32016-03-11 04:30:31 +0000149 FTP->getExtInfo(), paramInfos,
150 required);
John McCall8ee376f2010-02-24 07:14:12 +0000151}
152
John McCalla729c622012-02-17 03:33:10 +0000153/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000154/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000155const CGFunctionInfo &
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000156CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP,
157 const FunctionDecl *FD) {
John McCalla729c622012-02-17 03:33:10 +0000158 SmallVector<CanQualType, 16> argTypes;
Peter Collingbournef7706832014-12-12 23:41:25 +0000159 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000160 FTP, FD);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000161}
162
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000163static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000164 // Set the appropriate calling convention for the Function.
165 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000166 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000167
168 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000169 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000170
Douglas Gregora941dca2010-05-18 16:57:00 +0000171 if (D->hasAttr<ThisCallAttr>())
172 return CC_X86ThisCall;
173
Reid Klecknerd7857f02014-10-24 17:42:17 +0000174 if (D->hasAttr<VectorCallAttr>())
175 return CC_X86VectorCall;
176
Dawn Perchik335e16b2010-09-03 01:29:35 +0000177 if (D->hasAttr<PascalAttr>())
178 return CC_X86Pascal;
179
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000180 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
181 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
182
Guy Benyeif0a014b2012-12-25 08:53:55 +0000183 if (D->hasAttr<IntelOclBiccAttr>())
184 return CC_IntelOclBicc;
185
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000186 if (D->hasAttr<MSABIAttr>())
187 return IsWindows ? CC_C : CC_X86_64Win64;
188
189 if (D->hasAttr<SysVABIAttr>())
190 return IsWindows ? CC_X86_64SysV : CC_C;
191
Roman Levenstein35aa5ce2016-03-16 18:00:46 +0000192 if (D->hasAttr<PreserveMostAttr>())
193 return CC_PreserveMost;
194
195 if (D->hasAttr<PreserveAllAttr>())
196 return CC_PreserveAll;
197
John McCallab26cfa2010-02-05 21:31:56 +0000198 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000199}
200
John McCalla729c622012-02-17 03:33:10 +0000201/// Arrange the argument and result information for a call to an
202/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000203/// (Zero value of RD means we don't have any meaningful "this" argument type,
204/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000205/// The member function must be an ordinary function, i.e. not a
206/// constructor or destructor.
207const CGFunctionInfo &
208CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000209 const FunctionProtoType *FTP,
210 const CXXMethodDecl *MD) {
John McCalla729c622012-02-17 03:33:10 +0000211 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000212
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000213 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000214 if (RD)
215 argTypes.push_back(GetThisType(Context, RD));
216 else
217 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000218
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000219 return ::arrangeLLVMFunctionInfo(
220 *this, true, argTypes,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000221 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>(), MD);
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000222}
223
John McCalla729c622012-02-17 03:33:10 +0000224/// Arrange the argument and result information for a declaration or
225/// definition of the given C++ non-static member function. The
226/// member function must be an ordinary function, i.e. not a
227/// constructor or destructor.
228const CGFunctionInfo &
229CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000230 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000231 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
232
John McCalla729c622012-02-17 03:33:10 +0000233 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000234
John McCalla729c622012-02-17 03:33:10 +0000235 if (MD->isInstance()) {
236 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000237 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000238 return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
John McCalla729c622012-02-17 03:33:10 +0000239 }
240
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000241 return arrangeFreeFunctionType(prototype, MD);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000242}
243
John McCalla729c622012-02-17 03:33:10 +0000244const CGFunctionInfo &
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000245CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
246 StructorType Type) {
247
John McCalla729c622012-02-17 03:33:10 +0000248 SmallVector<CanQualType, 16> argTypes;
John McCallc56a8b32016-03-11 04:30:31 +0000249 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000250 argTypes.push_back(GetThisType(Context, MD->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000251
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000252 GlobalDecl GD;
253 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
254 GD = GlobalDecl(CD, toCXXCtorType(Type));
255 } else {
256 auto *DD = dyn_cast<CXXDestructorDecl>(MD);
257 GD = GlobalDecl(DD, toCXXDtorType(Type));
258 }
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000259
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000260 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
John McCall5d865c322010-08-31 07:33:07 +0000261
262 // Add the formal parameters.
John McCallc56a8b32016-03-11 04:30:31 +0000263 appendParameterTypes(*this, argTypes, paramInfos, FTP, MD);
John McCall5d865c322010-08-31 07:33:07 +0000264
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000265 TheCXXABI.buildStructorSignature(MD, Type, argTypes);
Reid Kleckner89077a12013-12-17 19:46:40 +0000266
267 RequiredArgs required =
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000268 (MD->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All);
Reid Kleckner89077a12013-12-17 19:46:40 +0000269
John McCall8dda7b22012-07-07 06:41:13 +0000270 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000271 CanQualType resultType = TheCXXABI.HasThisReturn(GD)
272 ? argTypes.front()
273 : TheCXXABI.hasMostDerivedReturn(GD)
274 ? CGM.getContext().VoidPtrTy
275 : Context.VoidTy;
Peter Collingbournef7706832014-12-12 23:41:25 +0000276 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
277 /*chainCall=*/false, argTypes, extInfo,
John McCallc56a8b32016-03-11 04:30:31 +0000278 paramInfos, required);
279}
280
281static SmallVector<CanQualType, 16>
282getArgTypesForCall(ASTContext &ctx, const CallArgList &args) {
283 SmallVector<CanQualType, 16> argTypes;
284 for (auto &arg : args)
285 argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
286 return argTypes;
287}
288
289static SmallVector<CanQualType, 16>
290getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) {
291 SmallVector<CanQualType, 16> argTypes;
292 for (auto &arg : args)
293 argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
294 return argTypes;
295}
296
297static void addExtParameterInfosForCall(
298 llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
299 const FunctionProtoType *proto,
300 unsigned prefixArgs,
301 unsigned totalArgs) {
302 assert(proto->hasExtParameterInfos());
303 assert(paramInfos.size() <= prefixArgs);
304 assert(proto->getNumParams() + prefixArgs <= totalArgs);
305
306 // Add default infos for any prefix args that don't already have infos.
307 paramInfos.resize(prefixArgs);
308
309 // Add infos for the prototype.
310 auto protoInfos = proto->getExtParameterInfos();
311 paramInfos.append(protoInfos.begin(), protoInfos.end());
312
313 // Add default infos for the variadic arguments.
314 paramInfos.resize(totalArgs);
315}
316
317static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16>
318getExtParameterInfosForCall(const FunctionProtoType *proto,
319 unsigned prefixArgs, unsigned totalArgs) {
320 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result;
321 if (proto->hasExtParameterInfos()) {
322 addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
323 }
324 return result;
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000325}
326
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000327/// Arrange a call to a C++ method, passing the given arguments.
328const CGFunctionInfo &
329CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
330 const CXXConstructorDecl *D,
331 CXXCtorType CtorKind,
332 unsigned ExtraArgs) {
333 // FIXME: Kill copy.
334 SmallVector<CanQualType, 16> ArgTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000335 for (const auto &Arg : args)
336 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000337
338 CanQual<FunctionProtoType> FPT = GetFormalType(D);
339 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs);
340 GlobalDecl GD(D, CtorKind);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000341 CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
342 ? ArgTypes.front()
343 : TheCXXABI.hasMostDerivedReturn(GD)
344 ? CGM.getContext().VoidPtrTy
345 : Context.VoidTy;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000346
347 FunctionType::ExtInfo Info = FPT->getExtInfo();
John McCallc56a8b32016-03-11 04:30:31 +0000348 auto ParamInfos = getExtParameterInfosForCall(FPT.getTypePtr(), 1 + ExtraArgs,
349 ArgTypes.size());
Peter Collingbournef7706832014-12-12 23:41:25 +0000350 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
351 /*chainCall=*/false, ArgTypes, Info,
John McCallc56a8b32016-03-11 04:30:31 +0000352 ParamInfos, Required);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000353}
354
John McCalla729c622012-02-17 03:33:10 +0000355/// Arrange the argument and result information for the declaration or
356/// definition of the given function.
357const CGFunctionInfo &
358CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000359 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000360 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000361 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000362
John McCall2da83a32010-02-26 00:48:12 +0000363 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000364
John McCall2da83a32010-02-26 00:48:12 +0000365 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000366
367 // When declaring a function without a prototype, always use a
368 // non-variadic type.
369 if (isa<FunctionNoProtoType>(FTy)) {
370 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Peter Collingbournef7706832014-12-12 23:41:25 +0000371 return arrangeLLVMFunctionInfo(
372 noProto->getReturnType(), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000373 /*chainCall=*/false, None, noProto->getExtInfo(), {},RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000374 }
375
John McCall2da83a32010-02-26 00:48:12 +0000376 assert(isa<FunctionProtoType>(FTy));
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000377 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>(), FD);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000378}
379
John McCalla729c622012-02-17 03:33:10 +0000380/// Arrange the argument and result information for the declaration or
381/// definition of an Objective-C method.
382const CGFunctionInfo &
383CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
384 // It happens that this is the same as a call with no optional
385 // arguments, except also using the formal 'self' type.
386 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
387}
388
389/// Arrange the argument and result information for the function type
390/// through which to perform a send to the given Objective-C method,
391/// using the given receiver type. The receiver type is not always
392/// the 'self' type of the method or even an Objective-C pointer type.
393/// This is *not* the right method for actually performing such a
394/// message send, due to the possibility of optional arguments.
395const CGFunctionInfo &
396CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
397 QualType receiverType) {
398 SmallVector<CanQualType, 16> argTys;
399 argTys.push_back(Context.getCanonicalParamType(receiverType));
400 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000401 // FIXME: Kill copy?
Aaron Ballman43b68be2014-03-07 17:50:17 +0000402 for (const auto *I : MD->params()) {
403 argTys.push_back(Context.getCanonicalParamType(I->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000404 }
John McCall31168b02011-06-15 23:02:42 +0000405
406 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000407 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
408 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000409
David Blaikiebbafb8a2012-03-11 07:00:24 +0000410 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000411 MD->hasAttr<NSReturnsRetainedAttr>())
412 einfo = einfo.withProducesResult(true);
413
John McCalla729c622012-02-17 03:33:10 +0000414 RequiredArgs required =
415 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
416
Peter Collingbournef7706832014-12-12 23:41:25 +0000417 return arrangeLLVMFunctionInfo(
418 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000419 /*chainCall=*/false, argTys, einfo, {}, required);
420}
421
422const CGFunctionInfo &
423CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType,
424 const CallArgList &args) {
425 auto argTypes = getArgTypesForCall(Context, args);
426 FunctionType::ExtInfo einfo;
427
428 return arrangeLLVMFunctionInfo(
429 GetReturnType(returnType), /*instanceMethod=*/false,
430 /*chainCall=*/false, argTypes, einfo, {}, RequiredArgs::All);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000431}
432
John McCalla729c622012-02-17 03:33:10 +0000433const CGFunctionInfo &
434CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000435 // FIXME: Do we need to handle ObjCMethodDecl?
436 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000437
Anders Carlsson6710c532010-02-06 02:44:09 +0000438 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000439 return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
Anders Carlsson6710c532010-02-06 02:44:09 +0000440
441 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000442 return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000443
John McCalla729c622012-02-17 03:33:10 +0000444 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000445}
446
Reid Klecknerc3473512014-08-29 21:43:29 +0000447/// Arrange a thunk that takes 'this' as the first parameter followed by
448/// varargs. Return a void pointer, regardless of the actual return type.
449/// The body of the thunk will end in a musttail call to a function of the
450/// correct type, and the caller will bitcast the function to the correct
451/// prototype.
452const CGFunctionInfo &
453CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) {
454 assert(MD->isVirtual() && "only virtual memptrs have thunks");
455 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
456 CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
Peter Collingbournef7706832014-12-12 23:41:25 +0000457 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
458 /*chainCall=*/false, ArgTys,
John McCallc56a8b32016-03-11 04:30:31 +0000459 FTP->getExtInfo(), {}, RequiredArgs(1));
Reid Klecknerc3473512014-08-29 21:43:29 +0000460}
461
David Majnemerdfa6d202015-03-11 18:36:39 +0000462const CGFunctionInfo &
David Majnemer37fd66e2015-03-13 22:36:55 +0000463CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
464 CXXCtorType CT) {
465 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
466
David Majnemerdfa6d202015-03-11 18:36:39 +0000467 CanQual<FunctionProtoType> FTP = GetFormalType(CD);
468 SmallVector<CanQualType, 2> ArgTys;
469 const CXXRecordDecl *RD = CD->getParent();
470 ArgTys.push_back(GetThisType(Context, RD));
David Majnemer37fd66e2015-03-13 22:36:55 +0000471 if (CT == Ctor_CopyingClosure)
472 ArgTys.push_back(*FTP->param_type_begin());
David Majnemerdfa6d202015-03-11 18:36:39 +0000473 if (RD->getNumVBases() > 0)
474 ArgTys.push_back(Context.IntTy);
475 CallingConv CC = Context.getDefaultCallingConvention(
476 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
477 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
478 /*chainCall=*/false, ArgTys,
John McCallc56a8b32016-03-11 04:30:31 +0000479 FunctionType::ExtInfo(CC), {},
480 RequiredArgs::All);
David Majnemerdfa6d202015-03-11 18:36:39 +0000481}
482
John McCallc818bbb2012-12-07 07:03:17 +0000483/// Arrange a call as unto a free function, except possibly with an
484/// additional number of formal parameters considered required.
485static const CGFunctionInfo &
486arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000487 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000488 const CallArgList &args,
489 const FunctionType *fnType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000490 unsigned numExtraRequiredArgs,
491 bool chainCall) {
John McCallc818bbb2012-12-07 07:03:17 +0000492 assert(args.size() >= numExtraRequiredArgs);
493
John McCallc56a8b32016-03-11 04:30:31 +0000494 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
495
John McCallc818bbb2012-12-07 07:03:17 +0000496 // In most cases, there are no optional arguments.
497 RequiredArgs required = RequiredArgs::All;
498
499 // If we have a variadic prototype, the required arguments are the
500 // extra prefix plus the arguments in the prototype.
501 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
502 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000503 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000504
John McCallc56a8b32016-03-11 04:30:31 +0000505 if (proto->hasExtParameterInfos())
506 addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
507 args.size());
508
John McCallc818bbb2012-12-07 07:03:17 +0000509 // If we don't have a prototype at all, but we're supposed to
510 // explicitly use the variadic convention for unprototyped calls,
511 // treat all of the arguments as required but preserve the nominal
512 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000513 } else if (CGM.getTargetCodeGenInfo()
514 .isNoProtoCallVariadic(args,
515 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000516 required = RequiredArgs(args.size());
517 }
518
Peter Collingbournef7706832014-12-12 23:41:25 +0000519 // FIXME: Kill copy.
520 SmallVector<CanQualType, 16> argTypes;
521 for (const auto &arg : args)
522 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
523 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
524 /*instanceMethod=*/false, chainCall,
John McCallc56a8b32016-03-11 04:30:31 +0000525 argTypes, fnType->getExtInfo(), paramInfos,
526 required);
John McCallc818bbb2012-12-07 07:03:17 +0000527}
528
John McCalla729c622012-02-17 03:33:10 +0000529/// Figure out the rules for calling a function with the given formal
530/// type using the given arguments. The arguments are necessary
531/// because the function might be unprototyped, in which case it's
532/// target-dependent in crazy ways.
533const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000534CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
Peter Collingbournef7706832014-12-12 23:41:25 +0000535 const FunctionType *fnType,
536 bool chainCall) {
537 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
538 chainCall ? 1 : 0, chainCall);
John McCallc818bbb2012-12-07 07:03:17 +0000539}
John McCalla729c622012-02-17 03:33:10 +0000540
John McCallc56a8b32016-03-11 04:30:31 +0000541/// A block function is essentially a free function with an
John McCallc818bbb2012-12-07 07:03:17 +0000542/// extra implicit argument.
543const CGFunctionInfo &
544CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
545 const FunctionType *fnType) {
Peter Collingbournef7706832014-12-12 23:41:25 +0000546 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
547 /*chainCall=*/false);
John McCalla729c622012-02-17 03:33:10 +0000548}
549
550const CGFunctionInfo &
John McCallc56a8b32016-03-11 04:30:31 +0000551CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto,
552 const FunctionArgList &params) {
553 auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
554 auto argTypes = getArgTypesForDeclaration(Context, params);
555
556 return arrangeLLVMFunctionInfo(GetReturnType(proto->getReturnType()),
557 /*instanceMethod*/ false, /*chainCall*/ false,
558 argTypes, proto->getExtInfo(), paramInfos,
559 RequiredArgs::forPrototypePlus(proto, 1));
560}
561
562const CGFunctionInfo &
563CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType,
564 const CallArgList &args) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000565 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000566 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000567 for (const auto &Arg : args)
568 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Peter Collingbournef7706832014-12-12 23:41:25 +0000569 return arrangeLLVMFunctionInfo(
570 GetReturnType(resultType), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000571 /*chainCall=*/false, argTypes, FunctionType::ExtInfo(),
572 /*paramInfos=*/ {}, RequiredArgs::All);
John McCall8dda7b22012-07-07 06:41:13 +0000573}
574
John McCallc56a8b32016-03-11 04:30:31 +0000575const CGFunctionInfo &
576CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType,
577 const FunctionArgList &args) {
578 auto argTypes = getArgTypesForDeclaration(Context, args);
579
580 return arrangeLLVMFunctionInfo(
581 GetReturnType(resultType), /*instanceMethod=*/false, /*chainCall=*/false,
582 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
583}
584
585const CGFunctionInfo &
586CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType,
587 ArrayRef<CanQualType> argTypes) {
588 return arrangeLLVMFunctionInfo(
589 resultType, /*instanceMethod=*/false, /*chainCall=*/false,
590 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
591}
592
593
John McCall8dda7b22012-07-07 06:41:13 +0000594/// Arrange a call to a C++ method, passing the given arguments.
595const CGFunctionInfo &
596CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
John McCallc56a8b32016-03-11 04:30:31 +0000597 const FunctionProtoType *proto,
John McCall8dda7b22012-07-07 06:41:13 +0000598 RequiredArgs required) {
John McCallc56a8b32016-03-11 04:30:31 +0000599 unsigned numRequiredArgs =
600 (proto->isVariadic() ? required.getNumRequiredArgs() : args.size());
601 unsigned numPrefixArgs = numRequiredArgs - proto->getNumParams();
602 auto paramInfos =
603 getExtParameterInfosForCall(proto, numPrefixArgs, args.size());
604
John McCall8dda7b22012-07-07 06:41:13 +0000605 // FIXME: Kill copy.
John McCallc56a8b32016-03-11 04:30:31 +0000606 auto argTypes = getArgTypesForCall(Context, args);
John McCall8dda7b22012-07-07 06:41:13 +0000607
John McCallc56a8b32016-03-11 04:30:31 +0000608 FunctionType::ExtInfo info = proto->getExtInfo();
Peter Collingbournef7706832014-12-12 23:41:25 +0000609 return arrangeLLVMFunctionInfo(
John McCallc56a8b32016-03-11 04:30:31 +0000610 GetReturnType(proto->getReturnType()), /*instanceMethod=*/true,
611 /*chainCall=*/false, argTypes, info, paramInfos, required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000612}
613
John McCalla729c622012-02-17 03:33:10 +0000614const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Peter Collingbournef7706832014-12-12 23:41:25 +0000615 return arrangeLLVMFunctionInfo(
616 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000617 None, FunctionType::ExtInfo(), {}, RequiredArgs::All);
618}
619
620const CGFunctionInfo &
621CodeGenTypes::arrangeCall(const CGFunctionInfo &signature,
622 const CallArgList &args) {
623 assert(signature.arg_size() <= args.size());
624 if (signature.arg_size() == args.size())
625 return signature;
626
627 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
628 auto sigParamInfos = signature.getExtParameterInfos();
629 if (!sigParamInfos.empty()) {
630 paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
631 paramInfos.resize(args.size());
632 }
633
634 auto argTypes = getArgTypesForCall(Context, args);
635
636 assert(signature.getRequiredArgs().allowsOptionalArgs());
637 return arrangeLLVMFunctionInfo(signature.getReturnType(),
638 signature.isInstanceMethod(),
639 signature.isChainCall(),
640 argTypes,
641 signature.getExtInfo(),
642 paramInfos,
643 signature.getRequiredArgs());
John McCalla738c252011-03-09 04:27:21 +0000644}
645
John McCalla729c622012-02-17 03:33:10 +0000646/// Arrange the argument and result information for an abstract value
647/// of a given function type. This is the method which all of the
648/// above functions ultimately defer to.
649const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000650CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000651 bool instanceMethod,
652 bool chainCall,
John McCall8dda7b22012-07-07 06:41:13 +0000653 ArrayRef<CanQualType> argTypes,
654 FunctionType::ExtInfo info,
John McCallc56a8b32016-03-11 04:30:31 +0000655 ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
John McCall8dda7b22012-07-07 06:41:13 +0000656 RequiredArgs required) {
Saleem Abdulrasool32d1a962014-11-25 03:49:50 +0000657 assert(std::all_of(argTypes.begin(), argTypes.end(),
658 std::mem_fun_ref(&CanQualType::isCanonicalAsParam)));
John McCall2da83a32010-02-26 00:48:12 +0000659
Daniel Dunbare0be8292009-02-03 00:07:12 +0000660 // Lookup or create unique function info.
661 llvm::FoldingSetNodeID ID;
John McCallc56a8b32016-03-11 04:30:31 +0000662 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos,
663 required, resultType, argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000664
Craig Topper8a13c412014-05-21 05:09:00 +0000665 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000666 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000667 if (FI)
668 return *FI;
669
John McCallc56a8b32016-03-11 04:30:31 +0000670 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
671
John McCalla729c622012-02-17 03:33:10 +0000672 // Construct the function info. We co-allocate the ArgInfos.
Peter Collingbournef7706832014-12-12 23:41:25 +0000673 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
John McCallc56a8b32016-03-11 04:30:31 +0000674 paramInfos, resultType, argTypes, required);
John McCalla729c622012-02-17 03:33:10 +0000675 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000676
David Blaikie82e95a32014-11-19 07:49:47 +0000677 bool inserted = FunctionsBeingProcessed.insert(FI).second;
678 (void)inserted;
John McCalla729c622012-02-17 03:33:10 +0000679 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000680
Daniel Dunbar313321e2009-02-03 05:31:23 +0000681 // Compute ABI information.
Chris Lattner22326a12010-07-29 02:31:05 +0000682 getABIInfo().computeInfo(*FI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000683
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000684 // Loop over all of the computed argument and return value info. If any of
685 // them are direct or extend without a specified coerce type, specify the
686 // default now.
John McCalla729c622012-02-17 03:33:10 +0000687 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000688 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000689 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000690
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000691 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000692 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000693 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000694
John McCalla729c622012-02-17 03:33:10 +0000695 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
696 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000697
Daniel Dunbare0be8292009-02-03 00:07:12 +0000698 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000699}
700
John McCalla729c622012-02-17 03:33:10 +0000701CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Peter Collingbournef7706832014-12-12 23:41:25 +0000702 bool instanceMethod,
703 bool chainCall,
John McCalla729c622012-02-17 03:33:10 +0000704 const FunctionType::ExtInfo &info,
John McCallc56a8b32016-03-11 04:30:31 +0000705 ArrayRef<ExtParameterInfo> paramInfos,
John McCalla729c622012-02-17 03:33:10 +0000706 CanQualType resultType,
707 ArrayRef<CanQualType> argTypes,
708 RequiredArgs required) {
John McCallc56a8b32016-03-11 04:30:31 +0000709 assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
710
711 void *buffer =
712 operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
713 argTypes.size() + 1, paramInfos.size()));
714
John McCalla729c622012-02-17 03:33:10 +0000715 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
716 FI->CallingConvention = llvmCC;
717 FI->EffectiveCallingConvention = llvmCC;
718 FI->ASTCallingConvention = info.getCC();
Peter Collingbournef7706832014-12-12 23:41:25 +0000719 FI->InstanceMethod = instanceMethod;
720 FI->ChainCall = chainCall;
John McCalla729c622012-02-17 03:33:10 +0000721 FI->NoReturn = info.getNoReturn();
722 FI->ReturnsRetained = info.getProducesResult();
723 FI->Required = required;
724 FI->HasRegParm = info.getHasRegParm();
725 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000726 FI->ArgStruct = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +0000727 FI->ArgStructAlign = 0;
John McCalla729c622012-02-17 03:33:10 +0000728 FI->NumArgs = argTypes.size();
John McCallc56a8b32016-03-11 04:30:31 +0000729 FI->HasExtParameterInfos = !paramInfos.empty();
John McCalla729c622012-02-17 03:33:10 +0000730 FI->getArgsBuffer()[0].type = resultType;
731 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
732 FI->getArgsBuffer()[i + 1].type = argTypes[i];
John McCallc56a8b32016-03-11 04:30:31 +0000733 for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
734 FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
John McCalla729c622012-02-17 03:33:10 +0000735 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000736}
737
738/***/
739
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000740namespace {
741// ABIArgInfo::Expand implementation.
742
743// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
744struct TypeExpansion {
745 enum TypeExpansionKind {
746 // Elements of constant arrays are expanded recursively.
747 TEK_ConstantArray,
748 // Record fields are expanded recursively (but if record is a union, only
749 // the field with the largest size is expanded).
750 TEK_Record,
751 // For complex types, real and imaginary parts are expanded recursively.
752 TEK_Complex,
753 // All other types are not expandable.
754 TEK_None
755 };
756
757 const TypeExpansionKind Kind;
758
759 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000760 virtual ~TypeExpansion() {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000761};
762
763struct ConstantArrayExpansion : TypeExpansion {
764 QualType EltTy;
765 uint64_t NumElts;
766
767 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
768 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
769 static bool classof(const TypeExpansion *TE) {
770 return TE->Kind == TEK_ConstantArray;
771 }
772};
773
774struct RecordExpansion : TypeExpansion {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000775 SmallVector<const CXXBaseSpecifier *, 1> Bases;
776
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000777 SmallVector<const FieldDecl *, 1> Fields;
778
Reid Klecknere9f6a712014-10-31 17:10:41 +0000779 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
780 SmallVector<const FieldDecl *, 1> &&Fields)
Benjamin Kramer0bb97742016-02-13 16:00:13 +0000781 : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
782 Fields(std::move(Fields)) {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000783 static bool classof(const TypeExpansion *TE) {
784 return TE->Kind == TEK_Record;
785 }
786};
787
788struct ComplexExpansion : TypeExpansion {
789 QualType EltTy;
790
791 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
792 static bool classof(const TypeExpansion *TE) {
793 return TE->Kind == TEK_Complex;
794 }
795};
796
797struct NoExpansion : TypeExpansion {
798 NoExpansion() : TypeExpansion(TEK_None) {}
799 static bool classof(const TypeExpansion *TE) {
800 return TE->Kind == TEK_None;
801 }
802};
803} // namespace
804
805static std::unique_ptr<TypeExpansion>
806getTypeExpansion(QualType Ty, const ASTContext &Context) {
807 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
808 return llvm::make_unique<ConstantArrayExpansion>(
809 AT->getElementType(), AT->getSize().getZExtValue());
810 }
811 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000812 SmallVector<const CXXBaseSpecifier *, 1> Bases;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000813 SmallVector<const FieldDecl *, 1> Fields;
Bob Wilsone826a2a2011-08-03 05:58:22 +0000814 const RecordDecl *RD = RT->getDecl();
815 assert(!RD->hasFlexibleArrayMember() &&
816 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000817 if (RD->isUnion()) {
818 // Unions can be here only in degenerative cases - all the fields are same
819 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000820 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000821 CharUnits UnionSize = CharUnits::Zero();
822
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000823 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000824 // Skip zero length bitfields.
825 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
826 continue;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000827 assert(!FD->isBitField() &&
828 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000829 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000830 if (UnionSize < FieldSize) {
831 UnionSize = FieldSize;
832 LargestFD = FD;
833 }
834 }
835 if (LargestFD)
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000836 Fields.push_back(LargestFD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000837 } else {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000838 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
839 assert(!CXXRD->isDynamicClass() &&
840 "cannot expand vtable pointers in dynamic classes");
841 for (const CXXBaseSpecifier &BS : CXXRD->bases())
842 Bases.push_back(&BS);
843 }
844
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000845 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000846 // Skip zero length bitfields.
847 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
848 continue;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000849 assert(!FD->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000850 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000851 Fields.push_back(FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000852 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000853 }
Reid Klecknere9f6a712014-10-31 17:10:41 +0000854 return llvm::make_unique<RecordExpansion>(std::move(Bases),
855 std::move(Fields));
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000856 }
857 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
858 return llvm::make_unique<ComplexExpansion>(CT->getElementType());
859 }
860 return llvm::make_unique<NoExpansion>();
861}
862
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000863static int getExpansionSize(QualType Ty, const ASTContext &Context) {
864 auto Exp = getTypeExpansion(Ty, Context);
865 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
866 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
867 }
868 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
869 int Res = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +0000870 for (auto BS : RExp->Bases)
871 Res += getExpansionSize(BS->getType(), Context);
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000872 for (auto FD : RExp->Fields)
873 Res += getExpansionSize(FD->getType(), Context);
874 return Res;
875 }
876 if (isa<ComplexExpansion>(Exp.get()))
877 return 2;
878 assert(isa<NoExpansion>(Exp.get()));
879 return 1;
880}
881
Alexey Samsonov153004f2014-09-29 22:08:00 +0000882void
883CodeGenTypes::getExpandedTypes(QualType Ty,
884 SmallVectorImpl<llvm::Type *>::iterator &TI) {
885 auto Exp = getTypeExpansion(Ty, Context);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000886 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
887 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
Alexey Samsonov153004f2014-09-29 22:08:00 +0000888 getExpandedTypes(CAExp->EltTy, TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000889 }
890 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000891 for (auto BS : RExp->Bases)
892 getExpandedTypes(BS->getType(), TI);
893 for (auto FD : RExp->Fields)
Alexey Samsonov153004f2014-09-29 22:08:00 +0000894 getExpandedTypes(FD->getType(), TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000895 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
896 llvm::Type *EltTy = ConvertType(CExp->EltTy);
Alexey Samsonov153004f2014-09-29 22:08:00 +0000897 *TI++ = EltTy;
898 *TI++ = EltTy;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000899 } else {
900 assert(isa<NoExpansion>(Exp.get()));
Alexey Samsonov153004f2014-09-29 22:08:00 +0000901 *TI++ = ConvertType(Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000902 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000903}
904
John McCall7f416cc2015-09-08 08:05:57 +0000905static void forConstantArrayExpansion(CodeGenFunction &CGF,
906 ConstantArrayExpansion *CAE,
907 Address BaseAddr,
908 llvm::function_ref<void(Address)> Fn) {
909 CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
910 CharUnits EltAlign =
911 BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
912
913 for (int i = 0, n = CAE->NumElts; i < n; i++) {
914 llvm::Value *EltAddr =
915 CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i);
916 Fn(Address(EltAddr, EltAlign));
917 }
918}
919
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000920void CodeGenFunction::ExpandTypeFromArgs(
921 QualType Ty, LValue LV, SmallVectorImpl<llvm::Argument *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000922 assert(LV.isSimple() &&
923 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000924
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000925 auto Exp = getTypeExpansion(Ty, getContext());
926 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000927 forConstantArrayExpansion(*this, CAExp, LV.getAddress(),
928 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000929 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
930 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
John McCall7f416cc2015-09-08 08:05:57 +0000931 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000932 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000933 Address This = LV.getAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +0000934 for (const CXXBaseSpecifier *BS : RExp->Bases) {
935 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +0000936 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +0000937 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
938 /*NullCheckValue=*/false, SourceLocation());
939 LValue SubLV = MakeAddrLValue(Base, BS->getType());
940
941 // Recurse onto bases.
942 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
943 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000944 for (auto FD : RExp->Fields) {
945 // FIXME: What are the right qualifiers here?
946 LValue SubLV = EmitLValueForField(LV, FD);
947 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000948 }
John McCall7f416cc2015-09-08 08:05:57 +0000949 } else if (isa<ComplexExpansion>(Exp.get())) {
950 auto realValue = *AI++;
951 auto imagValue = *AI++;
952 EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000953 } else {
954 assert(isa<NoExpansion>(Exp.get()));
955 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000956 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000957}
958
959void CodeGenFunction::ExpandTypeToArgs(
960 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
961 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
962 auto Exp = getTypeExpansion(Ty, getContext());
963 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000964 forConstantArrayExpansion(*this, CAExp, RV.getAggregateAddress(),
965 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000966 RValue EltRV =
967 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
968 ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
John McCall7f416cc2015-09-08 08:05:57 +0000969 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000970 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000971 Address This = RV.getAggregateAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +0000972 for (const CXXBaseSpecifier *BS : RExp->Bases) {
973 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +0000974 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +0000975 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
976 /*NullCheckValue=*/false, SourceLocation());
977 RValue BaseRV = RValue::getAggregate(Base);
978
979 // Recurse onto bases.
980 ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
981 IRCallArgPos);
982 }
983
984 LValue LV = MakeAddrLValue(This, Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000985 for (auto FD : RExp->Fields) {
986 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
987 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
988 IRCallArgPos);
989 }
990 } else if (isa<ComplexExpansion>(Exp.get())) {
991 ComplexPairTy CV = RV.getComplexVal();
992 IRCallArgs[IRCallArgPos++] = CV.first;
993 IRCallArgs[IRCallArgPos++] = CV.second;
994 } else {
995 assert(isa<NoExpansion>(Exp.get()));
996 assert(RV.isScalar() &&
997 "Unexpected non-scalar rvalue during struct expansion.");
998
999 // Insert a bitcast as needed.
1000 llvm::Value *V = RV.getScalarVal();
1001 if (IRCallArgPos < IRFuncTy->getNumParams() &&
1002 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
1003 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
1004
1005 IRCallArgs[IRCallArgPos++] = V;
1006 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001007}
1008
John McCall7f416cc2015-09-08 08:05:57 +00001009/// Create a temporary allocation for the purposes of coercion.
1010static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
1011 CharUnits MinAlign) {
1012 // Don't use an alignment that's worse than what LLVM would prefer.
1013 auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty);
1014 CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
1015
1016 return CGF.CreateTempAlloca(Ty, Align);
1017}
1018
Chris Lattner895c52b2010-06-27 06:04:18 +00001019/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +00001020/// accessing some number of bytes out of it, try to gep into the struct to get
1021/// at its inner goodness. Dive as deep as possible without entering an element
1022/// with an in-memory size smaller than DstSize.
John McCall7f416cc2015-09-08 08:05:57 +00001023static Address
1024EnterStructPointerForCoercedAccess(Address SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +00001025 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +00001026 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +00001027 // We can't dive into a zero-element struct.
1028 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001029
Chris Lattner2192fe52011-07-18 04:24:23 +00001030 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001031
Chris Lattner1cd66982010-06-27 05:56:15 +00001032 // 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 +00001033 // first element is the same size as the whole struct, we can enter it. The
1034 // comparison must be made on the store size and not the alloca size. Using
1035 // the alloca size may overstate the size of the load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001036 uint64_t FirstEltSize =
James Molloy90d61012014-08-29 10:17:52 +00001037 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001038 if (FirstEltSize < DstSize &&
James Molloy90d61012014-08-29 10:17:52 +00001039 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +00001040 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001041
Chris Lattner1cd66982010-06-27 05:56:15 +00001042 // GEP into the first element.
John McCall7f416cc2015-09-08 08:05:57 +00001043 SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, CharUnits(), "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001044
Chris Lattner1cd66982010-06-27 05:56:15 +00001045 // If the first element is a struct, recurse.
John McCall7f416cc2015-09-08 08:05:57 +00001046 llvm::Type *SrcTy = SrcPtr.getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001047 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +00001048 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +00001049
1050 return SrcPtr;
1051}
1052
Chris Lattner055097f2010-06-27 06:26:04 +00001053/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
1054/// are either integers or pointers. This does a truncation of the value if it
1055/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001056///
1057/// This behaves as if the value were coerced through memory, so on big-endian
1058/// targets the high bits are preserved in a truncation, while little-endian
1059/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +00001060static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +00001061 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +00001062 CodeGenFunction &CGF) {
1063 if (Val->getType() == Ty)
1064 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001065
Chris Lattner055097f2010-06-27 06:26:04 +00001066 if (isa<llvm::PointerType>(Val->getType())) {
1067 // If this is Pointer->Pointer avoid conversion to and from int.
1068 if (isa<llvm::PointerType>(Ty))
1069 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001070
Chris Lattner055097f2010-06-27 06:26:04 +00001071 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +00001072 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +00001073 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001074
Chris Lattner2192fe52011-07-18 04:24:23 +00001075 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +00001076 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +00001077 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001078
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001079 if (Val->getType() != DestIntTy) {
1080 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
1081 if (DL.isBigEndian()) {
1082 // Preserve the high bits on big-endian targets.
1083 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +00001084 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
1085 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
1086
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001087 if (SrcSize > DstSize) {
1088 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
1089 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
1090 } else {
1091 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
1092 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
1093 }
1094 } else {
1095 // Little-endian targets preserve the low bits. No shifts required.
1096 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
1097 }
1098 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001099
Chris Lattner055097f2010-06-27 06:26:04 +00001100 if (isa<llvm::PointerType>(Ty))
1101 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
1102 return Val;
1103}
1104
Chris Lattner1cd66982010-06-27 05:56:15 +00001105
1106
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001107/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001108/// a pointer to an object of type \arg Ty, known to be aligned to
1109/// \arg SrcAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001110///
1111/// This safely handles the case when the src type is smaller than the
1112/// destination type; in this situation the values of bits which not
1113/// present in the src are undefined.
John McCall7f416cc2015-09-08 08:05:57 +00001114static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001115 CodeGenFunction &CGF) {
John McCall7f416cc2015-09-08 08:05:57 +00001116 llvm::Type *SrcTy = Src.getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001117
Chris Lattnerd200eda2010-06-28 22:51:39 +00001118 // If SrcTy and Ty are the same, just do a load.
1119 if (SrcTy == Ty)
John McCall7f416cc2015-09-08 08:05:57 +00001120 return CGF.Builder.CreateLoad(Src);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001121
Micah Villmowdd31ca12012-10-08 16:25:52 +00001122 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001123
Chris Lattner2192fe52011-07-18 04:24:23 +00001124 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001125 Src = EnterStructPointerForCoercedAccess(Src, SrcSTy, DstSize, CGF);
1126 SrcTy = Src.getType()->getElementType();
Chris Lattner1cd66982010-06-27 05:56:15 +00001127 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001128
Micah Villmowdd31ca12012-10-08 16:25:52 +00001129 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001130
Chris Lattner055097f2010-06-27 06:26:04 +00001131 // If the source and destination are integer or pointer types, just do an
1132 // extension or truncation to the desired type.
1133 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
1134 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
John McCall7f416cc2015-09-08 08:05:57 +00001135 llvm::Value *Load = CGF.Builder.CreateLoad(Src);
Chris Lattner055097f2010-06-27 06:26:04 +00001136 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
1137 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001138
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001139 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +00001140 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +00001141 // Generally SrcSize is never greater than DstSize, since this means we are
1142 // losing bits. However, this can happen in cases where the structure has
1143 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +00001144 //
Mike Stump18bb9282009-05-16 07:57:57 +00001145 // FIXME: Assert that we aren't truncating non-padding bits when have access
1146 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001147 Src = CGF.Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(Ty));
1148 return CGF.Builder.CreateLoad(Src);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001149 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001150
John McCall7f416cc2015-09-08 08:05:57 +00001151 // Otherwise do coercion through memory. This is stupid, but simple.
1152 Address Tmp = CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment());
1153 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1154 Address SrcCasted = CGF.Builder.CreateBitCast(Src, CGF.Int8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001155 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
1156 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
John McCall7f416cc2015-09-08 08:05:57 +00001157 false);
1158 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001159}
1160
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001161// Function to store a first-class aggregate into memory. We prefer to
1162// store the elements rather than the aggregate to be more friendly to
1163// fast-isel.
1164// FIXME: Do we need to recurse here?
1165static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
John McCall7f416cc2015-09-08 08:05:57 +00001166 Address Dest, bool DestIsVolatile) {
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001167 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +00001168 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001169 dyn_cast<llvm::StructType>(Val->getType())) {
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001170 const llvm::StructLayout *Layout =
1171 CGF.CGM.getDataLayout().getStructLayout(STy);
1172
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001173 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00001174 auto EltOffset = CharUnits::fromQuantity(Layout->getElementOffset(i));
1175 Address EltPtr = CGF.Builder.CreateStructGEP(Dest, i, EltOffset);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001176 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
John McCall7f416cc2015-09-08 08:05:57 +00001177 CGF.Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001178 }
1179 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001180 CGF.Builder.CreateStore(Val, Dest, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001181 }
1182}
1183
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001184/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001185/// where the source and destination may have different types. The
1186/// destination is known to be aligned to \arg DstAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001187///
1188/// This safely handles the case when the src type is larger than the
1189/// destination type; the upper bits of the src will be lost.
1190static void CreateCoercedStore(llvm::Value *Src,
John McCall7f416cc2015-09-08 08:05:57 +00001191 Address Dst,
Anders Carlsson17490832009-12-24 20:40:36 +00001192 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001193 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001194 llvm::Type *SrcTy = Src->getType();
John McCall7f416cc2015-09-08 08:05:57 +00001195 llvm::Type *DstTy = Dst.getType()->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +00001196 if (SrcTy == DstTy) {
John McCall7f416cc2015-09-08 08:05:57 +00001197 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattnerd200eda2010-06-28 22:51:39 +00001198 return;
1199 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001200
Micah Villmowdd31ca12012-10-08 16:25:52 +00001201 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001202
Chris Lattner2192fe52011-07-18 04:24:23 +00001203 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001204 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy, SrcSize, CGF);
1205 DstTy = Dst.getType()->getElementType();
Chris Lattner895c52b2010-06-27 06:04:18 +00001206 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001207
Chris Lattner055097f2010-06-27 06:26:04 +00001208 // If the source and destination are integer or pointer types, just do an
1209 // extension or truncation to the desired type.
1210 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1211 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1212 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
John McCall7f416cc2015-09-08 08:05:57 +00001213 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattner055097f2010-06-27 06:26:04 +00001214 return;
1215 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001216
Micah Villmowdd31ca12012-10-08 16:25:52 +00001217 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001218
Daniel Dunbar313321e2009-02-03 05:31:23 +00001219 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001220 if (SrcSize <= DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00001221 Dst = CGF.Builder.CreateBitCast(Dst, llvm::PointerType::getUnqual(SrcTy));
1222 BuildAggStore(CGF, Src, Dst, DstIsVolatile);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001223 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001224 // Otherwise do coercion through memory. This is stupid, but
1225 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001226
1227 // Generally SrcSize is never greater than DstSize, since this means we are
1228 // losing bits. However, this can happen in cases where the structure has
1229 // additional padding, for example due to a user specified alignment.
1230 //
1231 // FIXME: Assert that we aren't truncating non-padding bits when have access
1232 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001233 Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
1234 CGF.Builder.CreateStore(Src, Tmp);
1235 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1236 Address DstCasted = CGF.Builder.CreateBitCast(Dst, CGF.Int8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001237 CGF.Builder.CreateMemCpy(DstCasted, Casted,
1238 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
John McCall7f416cc2015-09-08 08:05:57 +00001239 false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001240 }
1241}
1242
John McCall7f416cc2015-09-08 08:05:57 +00001243static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
1244 const ABIArgInfo &info) {
1245 if (unsigned offset = info.getDirectOffset()) {
1246 addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
1247 addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
1248 CharUnits::fromQuantity(offset));
1249 addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
1250 }
1251 return addr;
1252}
1253
Alexey Samsonov153004f2014-09-29 22:08:00 +00001254namespace {
1255
1256/// Encapsulates information about the way function arguments from
1257/// CGFunctionInfo should be passed to actual LLVM IR function.
1258class ClangToLLVMArgMapping {
1259 static const unsigned InvalidIndex = ~0U;
1260 unsigned InallocaArgNo;
1261 unsigned SRetArgNo;
1262 unsigned TotalIRArgs;
1263
1264 /// Arguments of LLVM IR function corresponding to single Clang argument.
1265 struct IRArgs {
1266 unsigned PaddingArgIndex;
1267 // Argument is expanded to IR arguments at positions
1268 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1269 unsigned FirstArgIndex;
1270 unsigned NumberOfArgs;
1271
1272 IRArgs()
1273 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1274 NumberOfArgs(0) {}
1275 };
1276
1277 SmallVector<IRArgs, 8> ArgInfo;
1278
1279public:
1280 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1281 bool OnlyRequiredArgs = false)
1282 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1283 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1284 construct(Context, FI, OnlyRequiredArgs);
1285 }
1286
1287 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1288 unsigned getInallocaArgNo() const {
1289 assert(hasInallocaArg());
1290 return InallocaArgNo;
1291 }
1292
1293 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1294 unsigned getSRetArgNo() const {
1295 assert(hasSRetArg());
1296 return SRetArgNo;
1297 }
1298
1299 unsigned totalIRArgs() const { return TotalIRArgs; }
1300
1301 bool hasPaddingArg(unsigned ArgNo) const {
1302 assert(ArgNo < ArgInfo.size());
1303 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1304 }
1305 unsigned getPaddingArgNo(unsigned ArgNo) const {
1306 assert(hasPaddingArg(ArgNo));
1307 return ArgInfo[ArgNo].PaddingArgIndex;
1308 }
1309
1310 /// Returns index of first IR argument corresponding to ArgNo, and their
1311 /// quantity.
1312 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1313 assert(ArgNo < ArgInfo.size());
1314 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1315 ArgInfo[ArgNo].NumberOfArgs);
1316 }
1317
1318private:
1319 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1320 bool OnlyRequiredArgs);
1321};
1322
1323void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1324 const CGFunctionInfo &FI,
1325 bool OnlyRequiredArgs) {
1326 unsigned IRArgNo = 0;
1327 bool SwapThisWithSRet = false;
1328 const ABIArgInfo &RetAI = FI.getReturnInfo();
1329
1330 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1331 SwapThisWithSRet = RetAI.isSRetAfterThis();
1332 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1333 }
1334
1335 unsigned ArgNo = 0;
1336 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1337 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1338 ++I, ++ArgNo) {
1339 assert(I != FI.arg_end());
1340 QualType ArgType = I->type;
1341 const ABIArgInfo &AI = I->info;
1342 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1343 auto &IRArgs = ArgInfo[ArgNo];
1344
1345 if (AI.getPaddingType())
1346 IRArgs.PaddingArgIndex = IRArgNo++;
1347
1348 switch (AI.getKind()) {
1349 case ABIArgInfo::Extend:
1350 case ABIArgInfo::Direct: {
1351 // FIXME: handle sseregparm someday...
1352 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1353 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1354 IRArgs.NumberOfArgs = STy->getNumElements();
1355 } else {
1356 IRArgs.NumberOfArgs = 1;
1357 }
1358 break;
1359 }
1360 case ABIArgInfo::Indirect:
1361 IRArgs.NumberOfArgs = 1;
1362 break;
1363 case ABIArgInfo::Ignore:
1364 case ABIArgInfo::InAlloca:
1365 // ignore and inalloca doesn't have matching LLVM parameters.
1366 IRArgs.NumberOfArgs = 0;
1367 break;
John McCallf26e73d2016-03-11 04:30:43 +00001368 case ABIArgInfo::CoerceAndExpand:
1369 IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
1370 break;
1371 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001372 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1373 break;
1374 }
Alexey Samsonov153004f2014-09-29 22:08:00 +00001375
1376 if (IRArgs.NumberOfArgs > 0) {
1377 IRArgs.FirstArgIndex = IRArgNo;
1378 IRArgNo += IRArgs.NumberOfArgs;
1379 }
1380
1381 // Skip over the sret parameter when it comes second. We already handled it
1382 // above.
1383 if (IRArgNo == 1 && SwapThisWithSRet)
1384 IRArgNo++;
1385 }
1386 assert(ArgNo == ArgInfo.size());
1387
1388 if (FI.usesInAlloca())
1389 InallocaArgNo = IRArgNo++;
1390
1391 TotalIRArgs = IRArgNo;
1392}
1393} // namespace
1394
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001395/***/
1396
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001397bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001398 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00001399}
1400
Tim Northovere77cc392014-03-29 13:28:05 +00001401bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1402 return ReturnTypeUsesSRet(FI) &&
1403 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1404}
1405
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001406bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1407 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1408 switch (BT->getKind()) {
1409 default:
1410 return false;
1411 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +00001412 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001413 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +00001414 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001415 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +00001416 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001417 }
1418 }
1419
1420 return false;
1421}
1422
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001423bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1424 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1425 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1426 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +00001427 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001428 }
1429 }
1430
1431 return false;
1432}
1433
Chris Lattnera5f58b02011-07-09 17:41:47 +00001434llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +00001435 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1436 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +00001437}
1438
Chris Lattnera5f58b02011-07-09 17:41:47 +00001439llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +00001440CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001441
David Blaikie82e95a32014-11-19 07:49:47 +00001442 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1443 (void)Inserted;
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001444 assert(Inserted && "Recursively being processed?");
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001445
Alexey Samsonov153004f2014-09-29 22:08:00 +00001446 llvm::Type *resultType = nullptr;
John McCall85dd2c52011-05-15 02:19:42 +00001447 const ABIArgInfo &retAI = FI.getReturnInfo();
1448 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +00001449 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +00001450 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +00001451
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001452 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001453 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +00001454 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +00001455 break;
1456
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001457 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001458 if (retAI.getInAllocaSRet()) {
1459 // sret things on win32 aren't void, they return the sret pointer.
1460 QualType ret = FI.getReturnType();
1461 llvm::Type *ty = ConvertType(ret);
1462 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1463 resultType = llvm::PointerType::get(ty, addressSpace);
1464 } else {
1465 resultType = llvm::Type::getVoidTy(getLLVMContext());
1466 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001467 break;
1468
John McCall7f416cc2015-09-08 08:05:57 +00001469 case ABIArgInfo::Indirect:
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001470 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +00001471 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001472 break;
John McCallf26e73d2016-03-11 04:30:43 +00001473
1474 case ABIArgInfo::CoerceAndExpand:
1475 resultType = retAI.getUnpaddedCoerceAndExpandType();
1476 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001477 }
Mike Stump11289f42009-09-09 15:08:12 +00001478
Alexey Samsonov153004f2014-09-29 22:08:00 +00001479 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1480 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1481
1482 // Add type for sret argument.
1483 if (IRFunctionArgs.hasSRetArg()) {
1484 QualType Ret = FI.getReturnType();
1485 llvm::Type *Ty = ConvertType(Ret);
1486 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1487 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1488 llvm::PointerType::get(Ty, AddressSpace);
1489 }
1490
1491 // Add type for inalloca argument.
1492 if (IRFunctionArgs.hasInallocaArg()) {
1493 auto ArgStruct = FI.getArgStruct();
1494 assert(ArgStruct);
1495 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1496 }
1497
John McCallc818bbb2012-12-07 07:03:17 +00001498 // Add in all of the required arguments.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001499 unsigned ArgNo = 0;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00001500 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1501 ie = it + FI.getNumRequiredArgs();
Alexey Samsonov153004f2014-09-29 22:08:00 +00001502 for (; it != ie; ++it, ++ArgNo) {
1503 const ABIArgInfo &ArgInfo = it->info;
Mike Stump11289f42009-09-09 15:08:12 +00001504
Rafael Espindolafad28de2012-10-24 01:59:00 +00001505 // Insert a padding type to ensure proper alignment.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001506 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1507 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1508 ArgInfo.getPaddingType();
Rafael Espindolafad28de2012-10-24 01:59:00 +00001509
Alexey Samsonov153004f2014-09-29 22:08:00 +00001510 unsigned FirstIRArg, NumIRArgs;
1511 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1512
1513 switch (ArgInfo.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001514 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001515 case ABIArgInfo::InAlloca:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001516 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001517 break;
1518
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001519 case ABIArgInfo::Indirect: {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001520 assert(NumIRArgs == 1);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001521 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +00001522 llvm::Type *LTy = ConvertTypeForMem(it->type);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001523 ArgTypes[FirstIRArg] = LTy->getPointerTo();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001524 break;
1525 }
1526
1527 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +00001528 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001529 // Fast-isel and the optimizer generally like scalar values better than
1530 // FCAs, so we flatten them if this is safe to do for this argument.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001531 llvm::Type *argType = ArgInfo.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +00001532 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001533 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1534 assert(NumIRArgs == st->getNumElements());
John McCall85dd2c52011-05-15 02:19:42 +00001535 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
Alexey Samsonov153004f2014-09-29 22:08:00 +00001536 ArgTypes[FirstIRArg + i] = st->getElementType(i);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001537 } else {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001538 assert(NumIRArgs == 1);
1539 ArgTypes[FirstIRArg] = argType;
Chris Lattner3dd716c2010-06-28 23:44:11 +00001540 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001541 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001542 }
Mike Stump11289f42009-09-09 15:08:12 +00001543
John McCallf26e73d2016-03-11 04:30:43 +00001544 case ABIArgInfo::CoerceAndExpand: {
1545 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1546 for (auto EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
1547 *ArgTypesIter++ = EltTy;
1548 }
1549 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1550 break;
1551 }
1552
Daniel Dunbard3674e62008-09-11 01:48:57 +00001553 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001554 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1555 getExpandedTypes(it->type, ArgTypesIter);
1556 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001557 break;
1558 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001559 }
1560
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001561 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1562 assert(Erased && "Not in set?");
Alexey Samsonov153004f2014-09-29 22:08:00 +00001563
1564 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001565}
1566
Chris Lattner2192fe52011-07-18 04:24:23 +00001567llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001568 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001569 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001570
Chris Lattner8806e322011-07-10 00:18:59 +00001571 if (!isFuncTypeConvertible(FPT))
1572 return llvm::StructType::get(getLLVMContext());
1573
1574 const CGFunctionInfo *Info;
1575 if (isa<CXXDestructorDecl>(MD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001576 Info =
1577 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
Chris Lattner8806e322011-07-10 00:18:59 +00001578 else
John McCalla729c622012-02-17 03:33:10 +00001579 Info = &arrangeCXXMethodDeclaration(MD);
1580 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001581}
1582
Samuel Antao798f11c2015-11-23 22:04:44 +00001583static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
1584 llvm::AttrBuilder &FuncAttrs,
1585 const FunctionProtoType *FPT) {
1586 if (!FPT)
1587 return;
1588
1589 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
1590 FPT->isNothrow(Ctx))
1591 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1592}
1593
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00001594void CodeGenModule::ConstructAttributeList(
1595 StringRef Name, const CGFunctionInfo &FI, CGCalleeInfo CalleeInfo,
1596 AttributeListType &PAL, unsigned &CallingConv, bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001597 llvm::AttrBuilder FuncAttrs;
1598 llvm::AttrBuilder RetAttrs;
Paul Robinson08556952014-12-11 20:14:04 +00001599 bool HasOptnone = false;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001600
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001601 CallingConv = FI.getEffectiveCallingConvention();
1602
John McCallab26cfa2010-02-05 21:31:56 +00001603 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001604 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001605
Samuel Antao798f11c2015-11-23 22:04:44 +00001606 // If we have information about the function prototype, we can learn
1607 // attributes form there.
1608 AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
1609 CalleeInfo.getCalleeFunctionProtoType());
1610
1611 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
1612
Amjad Aboudfaea5602016-03-07 14:22:46 +00001613 bool HasAnyX86InterruptAttr = false;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001614 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001615 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001616 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001617 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001618 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001619 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001620 if (TargetDecl->hasAttr<NoReturnAttr>())
1621 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001622 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1623 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smithdebc59d2013-01-30 05:45:05 +00001624
1625 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
Samuel Antao798f11c2015-11-23 22:04:44 +00001626 AddAttributesFromFunctionProtoType(
1627 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
Richard Smith49af6292013-03-05 08:30:04 +00001628 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1629 // These attributes are not inherited by overloads.
1630 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1631 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001632 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001633 }
1634
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001635 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
Eric Christopherbf005ec2011-08-15 22:38:22 +00001636 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001637 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1638 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001639 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001640 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1641 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001642 } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
1643 FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
1644 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001645 }
David Majnemer631a90b2015-02-04 07:23:21 +00001646 if (TargetDecl->hasAttr<RestrictAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001647 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001648 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1649 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Paul Robinson08556952014-12-11 20:14:04 +00001650
Amjad Aboudfaea5602016-03-07 14:22:46 +00001651 HasAnyX86InterruptAttr = TargetDecl->hasAttr<AnyX86InterruptAttr>();
Paul Robinson08556952014-12-11 20:14:04 +00001652 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001653 }
1654
Paul Robinson08556952014-12-11 20:14:04 +00001655 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1656 if (!HasOptnone) {
1657 if (CodeGenOpts.OptimizeSize)
1658 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1659 if (CodeGenOpts.OptimizeSize == 2)
1660 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1661 }
1662
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001663 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001664 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001665 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001666 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001667 if (CodeGenOpts.EnableSegmentedStacks &&
1668 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001669 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001670
Bill Wendling2f81db62013-02-22 20:53:29 +00001671 if (AttrOnCallSite) {
1672 // Attributes that should go on the call site only.
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00001673 if (!CodeGenOpts.SimplifyLibCalls ||
1674 CodeGenOpts.isNoBuiltinFunc(Name.data()))
Bill Wendling2f81db62013-02-22 20:53:29 +00001675 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00001676 if (!CodeGenOpts.TrapFuncName.empty())
1677 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
Bill Wendling706469b2013-02-28 22:49:57 +00001678 } else {
1679 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001680 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001681 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001682 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001683 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001684 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001685 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001686 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001687 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001688 }
1689
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001690 bool DisableTailCalls =
Amjad Aboudfaea5602016-03-07 14:22:46 +00001691 CodeGenOpts.DisableTailCalls || HasAnyX86InterruptAttr ||
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001692 (TargetDecl && TargetDecl->hasAttr<DisableTailCallsAttr>());
Amjad Aboudfaea5602016-03-07 14:22:46 +00001693 FuncAttrs.addAttribute(
1694 "disable-tail-calls",
1695 llvm::toStringRef(DisableTailCalls));
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001696
Bill Wendlingdabafea2013-03-13 22:24:33 +00001697 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001698 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001699 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001700 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001701 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001702 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001703 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001704 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001705 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001706 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001707 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001708 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001709
Akira Hatanakaaecca042015-09-11 18:55:09 +00001710 if (CodeGenOpts.StackRealignment)
1711 FuncAttrs.addAttribute("stackrealign");
Eric Christopher70c16652015-03-25 23:14:47 +00001712
Eric Christopher11acf732015-06-12 01:35:52 +00001713 // Add target-cpu and target-features attributes to functions. If
1714 // we have a decl for the function and it has a target attribute then
1715 // parse that and add it to the feature set.
1716 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
Eric Christopher11acf732015-06-12 01:35:52 +00001717 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
Eric Christopherb57804a2015-09-01 22:03:56 +00001718 if (FD && FD->hasAttr<TargetAttr>()) {
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001719 llvm::StringMap<bool> FeatureMap;
Eric Christopher2b90a642015-11-11 23:05:08 +00001720 getFunctionFeatureMap(FeatureMap, FD);
Eric Christopher11acf732015-06-12 01:35:52 +00001721
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001722 // Produce the canonical string for this set of features.
1723 std::vector<std::string> Features;
1724 for (llvm::StringMap<bool>::const_iterator it = FeatureMap.begin(),
1725 ie = FeatureMap.end();
1726 it != ie; ++it)
1727 Features.push_back((it->second ? "+" : "-") + it->first().str());
Eric Christopher2249b812015-07-01 00:08:29 +00001728
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001729 // Now add the target-cpu and target-features to the function.
Eric Christopher2b90a642015-11-11 23:05:08 +00001730 // While we populated the feature map above, we still need to
1731 // get and parse the target attribute so we can get the cpu for
1732 // the function.
1733 const auto *TD = FD->getAttr<TargetAttr>();
1734 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
1735 if (ParsedAttr.second != "")
1736 TargetCPU = ParsedAttr.second;
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001737 if (TargetCPU != "")
1738 FuncAttrs.addAttribute("target-cpu", TargetCPU);
1739 if (!Features.empty()) {
1740 std::sort(Features.begin(), Features.end());
1741 FuncAttrs.addAttribute(
1742 "target-features",
1743 llvm::join(Features.begin(), Features.end(), ","));
1744 }
1745 } else {
1746 // Otherwise just add the existing target cpu and target features to the
1747 // function.
1748 std::vector<std::string> &Features = getTarget().getTargetOpts().Features;
1749 if (TargetCPU != "")
1750 FuncAttrs.addAttribute("target-cpu", TargetCPU);
1751 if (!Features.empty()) {
1752 std::sort(Features.begin(), Features.end());
1753 FuncAttrs.addAttribute(
1754 "target-features",
1755 llvm::join(Features.begin(), Features.end(), ","));
1756 }
Eric Christopher70c16652015-03-25 23:14:47 +00001757 }
Bill Wendling985d1c52013-02-15 21:30:01 +00001758 }
1759
Justin Lebarddd97fa2016-02-24 21:55:11 +00001760 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
1761 // Conservatively, mark all functions and calls in CUDA as convergent
1762 // (meaning, they may call an intrinsically convergent op, such as
1763 // __syncthreads(), and so can't have certain optimizations applied around
1764 // them). LLVM will remove this attribute where it safely can.
1765 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
1766 }
1767
Alexey Samsonov153004f2014-09-29 22:08:00 +00001768 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001769
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001770 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001771 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001772 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001773 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001774 if (RetTy->hasSignedIntegerRepresentation())
1775 RetAttrs.addAttribute(llvm::Attribute::SExt);
1776 else if (RetTy->hasUnsignedIntegerRepresentation())
1777 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001778 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001779 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001780 if (RetAI.getInReg())
1781 RetAttrs.addAttribute(llvm::Attribute::InReg);
1782 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001783 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001784 break;
1785
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001786 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001787 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001788 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001789 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1790 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001791 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001792 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001793
John McCallf26e73d2016-03-11 04:30:43 +00001794 case ABIArgInfo::CoerceAndExpand:
1795 break;
1796
Daniel Dunbard3674e62008-09-11 01:48:57 +00001797 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001798 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001799 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001800
Hal Finkela2347ba2014-07-18 15:52:10 +00001801 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1802 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00001803 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00001804 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1805 .getQuantity());
1806 else if (getContext().getTargetAddressSpace(PTy) == 0)
1807 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1808 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001809
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001810 // Attach return attributes.
1811 if (RetAttrs.hasAttributes()) {
1812 PAL.push_back(llvm::AttributeSet::get(
1813 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1814 }
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001815
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001816 // Attach attributes to sret.
1817 if (IRFunctionArgs.hasSRetArg()) {
1818 llvm::AttrBuilder SRETAttrs;
1819 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
1820 if (RetAI.getInReg())
1821 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1822 PAL.push_back(llvm::AttributeSet::get(
1823 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1824 }
1825
1826 // Attach attributes to inalloca argument.
1827 if (IRFunctionArgs.hasInallocaArg()) {
1828 llvm::AttrBuilder Attrs;
1829 Attrs.addAttribute(llvm::Attribute::InAlloca);
1830 PAL.push_back(llvm::AttributeSet::get(
1831 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1832 }
1833
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001834 unsigned ArgNo = 0;
1835 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1836 E = FI.arg_end();
1837 I != E; ++I, ++ArgNo) {
1838 QualType ParamType = I->type;
1839 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001840 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001841
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001842 // Add attribute for padding argument, if necessary.
1843 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendling290d9522013-01-27 02:46:53 +00001844 if (AI.getPaddingInReg())
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001845 PAL.push_back(llvm::AttributeSet::get(
1846 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1847 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001848 }
1849
John McCall39ec71f2010-03-27 00:47:27 +00001850 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1851 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001852 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001853 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001854 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001855 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001856 Attrs.addAttribute(llvm::Attribute::SExt);
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00001857 else if (ParamType->isUnsignedIntegerOrEnumerationType()) {
1858 if (getTypes().getABIInfo().shouldSignExtUnsignedType(ParamType))
1859 Attrs.addAttribute(llvm::Attribute::SExt);
1860 else
1861 Attrs.addAttribute(llvm::Attribute::ZExt);
1862 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001863 // FALL THROUGH
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001864 case ABIArgInfo::Direct:
Peter Collingbournef7706832014-12-12 23:41:25 +00001865 if (ArgNo == 0 && FI.isChainCall())
1866 Attrs.addAttribute(llvm::Attribute::Nest);
1867 else if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001868 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001869 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001870
James Y Knight71608572015-08-21 18:19:06 +00001871 case ABIArgInfo::Indirect: {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001872 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001873 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001874
Anders Carlsson20759ad2009-09-16 15:53:40 +00001875 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001876 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001877
John McCall7f416cc2015-09-08 08:05:57 +00001878 CharUnits Align = AI.getIndirectAlign();
James Y Knight71608572015-08-21 18:19:06 +00001879
1880 // In a byval argument, it is important that the required
1881 // alignment of the type is honored, as LLVM might be creating a
1882 // *new* stack object, and needs to know what alignment to give
1883 // it. (Sometimes it can deduce a sensible alignment on its own,
1884 // but not if clang decides it must emit a packed struct, or the
1885 // user specifies increased alignment requirements.)
1886 //
1887 // This is different from indirect *not* byval, where the object
1888 // exists already, and the align attribute is purely
1889 // informative.
John McCall7f416cc2015-09-08 08:05:57 +00001890 assert(!Align.isZero());
James Y Knight71608572015-08-21 18:19:06 +00001891
John McCall7f416cc2015-09-08 08:05:57 +00001892 // For now, only add this when we have a byval argument.
1893 // TODO: be less lazy about updating test cases.
1894 if (AI.getIndirectByVal())
1895 Attrs.addAlignmentAttr(Align.getQuantity());
Bill Wendlinga7912f82012-10-10 07:36:56 +00001896
Daniel Dunbarc2304432009-03-18 19:51:01 +00001897 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001898 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1899 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001900 break;
James Y Knight71608572015-08-21 18:19:06 +00001901 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001902 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001903 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00001904 case ABIArgInfo::CoerceAndExpand:
1905 break;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001906
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001907 case ABIArgInfo::InAlloca:
1908 // inalloca disables readnone and readonly.
1909 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1910 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001911 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001912 }
Mike Stump11289f42009-09-09 15:08:12 +00001913
Hal Finkela2347ba2014-07-18 15:52:10 +00001914 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1915 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00001916 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00001917 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1918 .getQuantity());
1919 else if (getContext().getTargetAddressSpace(PTy) == 0)
1920 Attrs.addAttribute(llvm::Attribute::NonNull);
1921 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001922
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001923 if (Attrs.hasAttributes()) {
1924 unsigned FirstIRArg, NumIRArgs;
1925 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1926 for (unsigned i = 0; i < NumIRArgs; i++)
1927 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
1928 FirstIRArg + i + 1, Attrs));
1929 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001930 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001931 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001932
Bill Wendlinga7912f82012-10-10 07:36:56 +00001933 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001934 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001935 AttributeSet::get(getLLVMContext(),
1936 llvm::AttributeSet::FunctionIndex,
1937 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001938}
1939
John McCalla738c252011-03-09 04:27:21 +00001940/// An argument came in as a promoted argument; demote it back to its
1941/// declared type.
1942static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1943 const VarDecl *var,
1944 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001945 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001946
1947 // This can happen with promotions that actually don't change the
1948 // underlying type, like the enum promotions.
1949 if (value->getType() == varType) return value;
1950
1951 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1952 && "unexpected promotion type");
1953
1954 if (isa<llvm::IntegerType>(varType))
1955 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1956
1957 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1958}
1959
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001960/// Returns the attribute (either parameter attribute, or function
1961/// attribute), which declares argument ArgNo to be non-null.
1962static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
1963 QualType ArgType, unsigned ArgNo) {
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001964 // FIXME: __attribute__((nonnull)) can also be applied to:
1965 // - references to pointers, where the pointee is known to be
1966 // nonnull (apparently a Clang extension)
1967 // - transparent unions containing pointers
1968 // In the former case, LLVM IR cannot represent the constraint. In
1969 // the latter case, we have no guarantee that the transparent union
1970 // is in fact passed as a pointer.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001971 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
1972 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001973 // First, check attribute on parameter itself.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001974 if (PVD) {
1975 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
1976 return ParmNNAttr;
1977 }
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001978 // Check function attributes.
1979 if (!FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001980 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001981 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001982 if (NNAttr->isNonNull(ArgNo))
1983 return NNAttr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001984 }
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001985 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001986}
1987
Daniel Dunbard931a872009-02-02 22:03:45 +00001988void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1989 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00001990 const FunctionArgList &Args) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00001991 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
1992 // Naked functions don't have prologues.
1993 return;
1994
John McCallcaa19452009-07-28 01:00:58 +00001995 // If this is an implicit-return-zero function, go ahead and
1996 // initialize the return value. TODO: it might be nice to have
1997 // a more general mechanism for this that didn't require synthesized
1998 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00001999 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00002000 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00002001 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00002002 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00002003 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00002004 Builder.CreateStore(Zero, ReturnValue);
2005 }
2006 }
2007
Mike Stump18bb9282009-05-16 07:57:57 +00002008 // FIXME: We no longer need the types from FunctionArgList; lift up and
2009 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00002010
Alexey Samsonov153004f2014-09-29 22:08:00 +00002011 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002012 // Flattened function arguments.
2013 SmallVector<llvm::Argument *, 16> FnArgs;
2014 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
2015 for (auto &Arg : Fn->args()) {
2016 FnArgs.push_back(&Arg);
2017 }
2018 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00002019
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002020 // If we're using inalloca, all the memory arguments are GEPs off of the last
2021 // parameter, which is a pointer to the complete memory area.
John McCall7f416cc2015-09-08 08:05:57 +00002022 Address ArgStruct = Address::invalid();
2023 const llvm::StructLayout *ArgStructLayout = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002024 if (IRFunctionArgs.hasInallocaArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00002025 ArgStructLayout = CGM.getDataLayout().getStructLayout(FI.getArgStruct());
2026 ArgStruct = Address(FnArgs[IRFunctionArgs.getInallocaArgNo()],
2027 FI.getArgStructAlignment());
2028
2029 assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002030 }
2031
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002032 // Name the struct return parameter.
2033 if (IRFunctionArgs.hasSRetArg()) {
2034 auto AI = FnArgs[IRFunctionArgs.getSRetArgNo()];
Daniel Dunbar613855c2008-09-09 23:27:19 +00002035 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00002036 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00002037 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002038 }
Mike Stump11289f42009-09-09 15:08:12 +00002039
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002040 // Track if we received the parameter as a pointer (indirect, byval, or
2041 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
2042 // into a local alloca for us.
John McCall7f416cc2015-09-08 08:05:57 +00002043 SmallVector<ParamValue, 16> ArgVals;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002044 ArgVals.reserve(Args.size());
2045
Reid Kleckner739756c2013-12-04 19:23:12 +00002046 // Create a pointer value for every parameter declaration. This usually
2047 // entails copying one or more LLVM IR arguments into an alloca. Don't push
2048 // any cleanups or do anything that might unwind. We do that separately, so
2049 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002050 assert(FI.arg_size() == Args.size() &&
2051 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002052 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002053 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002054 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00002055 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00002056 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002057 QualType Ty = info_it->type;
2058 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002059
John McCalla738c252011-03-09 04:27:21 +00002060 bool isPromoted =
2061 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
2062
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002063 unsigned FirstIRArg, NumIRArgs;
2064 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002065
Daniel Dunbard3674e62008-09-11 01:48:57 +00002066 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002067 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002068 assert(NumIRArgs == 0);
John McCall7f416cc2015-09-08 08:05:57 +00002069 auto FieldIndex = ArgI.getInAllocaFieldIndex();
2070 CharUnits FieldOffset =
2071 CharUnits::fromQuantity(ArgStructLayout->getElementOffset(FieldIndex));
2072 Address V = Builder.CreateStructGEP(ArgStruct, FieldIndex, FieldOffset,
2073 Arg->getName());
2074 ArgVals.push_back(ParamValue::forIndirect(V));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002075 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002076 }
2077
Daniel Dunbar747865a2009-02-05 09:16:39 +00002078 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002079 assert(NumIRArgs == 1);
John McCall7f416cc2015-09-08 08:05:57 +00002080 Address ParamAddr = Address(FnArgs[FirstIRArg], ArgI.getIndirectAlign());
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002081
John McCall47fb9502013-03-07 21:37:08 +00002082 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002083 // Aggregates and complex variables are accessed by reference. All we
John McCall7f416cc2015-09-08 08:05:57 +00002084 // need to do is realign the value, if requested.
2085 Address V = ParamAddr;
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002086 if (ArgI.getIndirectRealign()) {
John McCall7f416cc2015-09-08 08:05:57 +00002087 Address AlignedTemp = CreateMemTemp(Ty, "coerce");
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002088
2089 // Copy from the incoming argument pointer to the temporary with the
2090 // appropriate alignment.
2091 //
2092 // FIXME: We should have a common utility for generating an aggregate
2093 // copy.
Ken Dyck705ba072011-01-19 01:58:38 +00002094 CharUnits Size = getContext().getTypeSizeInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002095 auto SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity());
2096 Address Dst = Builder.CreateBitCast(AlignedTemp, Int8PtrTy);
2097 Address Src = Builder.CreateBitCast(ParamAddr, Int8PtrTy);
2098 Builder.CreateMemCpy(Dst, Src, SizeVal, false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002099 V = AlignedTemp;
2100 }
John McCall7f416cc2015-09-08 08:05:57 +00002101 ArgVals.push_back(ParamValue::forIndirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00002102 } else {
2103 // Load scalar value from indirect argument.
John McCall7f416cc2015-09-08 08:05:57 +00002104 llvm::Value *V =
2105 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00002106
2107 if (isPromoted)
2108 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002109 ArgVals.push_back(ParamValue::forDirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00002110 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002111 break;
2112 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002113
2114 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00002115 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00002116
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002117 // If we have the trivial case, handle it with no muss and fuss.
2118 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002119 ArgI.getCoerceToType() == ConvertType(Ty) &&
2120 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002121 assert(NumIRArgs == 1);
2122 auto AI = FnArgs[FirstIRArg];
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002123 llvm::Value *V = AI;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002124
Hal Finkel48d53e22014-07-19 01:41:07 +00002125 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002126 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
2127 PVD->getFunctionScopeIndex()))
Hal Finkel82504f02014-07-11 17:35:21 +00002128 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2129 AI->getArgNo() + 1,
2130 llvm::Attribute::NonNull));
2131
Hal Finkel48d53e22014-07-19 01:41:07 +00002132 QualType OTy = PVD->getOriginalType();
2133 if (const auto *ArrTy =
2134 getContext().getAsConstantArrayType(OTy)) {
2135 // A C99 array parameter declaration with the static keyword also
2136 // indicates dereferenceability, and if the size is constant we can
2137 // use the dereferenceable attribute (which requires the size in
2138 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00002139 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00002140 QualType ETy = ArrTy->getElementType();
2141 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
2142 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
2143 ArrSize) {
2144 llvm::AttrBuilder Attrs;
2145 Attrs.addDereferenceableAttr(
2146 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
2147 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2148 AI->getArgNo() + 1, Attrs));
2149 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
2150 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2151 AI->getArgNo() + 1,
2152 llvm::Attribute::NonNull));
2153 }
2154 }
2155 } else if (const auto *ArrTy =
2156 getContext().getAsVariableArrayType(OTy)) {
2157 // For C99 VLAs with the static keyword, we don't know the size so
2158 // we can't use the dereferenceable attribute, but in addrspace(0)
2159 // we know that it must be nonnull.
2160 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
2161 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
2162 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2163 AI->getArgNo() + 1,
2164 llvm::Attribute::NonNull));
2165 }
Hal Finkel1b0d24e2014-10-02 21:21:25 +00002166
2167 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
2168 if (!AVAttr)
2169 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
2170 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
2171 if (AVAttr) {
2172 llvm::Value *AlignmentValue =
2173 EmitScalarExpr(AVAttr->getAlignment());
2174 llvm::ConstantInt *AlignmentCI =
2175 cast<llvm::ConstantInt>(AlignmentValue);
2176 unsigned Alignment =
2177 std::min((unsigned) AlignmentCI->getZExtValue(),
2178 +llvm::Value::MaximumAlignment);
2179
2180 llvm::AttrBuilder Attrs;
2181 Attrs.addAlignmentAttr(Alignment);
2182 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2183 AI->getArgNo() + 1, Attrs));
2184 }
Hal Finkel48d53e22014-07-19 01:41:07 +00002185 }
2186
Bill Wendling507c3512012-10-16 05:23:44 +00002187 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00002188 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2189 AI->getArgNo() + 1,
2190 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00002191
Chris Lattner7369c142011-07-20 06:29:00 +00002192 // Ensure the argument is the correct type.
2193 if (V->getType() != ArgI.getCoerceToType())
2194 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
2195
John McCalla738c252011-03-09 04:27:21 +00002196 if (isPromoted)
2197 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00002198
Nick Lewycky5fa40c32013-10-01 21:51:38 +00002199 if (const CXXMethodDecl *MD =
2200 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00002201 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00002202 V = CGM.getCXXABI().
2203 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00002204 }
2205
Rafael Espindola8778c282012-11-29 16:09:03 +00002206 // Because of merging of function types from multiple decls it is
2207 // possible for the type of an argument to not match the corresponding
2208 // type in the function type. Since we are codegening the callee
2209 // in here, add a cast to the argument type.
2210 llvm::Type *LTy = ConvertType(Arg->getType());
2211 if (V->getType() != LTy)
2212 V = Builder.CreateBitCast(V, LTy);
2213
John McCall7f416cc2015-09-08 08:05:57 +00002214 ArgVals.push_back(ParamValue::forDirect(V));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002215 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00002216 }
Mike Stump11289f42009-09-09 15:08:12 +00002217
John McCall7f416cc2015-09-08 08:05:57 +00002218 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
2219 Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002220
John McCall7f416cc2015-09-08 08:05:57 +00002221 // Pointer to store into.
2222 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002223
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002224 // Fast-isel and the optimizer generally like scalar values better than
2225 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002226 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002227 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
2228 STy->getNumElements() > 1) {
John McCall7f416cc2015-09-08 08:05:57 +00002229 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Micah Villmowdd31ca12012-10-08 16:25:52 +00002230 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
John McCall7f416cc2015-09-08 08:05:57 +00002231 llvm::Type *DstTy = Ptr.getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002232 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002233
John McCall7f416cc2015-09-08 08:05:57 +00002234 Address AddrToStoreInto = Address::invalid();
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002235 if (SrcSize <= DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00002236 AddrToStoreInto =
2237 Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002238 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002239 AddrToStoreInto =
2240 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
Chris Lattner15ec3612010-06-29 00:06:42 +00002241 }
John McCall7f416cc2015-09-08 08:05:57 +00002242
2243 assert(STy->getNumElements() == NumIRArgs);
2244 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2245 auto AI = FnArgs[FirstIRArg + i];
2246 AI->setName(Arg->getName() + ".coerce" + Twine(i));
2247 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
2248 Address EltPtr =
2249 Builder.CreateStructGEP(AddrToStoreInto, i, Offset);
2250 Builder.CreateStore(AI, EltPtr);
2251 }
2252
2253 if (SrcSize > DstSize) {
2254 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
2255 }
2256
Chris Lattner15ec3612010-06-29 00:06:42 +00002257 } else {
2258 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002259 assert(NumIRArgs == 1);
2260 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00002261 AI->setName(Arg->getName() + ".coerce");
John McCall7f416cc2015-09-08 08:05:57 +00002262 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00002263 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002264
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002265 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00002266 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002267 llvm::Value *V =
2268 EmitLoadOfScalar(Alloca, false, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00002269 if (isPromoted)
2270 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002271 ArgVals.push_back(ParamValue::forDirect(V));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002272 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002273 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00002274 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002275 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002276 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002277
John McCallf26e73d2016-03-11 04:30:43 +00002278 case ABIArgInfo::CoerceAndExpand: {
2279 // Reconstruct into a temporary.
2280 Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2281 ArgVals.push_back(ParamValue::forIndirect(alloca));
2282
2283 auto coercionType = ArgI.getCoerceAndExpandType();
2284 alloca = Builder.CreateElementBitCast(alloca, coercionType);
2285 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
2286
2287 unsigned argIndex = FirstIRArg;
2288 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2289 llvm::Type *eltType = coercionType->getElementType(i);
2290 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
2291 continue;
2292
2293 auto eltAddr = Builder.CreateStructGEP(alloca, i, layout);
2294 auto elt = FnArgs[argIndex++];
2295 Builder.CreateStore(elt, eltAddr);
2296 }
2297 assert(argIndex == FirstIRArg + NumIRArgs);
2298 break;
2299 }
2300
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002301 case ABIArgInfo::Expand: {
2302 // If this structure was expanded into multiple arguments then
2303 // we need to create a temporary and reconstruct it from the
2304 // arguments.
John McCall7f416cc2015-09-08 08:05:57 +00002305 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2306 LValue LV = MakeAddrLValue(Alloca, Ty);
2307 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002308
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002309 auto FnArgIter = FnArgs.begin() + FirstIRArg;
2310 ExpandTypeFromArgs(Ty, LV, FnArgIter);
2311 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
2312 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
2313 auto AI = FnArgs[FirstIRArg + i];
2314 AI->setName(Arg->getName() + "." + Twine(i));
2315 }
2316 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002317 }
2318
2319 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002320 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002321 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002322 if (!hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002323 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002324 } else {
2325 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002326 ArgVals.push_back(ParamValue::forDirect(U));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002327 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002328 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002329 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002330 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002331
Reid Kleckner739756c2013-12-04 19:23:12 +00002332 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2333 for (int I = Args.size() - 1; I >= 0; --I)
John McCall7f416cc2015-09-08 08:05:57 +00002334 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002335 } else {
2336 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall7f416cc2015-09-08 08:05:57 +00002337 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002338 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002339}
2340
John McCallffa2c1a2012-01-29 07:46:59 +00002341static void eraseUnusedBitCasts(llvm::Instruction *insn) {
2342 while (insn->use_empty()) {
2343 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
2344 if (!bitcast) return;
2345
2346 // This is "safe" because we would have used a ConstantExpr otherwise.
2347 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
2348 bitcast->eraseFromParent();
2349 }
2350}
2351
John McCall31168b02011-06-15 23:02:42 +00002352/// Try to emit a fused autorelease of a return result.
2353static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
2354 llvm::Value *result) {
2355 // We must be immediately followed the cast.
2356 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002357 if (BB->empty()) return nullptr;
2358 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002359
Chris Lattner2192fe52011-07-18 04:24:23 +00002360 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00002361
2362 // result is in a BasicBlock and is therefore an Instruction.
2363 llvm::Instruction *generator = cast<llvm::Instruction>(result);
2364
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002365 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00002366
2367 // Look for:
2368 // %generator = bitcast %type1* %generator2 to %type2*
2369 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2370 // We would have emitted this as a constant if the operand weren't
2371 // an Instruction.
2372 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2373
2374 // Require the generator to be immediately followed by the cast.
2375 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00002376 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002377
2378 insnsToKill.push_back(bitcast);
2379 }
2380
2381 // Look for:
2382 // %generator = call i8* @objc_retain(i8* %originalResult)
2383 // or
2384 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2385 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00002386 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002387
2388 bool doRetainAutorelease;
2389
John McCallb04ecb72015-10-21 18:06:43 +00002390 if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints().objc_retain) {
John McCall31168b02011-06-15 23:02:42 +00002391 doRetainAutorelease = true;
John McCallb04ecb72015-10-21 18:06:43 +00002392 } else if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints()
John McCall31168b02011-06-15 23:02:42 +00002393 .objc_retainAutoreleasedReturnValue) {
2394 doRetainAutorelease = false;
2395
John McCallcfa4e9b2012-09-07 23:30:50 +00002396 // If we emitted an assembly marker for this call (and the
2397 // ARCEntrypoints field should have been set if so), go looking
2398 // for that call. If we can't find it, we can't do this
2399 // optimization. But it should always be the immediately previous
2400 // instruction, unless we needed bitcasts around the call.
John McCallb04ecb72015-10-21 18:06:43 +00002401 if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
John McCallcfa4e9b2012-09-07 23:30:50 +00002402 llvm::Instruction *prev = call->getPrevNode();
2403 assert(prev);
2404 if (isa<llvm::BitCastInst>(prev)) {
2405 prev = prev->getPrevNode();
2406 assert(prev);
2407 }
2408 assert(isa<llvm::CallInst>(prev));
2409 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
John McCallb04ecb72015-10-21 18:06:43 +00002410 CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
John McCallcfa4e9b2012-09-07 23:30:50 +00002411 insnsToKill.push_back(prev);
2412 }
John McCall31168b02011-06-15 23:02:42 +00002413 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002414 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002415 }
2416
2417 result = call->getArgOperand(0);
2418 insnsToKill.push_back(call);
2419
2420 // Keep killing bitcasts, for sanity. Note that we no longer care
2421 // about precise ordering as long as there's exactly one use.
2422 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2423 if (!bitcast->hasOneUse()) break;
2424 insnsToKill.push_back(bitcast);
2425 result = bitcast->getOperand(0);
2426 }
2427
2428 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002429 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00002430 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
2431 (*i)->eraseFromParent();
2432
2433 // Do the fused retain/autorelease if we were asked to.
2434 if (doRetainAutorelease)
2435 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2436
2437 // Cast back to the result type.
2438 return CGF.Builder.CreateBitCast(result, resultType);
2439}
2440
John McCallffa2c1a2012-01-29 07:46:59 +00002441/// If this is a +1 of the value of an immutable 'self', remove it.
2442static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2443 llvm::Value *result) {
2444 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00002445 const ObjCMethodDecl *method =
2446 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002447 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002448 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00002449 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002450
2451 // Look for a retain call.
2452 llvm::CallInst *retainCall =
2453 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2454 if (!retainCall ||
John McCallb04ecb72015-10-21 18:06:43 +00002455 retainCall->getCalledValue() != CGF.CGM.getObjCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00002456 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002457
2458 // Look for an ordinary load of 'self'.
2459 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2460 llvm::LoadInst *load =
2461 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2462 if (!load || load->isAtomic() || load->isVolatile() ||
John McCall7f416cc2015-09-08 08:05:57 +00002463 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
Craig Topper8a13c412014-05-21 05:09:00 +00002464 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002465
2466 // Okay! Burn it all down. This relies for correctness on the
2467 // assumption that the retain is emitted as part of the return and
2468 // that thereafter everything is used "linearly".
2469 llvm::Type *resultType = result->getType();
2470 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2471 assert(retainCall->use_empty());
2472 retainCall->eraseFromParent();
2473 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2474
2475 return CGF.Builder.CreateBitCast(load, resultType);
2476}
2477
John McCall31168b02011-06-15 23:02:42 +00002478/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00002479///
2480/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00002481static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2482 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00002483 // If we're returning 'self', kill the initial retain. This is a
2484 // heuristic attempt to "encourage correctness" in the really unfortunate
2485 // case where we have a return of self during a dealloc and we desperately
2486 // need to avoid the possible autorelease.
2487 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2488 return self;
2489
John McCall31168b02011-06-15 23:02:42 +00002490 // At -O0, try to emit a fused retain/autorelease.
2491 if (CGF.shouldUseFusedARCCalls())
2492 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2493 return fused;
2494
2495 return CGF.EmitARCAutoreleaseReturnValue(result);
2496}
2497
John McCall6e1c0122012-01-29 02:35:02 +00002498/// Heuristically search for a dominating store to the return-value slot.
2499static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002500 // Check if a User is a store which pointerOperand is the ReturnValue.
2501 // We are looking for stores to the ReturnValue, not for stores of the
2502 // ReturnValue to some other location.
2503 auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
2504 auto *SI = dyn_cast<llvm::StoreInst>(U);
2505 if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer())
2506 return nullptr;
2507 // These aren't actually possible for non-coerced returns, and we
2508 // only care about non-coerced returns on this code path.
2509 assert(!SI->isAtomic() && !SI->isVolatile());
2510 return SI;
2511 };
John McCall6e1c0122012-01-29 02:35:02 +00002512 // If there are multiple uses of the return-value slot, just check
2513 // for something immediately preceding the IP. Sometimes this can
2514 // happen with how we generate implicit-returns; it can also happen
2515 // with noreturn cleanups.
John McCall7f416cc2015-09-08 08:05:57 +00002516 if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
John McCall6e1c0122012-01-29 02:35:02 +00002517 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002518 if (IP->empty()) return nullptr;
David Majnemerdc012fa2015-04-22 21:38:15 +00002519 llvm::Instruction *I = &IP->back();
2520
2521 // Skip lifetime markers
2522 for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
2523 IE = IP->rend();
2524 II != IE; ++II) {
2525 if (llvm::IntrinsicInst *Intrinsic =
2526 dyn_cast<llvm::IntrinsicInst>(&*II)) {
2527 if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
2528 const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
2529 ++II;
Alexey Samsonov10544202015-06-12 21:05:32 +00002530 if (II == IE)
2531 break;
2532 if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
2533 continue;
David Majnemerdc012fa2015-04-22 21:38:15 +00002534 }
2535 }
2536 I = &*II;
2537 break;
2538 }
2539
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002540 return GetStoreIfValid(I);
John McCall6e1c0122012-01-29 02:35:02 +00002541 }
2542
2543 llvm::StoreInst *store =
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002544 GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00002545 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002546
John McCall6e1c0122012-01-29 02:35:02 +00002547 // Now do a first-and-dirty dominance check: just walk up the
2548 // single-predecessors chain from the current insertion point.
2549 llvm::BasicBlock *StoreBB = store->getParent();
2550 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2551 while (IP != StoreBB) {
2552 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00002553 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002554 }
2555
2556 // Okay, the store's basic block dominates the insertion point; we
2557 // can do our thing.
2558 return store;
2559}
2560
Adrian Prantl3be10542013-05-02 17:30:20 +00002561void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002562 bool EmitRetDbgLoc,
2563 SourceLocation EndLoc) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002564 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2565 // Naked functions don't have epilogues.
2566 Builder.CreateUnreachable();
2567 return;
2568 }
2569
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002570 // Functions with no result always return void.
John McCall7f416cc2015-09-08 08:05:57 +00002571 if (!ReturnValue.isValid()) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002572 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00002573 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002574 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00002575
Dan Gohman481e40c2010-07-20 20:13:52 +00002576 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00002577 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00002578 QualType RetTy = FI.getReturnType();
2579 const ABIArgInfo &RetAI = FI.getReturnInfo();
2580
2581 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002582 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00002583 // Aggregrates get evaluated directly into the destination. Sometimes we
2584 // need to return the sret value in a register, though.
2585 assert(hasAggregateEvaluationKind(RetTy));
2586 if (RetAI.getInAllocaSRet()) {
2587 llvm::Function::arg_iterator EI = CurFn->arg_end();
2588 --EI;
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002589 llvm::Value *ArgStruct = &*EI;
David Blaikie2e804282015-04-05 22:47:07 +00002590 llvm::Value *SRet = Builder.CreateStructGEP(
2591 nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
John McCall7f416cc2015-09-08 08:05:57 +00002592 RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret");
Reid Klecknerfab1e892014-02-25 00:59:14 +00002593 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002594 break;
2595
Daniel Dunbar03816342010-08-21 02:24:36 +00002596 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002597 auto AI = CurFn->arg_begin();
2598 if (RetAI.isSRetAfterThis())
2599 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002600 switch (getEvaluationKind(RetTy)) {
2601 case TEK_Complex: {
2602 ComplexPairTy RT =
John McCall7f416cc2015-09-08 08:05:57 +00002603 EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002604 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002605 /*isInit*/ true);
2606 break;
2607 }
2608 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002609 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002610 break;
2611 case TEK_Scalar:
2612 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002613 MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002614 /*isInit*/ true);
2615 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002616 }
2617 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002618 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002619
2620 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002621 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002622 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2623 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002624 // The internal return value temp always will have pointer-to-return-type
2625 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002626
John McCall6e1c0122012-01-29 02:35:02 +00002627 // If there is a dominating store to ReturnValue, we can elide
2628 // the load, zap the store, and usually zap the alloca.
David Majnemerdc012fa2015-04-22 21:38:15 +00002629 if (llvm::StoreInst *SI =
2630 findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002631 // Reuse the debug location from the store unless there is
2632 // cleanup code to be emitted between the store and return
2633 // instruction.
2634 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002635 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002636 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002637 RV = SI->getValueOperand();
2638 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002639
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002640 // If that was the only use of the return value, nuke it as well now.
John McCall7f416cc2015-09-08 08:05:57 +00002641 auto returnValueInst = ReturnValue.getPointer();
2642 if (returnValueInst->use_empty()) {
2643 if (auto alloca = dyn_cast<llvm::AllocaInst>(returnValueInst)) {
2644 alloca->eraseFromParent();
2645 ReturnValue = Address::invalid();
2646 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002647 }
John McCall6e1c0122012-01-29 02:35:02 +00002648
2649 // Otherwise, we have to do a simple load.
2650 } else {
2651 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002652 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002653 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002654 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00002655 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002656
John McCall7f416cc2015-09-08 08:05:57 +00002657 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002658 }
John McCall31168b02011-06-15 23:02:42 +00002659
2660 // In ARC, end functions that return a retainable type with a call
2661 // to objc_autoreleaseReturnValue.
2662 if (AutoreleaseResult) {
Akira Hatanaka9d8ac612016-02-17 21:09:50 +00002663#ifndef NDEBUG
2664 // Type::isObjCRetainabletype has to be called on a QualType that hasn't
2665 // been stripped of the typedefs, so we cannot use RetTy here. Get the
2666 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
2667 // CurCodeDecl or BlockInfo.
2668 QualType RT;
2669
2670 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
2671 RT = FD->getReturnType();
2672 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
2673 RT = MD->getReturnType();
2674 else if (isa<BlockDecl>(CurCodeDecl))
2675 RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
2676 else
2677 llvm_unreachable("Unexpected function/method type");
2678
David Blaikiebbafb8a2012-03-11 07:00:24 +00002679 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002680 !FI.isReturnsRetained() &&
Akira Hatanaka9d8ac612016-02-17 21:09:50 +00002681 RT->isObjCRetainableType());
2682#endif
John McCall31168b02011-06-15 23:02:42 +00002683 RV = emitAutoreleaseOfResult(*this, RV);
2684 }
2685
Chris Lattner726b3d02010-06-26 23:13:19 +00002686 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002687
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002688 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002689 break;
2690
John McCallf26e73d2016-03-11 04:30:43 +00002691 case ABIArgInfo::CoerceAndExpand: {
2692 auto coercionType = RetAI.getCoerceAndExpandType();
2693 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
2694
2695 // Load all of the coerced elements out into results.
2696 llvm::SmallVector<llvm::Value*, 4> results;
2697 Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType);
2698 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2699 auto coercedEltType = coercionType->getElementType(i);
2700 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
2701 continue;
2702
2703 auto eltAddr = Builder.CreateStructGEP(addr, i, layout);
2704 auto elt = Builder.CreateLoad(eltAddr);
2705 results.push_back(elt);
2706 }
2707
2708 // If we have one result, it's the single direct result type.
2709 if (results.size() == 1) {
2710 RV = results[0];
2711
2712 // Otherwise, we need to make a first-class aggregate.
2713 } else {
2714 // Construct a return type that lacks padding elements.
2715 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
2716
2717 RV = llvm::UndefValue::get(returnType);
2718 for (unsigned i = 0, e = results.size(); i != e; ++i) {
2719 RV = Builder.CreateInsertValue(RV, results[i], i);
2720 }
2721 }
2722 break;
2723 }
2724
Chris Lattner726b3d02010-06-26 23:13:19 +00002725 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002726 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002727 }
2728
Alexey Samsonovde443c52014-08-13 00:26:40 +00002729 llvm::Instruction *Ret;
2730 if (RV) {
John McCall9a2c1c92015-09-10 00:57:46 +00002731 if (CurCodeDecl && SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) {
2732 if (auto RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>()) {
Alexey Samsonov90452df2014-09-08 20:17:19 +00002733 SanitizerScope SanScope(this);
2734 llvm::Value *Cond = Builder.CreateICmpNE(
2735 RV, llvm::Constant::getNullValue(RV->getType()));
2736 llvm::Constant *StaticData[] = {
2737 EmitCheckSourceLocation(EndLoc),
2738 EmitCheckSourceLocation(RetNNAttr->getLocation()),
2739 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002740 EmitCheck(std::make_pair(Cond, SanitizerKind::ReturnsNonnullAttribute),
2741 "nonnull_return", StaticData, None);
Alexey Samsonov90452df2014-09-08 20:17:19 +00002742 }
Alexey Samsonovde443c52014-08-13 00:26:40 +00002743 }
2744 Ret = Builder.CreateRet(RV);
2745 } else {
2746 Ret = Builder.CreateRetVoid();
2747 }
2748
Duncan P. N. Exon Smith2809cc72015-03-30 20:01:41 +00002749 if (RetDbgLoc)
Benjamin Kramer03278662015-02-07 13:15:54 +00002750 Ret->setDebugLoc(std::move(RetDbgLoc));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002751}
2752
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002753static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2754 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2755 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2756}
2757
John McCall7f416cc2015-09-08 08:05:57 +00002758static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
2759 QualType Ty) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002760 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2761 // placeholders.
2762 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2763 llvm::Value *Placeholder =
John McCall7f416cc2015-09-08 08:05:57 +00002764 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2765 Placeholder = CGF.Builder.CreateDefaultAlignedLoad(Placeholder);
2766
2767 // FIXME: When we generate this IR in one pass, we shouldn't need
2768 // this win32-specific alignment hack.
2769 CharUnits Align = CharUnits::fromQuantity(4);
2770
2771 return AggValueSlot::forAddr(Address(Placeholder, Align),
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002772 Ty.getQualifiers(),
2773 AggValueSlot::IsNotDestructed,
2774 AggValueSlot::DoesNotNeedGCBarriers,
2775 AggValueSlot::IsNotAliased);
2776}
2777
John McCall32ea9692011-03-11 20:59:21 +00002778void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002779 const VarDecl *param,
2780 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002781 // StartFunction converted the ABI-lowered parameter(s) into a
2782 // local alloca. We need to turn that into an r-value suitable
2783 // for EmitCall.
John McCall7f416cc2015-09-08 08:05:57 +00002784 Address local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002785
John McCall32ea9692011-03-11 20:59:21 +00002786 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002787
John McCall23f66262010-05-26 22:34:26 +00002788 // For the most part, we just need to load the alloca, except:
2789 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall47fb9502013-03-07 21:37:08 +00002790 // 2) references to non-scalars are pointers directly to the aggregate.
2791 // I don't know why references to scalars are different here.
John McCall32ea9692011-03-11 20:59:21 +00002792 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall47fb9502013-03-07 21:37:08 +00002793 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall32ea9692011-03-11 20:59:21 +00002794 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00002795
2796 // Locals which are references to scalars are represented
2797 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00002798 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00002799 }
2800
Reid Klecknerab2090d2014-07-26 01:34:32 +00002801 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2802 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002803
Nick Lewycky2d84e842013-10-02 02:29:49 +00002804 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00002805}
2806
John McCall31168b02011-06-15 23:02:42 +00002807static bool isProvablyNull(llvm::Value *addr) {
2808 return isa<llvm::ConstantPointerNull>(addr);
2809}
2810
2811static bool isProvablyNonNull(llvm::Value *addr) {
2812 return isa<llvm::AllocaInst>(addr);
2813}
2814
2815/// Emit the actual writing-back of a writeback.
2816static void emitWriteback(CodeGenFunction &CGF,
2817 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002818 const LValue &srcLV = writeback.Source;
John McCall7f416cc2015-09-08 08:05:57 +00002819 Address srcAddr = srcLV.getAddress();
2820 assert(!isProvablyNull(srcAddr.getPointer()) &&
John McCall31168b02011-06-15 23:02:42 +00002821 "shouldn't have writeback for provably null argument");
2822
Craig Topper8a13c412014-05-21 05:09:00 +00002823 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002824
2825 // If the argument wasn't provably non-null, we need to null check
2826 // before doing the store.
John McCall7f416cc2015-09-08 08:05:57 +00002827 bool provablyNonNull = isProvablyNonNull(srcAddr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002828 if (!provablyNonNull) {
2829 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2830 contBB = CGF.createBasicBlock("icr.done");
2831
John McCall7f416cc2015-09-08 08:05:57 +00002832 llvm::Value *isNull =
2833 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00002834 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2835 CGF.EmitBlock(writebackBB);
2836 }
2837
2838 // Load the value to writeback.
2839 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2840
2841 // Cast it back, in case we're writing an id to a Foo* or something.
John McCall7f416cc2015-09-08 08:05:57 +00002842 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
2843 "icr.writeback-cast");
John McCall31168b02011-06-15 23:02:42 +00002844
2845 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00002846
2847 // If we have a "to use" value, it's something we need to emit a use
2848 // of. This has to be carefully threaded in: if it's done after the
2849 // release it's potentially undefined behavior (and the optimizer
2850 // will ignore it), and if it happens before the retain then the
2851 // optimizer could move the release there.
2852 if (writeback.ToUse) {
2853 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2854
2855 // Retain the new value. No need to block-copy here: the block's
2856 // being passed up the stack.
2857 value = CGF.EmitARCRetainNonBlock(value);
2858
2859 // Emit the intrinsic use here.
2860 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2861
2862 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00002863 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00002864
2865 // Put the new value in place (primitively).
2866 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2867
2868 // Release the old value.
2869 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2870
2871 // Otherwise, we can just do a normal lvalue store.
2872 } else {
2873 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2874 }
John McCall31168b02011-06-15 23:02:42 +00002875
2876 // Jump to the continuation block.
2877 if (!provablyNonNull)
2878 CGF.EmitBlock(contBB);
2879}
2880
2881static void emitWritebacks(CodeGenFunction &CGF,
2882 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00002883 for (const auto &I : args.writebacks())
2884 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00002885}
2886
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002887static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2888 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002889 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002890 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2891 CallArgs.getCleanupsToDeactivate();
2892 // Iterate in reverse to increase the likelihood of popping the cleanup.
Pete Cooper57d3f142015-07-30 17:22:52 +00002893 for (const auto &I : llvm::reverse(Cleanups)) {
2894 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
2895 I.IsActiveIP->eraseFromParent();
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002896 }
2897}
2898
John McCalleff18842013-03-23 02:35:54 +00002899static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2900 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2901 if (uop->getOpcode() == UO_AddrOf)
2902 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002903 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00002904}
2905
John McCall31168b02011-06-15 23:02:42 +00002906/// Emit an argument that's being passed call-by-writeback. That is,
John McCall7f416cc2015-09-08 08:05:57 +00002907/// we are passing the address of an __autoreleased temporary; it
2908/// might be copy-initialized with the current value of the given
2909/// address, but it will definitely be copied out of after the call.
John McCall31168b02011-06-15 23:02:42 +00002910static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2911 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00002912 LValue srcLV;
2913
2914 // Make an optimistic effort to emit the address as an l-value.
Eric Christopher2c4555a2015-06-19 01:52:53 +00002915 // This can fail if the argument expression is more complicated.
John McCalleff18842013-03-23 02:35:54 +00002916 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2917 srcLV = CGF.EmitLValue(lvExpr);
2918
2919 // Otherwise, just emit it as a scalar.
2920 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002921 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
John McCalleff18842013-03-23 02:35:54 +00002922
2923 QualType srcAddrType =
2924 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00002925 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
John McCalleff18842013-03-23 02:35:54 +00002926 }
John McCall7f416cc2015-09-08 08:05:57 +00002927 Address srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002928
2929 // The dest and src types don't necessarily match in LLVM terms
2930 // because of the crazy ObjC compatibility rules.
2931
Chris Lattner2192fe52011-07-18 04:24:23 +00002932 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00002933 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
2934
2935 // If the address is a constant null, just pass the appropriate null.
John McCall7f416cc2015-09-08 08:05:57 +00002936 if (isProvablyNull(srcAddr.getPointer())) {
John McCall31168b02011-06-15 23:02:42 +00002937 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
2938 CRE->getType());
2939 return;
2940 }
2941
John McCall31168b02011-06-15 23:02:42 +00002942 // Create the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00002943 Address temp = CGF.CreateTempAlloca(destType->getElementType(),
2944 CGF.getPointerAlign(),
2945 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002946 // Loading an l-value can introduce a cleanup if the l-value is __weak,
2947 // and that cleanup will be conditional if we can't prove that the l-value
2948 // isn't null, so we need to register a dominating point so that the cleanups
2949 // system will make valid IR.
2950 CodeGenFunction::ConditionalEvaluation condEval(CGF);
2951
John McCall31168b02011-06-15 23:02:42 +00002952 // Zero-initialize it if we're not doing a copy-initialization.
2953 bool shouldCopy = CRE->shouldCopy();
2954 if (!shouldCopy) {
2955 llvm::Value *null =
2956 llvm::ConstantPointerNull::get(
2957 cast<llvm::PointerType>(destType->getElementType()));
2958 CGF.Builder.CreateStore(null, temp);
2959 }
Craig Topper8a13c412014-05-21 05:09:00 +00002960
2961 llvm::BasicBlock *contBB = nullptr;
2962 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002963
2964 // If the address is *not* known to be non-null, we need to switch.
2965 llvm::Value *finalArgument;
2966
John McCall7f416cc2015-09-08 08:05:57 +00002967 bool provablyNonNull = isProvablyNonNull(srcAddr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002968 if (provablyNonNull) {
John McCall7f416cc2015-09-08 08:05:57 +00002969 finalArgument = temp.getPointer();
John McCall31168b02011-06-15 23:02:42 +00002970 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002971 llvm::Value *isNull =
2972 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00002973
2974 finalArgument = CGF.Builder.CreateSelect(isNull,
2975 llvm::ConstantPointerNull::get(destType),
John McCall7f416cc2015-09-08 08:05:57 +00002976 temp.getPointer(), "icr.argument");
John McCall31168b02011-06-15 23:02:42 +00002977
2978 // If we need to copy, then the load has to be conditional, which
2979 // means we need control flow.
2980 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00002981 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002982 contBB = CGF.createBasicBlock("icr.cont");
2983 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
2984 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
2985 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002986 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00002987 }
2988 }
2989
Craig Topper8a13c412014-05-21 05:09:00 +00002990 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00002991
John McCall31168b02011-06-15 23:02:42 +00002992 // Perform a copy if necessary.
2993 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002994 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002995 assert(srcRV.isScalar());
2996
2997 llvm::Value *src = srcRV.getScalarVal();
2998 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
2999 "icr.cast");
3000
3001 // Use an ordinary store, not a store-to-lvalue.
3002 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00003003
3004 // If optimization is enabled, and the value was held in a
3005 // __strong variable, we need to tell the optimizer that this
3006 // value has to stay alive until we're doing the store back.
3007 // This is because the temporary is effectively unretained,
3008 // and so otherwise we can violate the high-level semantics.
3009 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3010 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
3011 valueToUse = src;
3012 }
John McCall31168b02011-06-15 23:02:42 +00003013 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003014
John McCall31168b02011-06-15 23:02:42 +00003015 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003016 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00003017 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00003018 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00003019
3020 // Make a phi for the value to intrinsically use.
3021 if (valueToUse) {
3022 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
3023 "icr.to-use");
3024 phiToUse->addIncoming(valueToUse, copyBB);
3025 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
3026 originBB);
3027 valueToUse = phiToUse;
3028 }
3029
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003030 condEval.end(CGF);
3031 }
John McCall31168b02011-06-15 23:02:42 +00003032
John McCalleff18842013-03-23 02:35:54 +00003033 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00003034 args.add(RValue::get(finalArgument), CRE->getType());
3035}
3036
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003037void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
3038 assert(!StackBase && !StackCleanup.isValid());
3039
3040 // Save the stack.
3041 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie43f9bb72015-05-18 22:14:03 +00003042 StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003043}
3044
Nico Weber8cdb3f92015-08-25 18:43:32 +00003045void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
3046 if (StackBase) {
Reid Kleckner7c2f9e82015-10-08 00:17:45 +00003047 // Restore the stack after the call.
Nico Weber8cdb3f92015-08-25 18:43:32 +00003048 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
Nico Weber8cdb3f92015-08-25 18:43:32 +00003049 CGF.Builder.CreateCall(F, StackBase);
3050 }
3051}
3052
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003053void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
3054 SourceLocation ArgLoc,
3055 const FunctionDecl *FD,
3056 unsigned ParmNum) {
3057 if (!SanOpts.has(SanitizerKind::NonnullAttribute) || !FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003058 return;
3059 auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
3060 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
3061 auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
3062 if (!NNAttr)
3063 return;
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003064 SanitizerScope SanScope(this);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003065 assert(RV.isScalar());
3066 llvm::Value *V = RV.getScalarVal();
3067 llvm::Value *Cond =
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003068 Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003069 llvm::Constant *StaticData[] = {
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003070 EmitCheckSourceLocation(ArgLoc),
3071 EmitCheckSourceLocation(NNAttr->getLocation()),
3072 llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003073 };
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003074 EmitCheck(std::make_pair(Cond, SanitizerKind::NonnullAttribute),
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003075 "nonnull_arg", StaticData, None);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003076}
3077
David Blaikief05779e2015-07-21 18:37:18 +00003078void CodeGenFunction::EmitCallArgs(
3079 CallArgList &Args, ArrayRef<QualType> ArgTypes,
3080 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
3081 const FunctionDecl *CalleeDecl, unsigned ParamsToSkip) {
3082 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003083
3084 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg) {
3085 if (CalleeDecl == nullptr || I >= CalleeDecl->getNumParams())
3086 return;
3087 auto *PS = CalleeDecl->getParamDecl(I)->getAttr<PassObjectSizeAttr>();
3088 if (PS == nullptr)
3089 return;
3090
3091 const auto &Context = getContext();
3092 auto SizeTy = Context.getSizeType();
3093 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
3094 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T);
3095 Args.add(RValue::get(V), SizeTy);
3096 };
3097
Reid Kleckner739756c2013-12-04 19:23:12 +00003098 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
3099 // because arguments are destroyed left to right in the callee.
3100 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003101 // Insert a stack save if we're going to need any inalloca args.
3102 bool HasInAllocaArgs = false;
3103 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
3104 I != E && !HasInAllocaArgs; ++I)
3105 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
3106 if (HasInAllocaArgs) {
3107 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3108 Args.allocateArgumentMemory(*this);
3109 }
3110
3111 // Evaluate each argument.
Reid Kleckner739756c2013-12-04 19:23:12 +00003112 size_t CallArgsStart = Args.size();
3113 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
David Blaikief05779e2015-07-21 18:37:18 +00003114 CallExpr::const_arg_iterator Arg = ArgRange.begin() + I;
Reid Kleckner739756c2013-12-04 19:23:12 +00003115 EmitCallArg(Args, *Arg, ArgTypes[I]);
Benjamin Kramerf48ee442015-07-18 14:35:53 +00003116 EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], (*Arg)->getExprLoc(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003117 CalleeDecl, ParamsToSkip + I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003118 MaybeEmitImplicitObjectSize(I, *Arg);
Reid Kleckner739756c2013-12-04 19:23:12 +00003119 }
3120
3121 // Un-reverse the arguments we just evaluated so they match up with the LLVM
3122 // IR function.
3123 std::reverse(Args.begin() + CallArgsStart, Args.end());
3124 return;
3125 }
3126
3127 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
David Blaikief05779e2015-07-21 18:37:18 +00003128 CallExpr::const_arg_iterator Arg = ArgRange.begin() + I;
3129 assert(Arg != ArgRange.end());
Reid Kleckner739756c2013-12-04 19:23:12 +00003130 EmitCallArg(Args, *Arg, ArgTypes[I]);
Benjamin Kramerf48ee442015-07-18 14:35:53 +00003131 EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], (*Arg)->getExprLoc(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003132 CalleeDecl, ParamsToSkip + I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003133 MaybeEmitImplicitObjectSize(I, *Arg);
Reid Kleckner739756c2013-12-04 19:23:12 +00003134 }
3135}
3136
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003137namespace {
3138
David Blaikie7e70d682015-08-18 22:40:54 +00003139struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +00003140 DestroyUnpassedArg(Address Addr, QualType Ty)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003141 : Addr(Addr), Ty(Ty) {}
3142
John McCall7f416cc2015-09-08 08:05:57 +00003143 Address Addr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003144 QualType Ty;
3145
Craig Topper4f12f102014-03-12 06:41:41 +00003146 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003147 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
3148 assert(!Dtor->isTrivial());
3149 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
3150 /*Delegating=*/false, Addr);
3151 }
3152};
3153
David Blaikie38b25912015-02-09 19:13:51 +00003154struct DisableDebugLocationUpdates {
3155 CodeGenFunction &CGF;
3156 bool disabledDebugInfo;
3157 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
3158 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
3159 CGF.disableDebugInfo();
3160 }
3161 ~DisableDebugLocationUpdates() {
3162 if (disabledDebugInfo)
3163 CGF.enableDebugInfo();
3164 }
3165};
3166
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00003167} // end anonymous namespace
3168
John McCall32ea9692011-03-11 20:59:21 +00003169void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
3170 QualType type) {
David Blaikie38b25912015-02-09 19:13:51 +00003171 DisableDebugLocationUpdates Dis(*this, E);
John McCall31168b02011-06-15 23:02:42 +00003172 if (const ObjCIndirectCopyRestoreExpr *CRE
3173 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00003174 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00003175 assert(getContext().hasSameType(E->getType(), type));
3176 return emitWritebackArg(*this, args, CRE);
3177 }
3178
John McCall0a76c0c2011-08-26 18:42:59 +00003179 assert(type->isReferenceType() == E->isGLValue() &&
3180 "reference binding to unmaterialized r-value!");
3181
John McCall17054bd62011-08-26 21:08:13 +00003182 if (E->isGLValue()) {
3183 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00003184 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00003185 }
Mike Stump11289f42009-09-09 15:08:12 +00003186
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003187 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
3188
3189 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
3190 // However, we still have to push an EH-only cleanup in case we unwind before
3191 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00003192 if (HasAggregateEvalKind &&
3193 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
3194 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00003195 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00003196 AggValueSlot Slot;
3197 if (args.isUsingInAlloca())
3198 Slot = createPlaceholderSlot(*this, type);
3199 else
3200 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00003201
3202 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
3203 bool DestroyedInCallee =
3204 RD && RD->hasNonTrivialDestructor() &&
3205 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
3206 if (DestroyedInCallee)
3207 Slot.setExternallyDestructed();
3208
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003209 EmitAggExpr(E, Slot);
3210 RValue RV = Slot.asRValue();
3211 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003212
Reid Klecknere39ee212014-05-03 00:33:28 +00003213 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003214 // Create a no-op GEP between the placeholder and the cleanup so we can
3215 // RAUW it successfully. It also serves as a marker of the first
3216 // instruction where the cleanup is active.
John McCall7f416cc2015-09-08 08:05:57 +00003217 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
3218 type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003219 // This unreachable is a temporary marker which will be removed later.
3220 llvm::Instruction *IsActive = Builder.CreateUnreachable();
3221 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003222 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003223 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003224 }
3225
3226 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00003227 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
3228 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
3229 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00003230 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
3231 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
3232 } else {
3233 // We can't represent a misaligned lvalue in the CallArgList, so copy
3234 // to an aligned temporary now.
John McCall7f416cc2015-09-08 08:05:57 +00003235 Address tmp = CreateMemTemp(type);
3236 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile());
Eli Friedman61f615a2013-06-11 01:08:22 +00003237 args.add(RValue::getAggregate(tmp), type);
3238 }
Eli Friedmandf968192011-05-26 00:10:27 +00003239 return;
3240 }
3241
John McCall32ea9692011-03-11 20:59:21 +00003242 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00003243}
3244
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003245QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
3246 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
3247 // implicitly widens null pointer constants that are arguments to varargs
3248 // functions to pointer-sized ints.
3249 if (!getTarget().getTriple().isOSWindows())
3250 return Arg->getType();
3251
3252 if (Arg->getType()->isIntegerType() &&
3253 getContext().getTypeSize(Arg->getType()) <
3254 getContext().getTargetInfo().getPointerWidth(0) &&
3255 Arg->isNullPointerConstant(getContext(),
3256 Expr::NPC_ValueDependentIsNotNull)) {
3257 return getContext().getIntPtrType();
3258 }
3259
3260 return Arg->getType();
3261}
3262
Dan Gohman515a60d2012-02-16 00:57:37 +00003263// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3264// optimizer it can aggressively ignore unwind edges.
3265void
3266CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
3267 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3268 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
3269 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
3270 CGM.getNoObjCARCExceptionsMetadata());
3271}
3272
John McCall882987f2013-02-28 19:01:20 +00003273/// Emits a call to the given no-arguments nounwind runtime function.
3274llvm::CallInst *
3275CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3276 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003277 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003278}
3279
3280/// Emits a call to the given nounwind runtime function.
3281llvm::CallInst *
3282CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3283 ArrayRef<llvm::Value*> args,
3284 const llvm::Twine &name) {
3285 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
3286 call->setDoesNotThrow();
3287 return call;
3288}
3289
3290/// Emits a simple call (never an invoke) to the given no-arguments
3291/// runtime function.
3292llvm::CallInst *
3293CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3294 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003295 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003296}
3297
David Majnemer0b17d442015-12-15 21:27:59 +00003298// Calls which may throw must have operand bundles indicating which funclet
3299// they are nested within.
3300static void
Sanjay Patel846b63b2016-01-18 22:15:33 +00003301getBundlesForFunclet(llvm::Value *Callee, llvm::Instruction *CurrentFuncletPad,
David Majnemer0b17d442015-12-15 21:27:59 +00003302 SmallVectorImpl<llvm::OperandBundleDef> &BundleList) {
Sanjay Patel846b63b2016-01-18 22:15:33 +00003303 // There is no need for a funclet operand bundle if we aren't inside a
3304 // funclet.
David Majnemer0b17d442015-12-15 21:27:59 +00003305 if (!CurrentFuncletPad)
3306 return;
3307
3308 // Skip intrinsics which cannot throw.
3309 auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts());
3310 if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow())
3311 return;
3312
3313 BundleList.emplace_back("funclet", CurrentFuncletPad);
3314}
3315
David Majnemer971d31b2016-02-24 17:02:45 +00003316/// Emits a simple call (never an invoke) to the given runtime function.
3317llvm::CallInst *
3318CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3319 ArrayRef<llvm::Value*> args,
3320 const llvm::Twine &name) {
3321 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3322 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList);
3323
3324 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList, name);
3325 call->setCallingConv(getRuntimeCC());
3326 return call;
3327}
3328
John McCall882987f2013-02-28 19:01:20 +00003329/// Emits a call or invoke to the given noreturn runtime function.
3330void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
3331 ArrayRef<llvm::Value*> args) {
David Majnemer0b17d442015-12-15 21:27:59 +00003332 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3333 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList);
3334
John McCall882987f2013-02-28 19:01:20 +00003335 if (getInvokeDest()) {
3336 llvm::InvokeInst *invoke =
3337 Builder.CreateInvoke(callee,
3338 getUnreachableBlock(),
3339 getInvokeDest(),
David Majnemer0b17d442015-12-15 21:27:59 +00003340 args,
3341 BundleList);
John McCall882987f2013-02-28 19:01:20 +00003342 invoke->setDoesNotReturn();
3343 invoke->setCallingConv(getRuntimeCC());
3344 } else {
David Majnemer0b17d442015-12-15 21:27:59 +00003345 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
John McCall882987f2013-02-28 19:01:20 +00003346 call->setDoesNotReturn();
3347 call->setCallingConv(getRuntimeCC());
3348 Builder.CreateUnreachable();
3349 }
3350}
3351
Sanjay Patel846b63b2016-01-18 22:15:33 +00003352/// Emits a call or invoke instruction to the given nullary runtime function.
John McCall882987f2013-02-28 19:01:20 +00003353llvm::CallSite
3354CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3355 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003356 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003357}
3358
3359/// Emits a call or invoke instruction to the given runtime function.
3360llvm::CallSite
3361CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3362 ArrayRef<llvm::Value*> args,
3363 const Twine &name) {
3364 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
3365 callSite.setCallingConv(getRuntimeCC());
3366 return callSite;
3367}
3368
John McCallbd309292010-07-06 01:34:17 +00003369/// Emits a call or invoke instruction to the given function, depending
3370/// on the current state of the EH stack.
3371llvm::CallSite
3372CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00003373 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003374 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00003375 llvm::BasicBlock *InvokeDest = getInvokeDest();
David Majnemer3df77bc2016-01-26 23:14:47 +00003376 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3377 getBundlesForFunclet(Callee, CurrentFuncletPad, BundleList);
John McCallbd309292010-07-06 01:34:17 +00003378
Dan Gohman515a60d2012-02-16 00:57:37 +00003379 llvm::Instruction *Inst;
3380 if (!InvokeDest)
David Majnemer3df77bc2016-01-26 23:14:47 +00003381 Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
Dan Gohman515a60d2012-02-16 00:57:37 +00003382 else {
3383 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
David Majnemer3df77bc2016-01-26 23:14:47 +00003384 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
3385 Name);
Dan Gohman515a60d2012-02-16 00:57:37 +00003386 EmitBlock(ContBB);
3387 }
3388
3389 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3390 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003391 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003392 AddObjCARCExceptionMetadata(Inst);
3393
Benjamin Kramerc19cde12015-04-10 14:49:31 +00003394 return llvm::CallSite(Inst);
John McCallbd309292010-07-06 01:34:17 +00003395}
3396
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003397/// \brief Store a non-aggregate value to an address to initialize it. For
3398/// initialization, a non-atomic store will be used.
3399static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
3400 LValue Dst) {
3401 if (Src.isScalar())
3402 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
3403 else
3404 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
3405}
3406
3407void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
3408 llvm::Value *New) {
3409 DeferredReplacements.push_back(std::make_pair(Old, New));
3410}
Chris Lattnerd59d8672011-07-12 06:29:11 +00003411
Daniel Dunbard931a872009-02-02 22:03:45 +00003412RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00003413 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00003414 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003415 const CallArgList &CallArgs,
Samuel Antao798f11c2015-11-23 22:04:44 +00003416 CGCalleeInfo CalleeInfo,
David Chisnallff5f88c2010-05-02 13:41:58 +00003417 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00003418 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00003419
3420 // Handle struct-return functions by passing a pointer to the
3421 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00003422 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003423 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003424
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003425 llvm::FunctionType *IRFuncTy =
3426 cast<llvm::FunctionType>(
3427 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00003428
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003429 // If we're using inalloca, insert the allocation after the stack save.
3430 // FIXME: Do this earlier rather than hacking it in here!
John McCall7f416cc2015-09-08 08:05:57 +00003431 Address ArgMemory = Address::invalid();
3432 const llvm::StructLayout *ArgMemoryLayout = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003433 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
John McCall7f416cc2015-09-08 08:05:57 +00003434 ArgMemoryLayout = CGM.getDataLayout().getStructLayout(ArgStruct);
Reid Kleckner9df1d972014-04-10 01:40:15 +00003435 llvm::Instruction *IP = CallArgs.getStackBase();
3436 llvm::AllocaInst *AI;
3437 if (IP) {
3438 IP = IP->getNextNode();
3439 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
3440 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00003441 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00003442 }
John McCall7f416cc2015-09-08 08:05:57 +00003443 auto Align = CallInfo.getArgStructAlignment();
3444 AI->setAlignment(Align.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003445 AI->setUsedWithInAlloca(true);
3446 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
John McCall7f416cc2015-09-08 08:05:57 +00003447 ArgMemory = Address(AI, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003448 }
3449
John McCall7f416cc2015-09-08 08:05:57 +00003450 // Helper function to drill into the inalloca allocation.
3451 auto createInAllocaStructGEP = [&](unsigned FieldIndex) -> Address {
3452 auto FieldOffset =
3453 CharUnits::fromQuantity(ArgMemoryLayout->getElementOffset(FieldIndex));
3454 return Builder.CreateStructGEP(ArgMemory, FieldIndex, FieldOffset);
3455 };
3456
Alexey Samsonov153004f2014-09-29 22:08:00 +00003457 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003458 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
3459
Chris Lattner4ca97c32009-06-13 00:26:38 +00003460 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00003461 // alloca to hold the result, unless one is given to us.
John McCall7f416cc2015-09-08 08:05:57 +00003462 Address SRetPtr = Address::invalid();
Leny Kholodov6aab1112015-06-08 10:23:49 +00003463 size_t UnusedReturnSize = 0;
John McCallf26e73d2016-03-11 04:30:43 +00003464 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
John McCall7f416cc2015-09-08 08:05:57 +00003465 if (!ReturnValue.isNull()) {
3466 SRetPtr = ReturnValue.getValue();
3467 } else {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003468 SRetPtr = CreateMemTemp(RetTy);
Leny Kholodov6aab1112015-06-08 10:23:49 +00003469 if (HaveInsertPoint() && ReturnValue.isUnused()) {
3470 uint64_t size =
3471 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
John McCall7f416cc2015-09-08 08:05:57 +00003472 if (EmitLifetimeStart(size, SRetPtr.getPointer()))
Leny Kholodov6aab1112015-06-08 10:23:49 +00003473 UnusedReturnSize = size;
3474 }
3475 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003476 if (IRFunctionArgs.hasSRetArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00003477 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
John McCallf26e73d2016-03-11 04:30:43 +00003478 } else if (RetAI.isInAlloca()) {
John McCall7f416cc2015-09-08 08:05:57 +00003479 Address Addr = createInAllocaStructGEP(RetAI.getInAllocaFieldIndex());
3480 Builder.CreateStore(SRetPtr.getPointer(), Addr);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003481 }
Anders Carlsson17490832009-12-24 20:40:36 +00003482 }
Mike Stump11289f42009-09-09 15:08:12 +00003483
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00003484 assert(CallInfo.arg_size() == CallArgs.size() &&
3485 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003486 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003487 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00003488 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003489 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003490 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003491 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003492
Rafael Espindolafad28de2012-10-24 01:59:00 +00003493 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003494 if (IRFunctionArgs.hasPaddingArg(ArgNo))
3495 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
3496 llvm::UndefValue::get(ArgInfo.getPaddingType());
3497
3498 unsigned FirstIRArg, NumIRArgs;
3499 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003500
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003501 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003502 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003503 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003504 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3505 if (RV.isAggregate()) {
3506 // Replace the placeholder with the appropriate argument slot GEP.
3507 llvm::Instruction *Placeholder =
John McCall7f416cc2015-09-08 08:05:57 +00003508 cast<llvm::Instruction>(RV.getAggregatePointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003509 CGBuilderTy::InsertPoint IP = Builder.saveIP();
3510 Builder.SetInsertPoint(Placeholder);
John McCall7f416cc2015-09-08 08:05:57 +00003511 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003512 Builder.restoreIP(IP);
John McCall7f416cc2015-09-08 08:05:57 +00003513 deferPlaceholderReplacement(Placeholder, Addr.getPointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003514 } else {
3515 // Store the RValue into the argument struct.
John McCall7f416cc2015-09-08 08:05:57 +00003516 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
3517 unsigned AS = Addr.getType()->getPointerAddressSpace();
David Majnemer32b57b02014-03-31 16:12:47 +00003518 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3519 // There are some cases where a trivial bitcast is not avoidable. The
3520 // definition of a type later in a translation unit may change it's type
3521 // from {}* to (%struct.foo*)*.
John McCall7f416cc2015-09-08 08:05:57 +00003522 if (Addr.getType() != MemType)
David Majnemer32b57b02014-03-31 16:12:47 +00003523 Addr = Builder.CreateBitCast(Addr, MemType);
John McCall7f416cc2015-09-08 08:05:57 +00003524 LValue argLV = MakeAddrLValue(Addr, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003525 EmitInitStoreOfNonAggregate(*this, RV, argLV);
3526 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003527 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003528 }
3529
Daniel Dunbar03816342010-08-21 02:24:36 +00003530 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003531 assert(NumIRArgs == 1);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003532 if (RV.isScalar() || RV.isComplex()) {
3533 // Make a temporary alloca to pass the argument.
John McCall7f416cc2015-09-08 08:05:57 +00003534 Address Addr = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3535 IRCallArgs[FirstIRArg] = Addr.getPointer();
John McCall47fb9502013-03-07 21:37:08 +00003536
John McCall7f416cc2015-09-08 08:05:57 +00003537 LValue argLV = MakeAddrLValue(Addr, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003538 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003539 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003540 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00003541 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003542 // 1. If the argument is not byval, and we are required to copy the
3543 // source. (This case doesn't occur on any common architecture.)
3544 // 2. If the argument is byval, RV is not sufficiently aligned, and
3545 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00003546 // 3. If the argument is byval, but RV is located in an address space
3547 // different than that of the argument (0).
John McCall7f416cc2015-09-08 08:05:57 +00003548 Address Addr = RV.getAggregateAddress();
3549 CharUnits Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003550 const llvm::DataLayout *TD = &CGM.getDataLayout();
John McCall7f416cc2015-09-08 08:05:57 +00003551 const unsigned RVAddrSpace = Addr.getType()->getAddressSpace();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003552 const unsigned ArgAddrSpace =
3553 (FirstIRArg < IRFuncTy->getNumParams()
3554 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
3555 : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00003556 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall7f416cc2015-09-08 08:05:57 +00003557 (ArgInfo.getIndirectByVal() && Addr.getAlignment() < Align &&
3558 llvm::getOrEnforceKnownAlignment(Addr.getPointer(),
3559 Align.getQuantity(), *TD)
3560 < Align.getQuantity()) ||
Mehdi Aminib3d52092015-03-10 02:36:43 +00003561 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003562 // Create an aligned temporary, and copy to it.
John McCall7f416cc2015-09-08 08:05:57 +00003563 Address AI = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3564 IRCallArgs[FirstIRArg] = AI.getPointer();
Chad Rosier615ed1a2012-03-29 17:37:10 +00003565 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003566 } else {
3567 // Skip the extra memcpy call.
John McCall7f416cc2015-09-08 08:05:57 +00003568 IRCallArgs[FirstIRArg] = Addr.getPointer();
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003569 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003570 }
3571 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00003572 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003573
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003574 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003575 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003576 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003577
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003578 case ABIArgInfo::Extend:
3579 case ABIArgInfo::Direct: {
3580 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003581 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3582 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003583 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003584 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003585 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003586 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003587 else
John McCall7f416cc2015-09-08 08:05:57 +00003588 V = Builder.CreateLoad(RV.getAggregateAddress());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003589
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003590 // We might have to widen integers, but we should never truncate.
3591 if (ArgInfo.getCoerceToType() != V->getType() &&
3592 V->getType()->isIntegerTy())
3593 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
3594
Chris Lattner3ce86682011-07-12 04:53:39 +00003595 // If the argument doesn't match, perform a bitcast to coerce it. This
3596 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003597 if (FirstIRArg < IRFuncTy->getNumParams() &&
3598 V->getType() != IRFuncTy->getParamType(FirstIRArg))
3599 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
3600 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003601 break;
3602 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003603
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003604 // FIXME: Avoid the conversion through memory if possible.
John McCall7f416cc2015-09-08 08:05:57 +00003605 Address Src = Address::invalid();
John McCall47fb9502013-03-07 21:37:08 +00003606 if (RV.isScalar() || RV.isComplex()) {
John McCall7f416cc2015-09-08 08:05:57 +00003607 Src = CreateMemTemp(I->Ty, "coerce");
3608 LValue SrcLV = MakeAddrLValue(Src, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003609 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00003610 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003611 Src = RV.getAggregateAddress();
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00003612 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003613
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003614 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00003615 Src = emitAddressAtOffset(*this, Src, ArgInfo);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003616
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003617 // Fast-isel and the optimizer generally like scalar values better than
3618 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00003619 llvm::StructType *STy =
3620 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003621 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
John McCall7f416cc2015-09-08 08:05:57 +00003622 llvm::Type *SrcTy = Src.getType()->getElementType();
Chandler Carrutha6399a52012-10-10 11:29:08 +00003623 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
3624 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
3625
3626 // If the source type is smaller than the destination type of the
3627 // coerce-to logic, copy the source value into a temp alloca the size
3628 // of the destination type to allow loading all of it. The bits past
3629 // the source value are left undef.
3630 if (SrcSize < DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00003631 Address TempAlloca
3632 = CreateTempAlloca(STy, Src.getAlignment(),
3633 Src.getName() + ".coerce");
3634 Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
3635 Src = TempAlloca;
Chandler Carrutha6399a52012-10-10 11:29:08 +00003636 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003637 Src = Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(STy));
Chandler Carrutha6399a52012-10-10 11:29:08 +00003638 }
3639
John McCall7f416cc2015-09-08 08:05:57 +00003640 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003641 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00003642 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00003643 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
3644 Address EltPtr = Builder.CreateStructGEP(Src, i, Offset);
3645 llvm::Value *LI = Builder.CreateLoad(EltPtr);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003646 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00003647 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00003648 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00003649 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003650 assert(NumIRArgs == 1);
3651 IRCallArgs[FirstIRArg] =
John McCall7f416cc2015-09-08 08:05:57 +00003652 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00003653 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003654
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003655 break;
3656 }
3657
John McCallf26e73d2016-03-11 04:30:43 +00003658 case ABIArgInfo::CoerceAndExpand: {
3659 assert(RV.isAggregate() &&
3660 "CoerceAndExpand does not support non-aggregate types yet");
3661
3662 auto coercionType = ArgInfo.getCoerceAndExpandType();
3663 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
3664
3665 Address addr = RV.getAggregateAddress();
3666 addr = Builder.CreateElementBitCast(addr, coercionType);
3667
3668 unsigned IRArgPos = FirstIRArg;
3669 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3670 llvm::Type *eltType = coercionType->getElementType(i);
3671 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
3672 Address eltAddr = Builder.CreateStructGEP(addr, i, layout);
3673 llvm::Value *elt = Builder.CreateLoad(eltAddr);
3674 IRCallArgs[IRArgPos++] = elt;
3675 }
3676 assert(IRArgPos == FirstIRArg + NumIRArgs);
3677
3678 break;
3679 }
3680
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003681 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003682 unsigned IRArgPos = FirstIRArg;
3683 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
3684 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003685 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003686 }
3687 }
Mike Stump11289f42009-09-09 15:08:12 +00003688
John McCall7f416cc2015-09-08 08:05:57 +00003689 if (ArgMemory.isValid()) {
3690 llvm::Value *Arg = ArgMemory.getPointer();
Reid Klecknerafba553e2014-07-08 02:24:27 +00003691 if (CallInfo.isVariadic()) {
3692 // When passing non-POD arguments by value to variadic functions, we will
3693 // end up with a variadic prototype and an inalloca call site. In such
3694 // cases, we can't do any parameter mismatch checks. Give up and bitcast
3695 // the callee.
3696 unsigned CalleeAS =
3697 cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
3698 Callee = Builder.CreateBitCast(
3699 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
3700 } else {
3701 llvm::Type *LastParamTy =
3702 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
3703 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003704#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00003705 // Assert that these structs have equivalent element types.
3706 llvm::StructType *FullTy = CallInfo.getArgStruct();
3707 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3708 cast<llvm::PointerType>(LastParamTy)->getElementType());
3709 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3710 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3711 DE = DeclaredTy->element_end(),
3712 FI = FullTy->element_begin();
3713 DI != DE; ++DI, ++FI)
3714 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003715#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00003716 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3717 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003718 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003719 assert(IRFunctionArgs.hasInallocaArg());
3720 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003721 }
3722
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003723 if (!CallArgs.getCleanupsToDeactivate().empty())
3724 deactivateArgCleanupsBeforeCall(*this, CallArgs);
3725
Chris Lattner4ca97c32009-06-13 00:26:38 +00003726 // If the callee is a bitcast of a function to a varargs pointer to function
3727 // type, check to see if we can remove the bitcast. This handles some cases
3728 // with unprototyped functions.
3729 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
3730 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003731 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
3732 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00003733 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00003734 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00003735
Chris Lattner4ca97c32009-06-13 00:26:38 +00003736 if (CE->getOpcode() == llvm::Instruction::BitCast &&
3737 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00003738 ActualFT->getNumParams() == CurFT->getNumParams() &&
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003739 ActualFT->getNumParams() == IRCallArgs.size() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00003740 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00003741 bool ArgsMatch = true;
3742 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
3743 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
3744 ArgsMatch = false;
3745 break;
3746 }
Mike Stump11289f42009-09-09 15:08:12 +00003747
Chris Lattner4ca97c32009-06-13 00:26:38 +00003748 // Strip the cast if we can get away with it. This is a nice cleanup,
3749 // but also allows us to inline the function at -O0 if it is marked
3750 // always_inline.
3751 if (ArgsMatch)
3752 Callee = CalleeF;
3753 }
3754 }
Mike Stump11289f42009-09-09 15:08:12 +00003755
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003756 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
3757 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
3758 // Inalloca argument can have different type.
3759 if (IRFunctionArgs.hasInallocaArg() &&
3760 i == IRFunctionArgs.getInallocaArgNo())
3761 continue;
3762 if (i < IRFuncTy->getNumParams())
3763 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
3764 }
3765
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003766 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00003767 CodeGen::AttributeListType AttributeList;
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00003768 CGM.ConstructAttributeList(Callee->getName(), CallInfo, CalleeInfo,
3769 AttributeList, CallingConv,
3770 /*AttrOnCallSite=*/true);
Bill Wendling3087d022012-12-07 23:17:26 +00003771 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003772 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00003773
David Majnemer4e52d6f2015-12-12 05:39:21 +00003774 bool CannotThrow;
3775 if (currentFunctionUsesSEHTry()) {
3776 // SEH cares about asynchronous exceptions, everything can "throw."
3777 CannotThrow = false;
3778 } else if (isCleanupPadScope() &&
3779 EHPersonality::get(*this).isMSVCXXPersonality()) {
3780 // The MSVC++ personality will implicitly terminate the program if an
3781 // exception is thrown. An unwind edge cannot be reached.
3782 CannotThrow = true;
3783 } else {
3784 // Otherwise, nowunind callsites will never throw.
3785 CannotThrow = Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
3786 llvm::Attribute::NoUnwind);
3787 }
3788 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00003789
David Majnemer0b17d442015-12-15 21:27:59 +00003790 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3791 getBundlesForFunclet(Callee, CurrentFuncletPad, BundleList);
3792
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003793 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00003794 if (!InvokeDest) {
David Majnemer0b17d442015-12-15 21:27:59 +00003795 CS = Builder.CreateCall(Callee, IRCallArgs, BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00003796 } else {
3797 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
David Majnemer0b17d442015-12-15 21:27:59 +00003798 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs,
3799 BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00003800 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003801 }
Chris Lattnere70a0072010-06-29 16:40:28 +00003802 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00003803 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003804
Peter Collingbourne41af7c22014-05-20 17:12:51 +00003805 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
3806 !CS.hasFnAttr(llvm::Attribute::NoInline))
3807 Attrs =
3808 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3809 llvm::Attribute::AlwaysInline);
3810
David Majnemer4e52d6f2015-12-12 05:39:21 +00003811 // Disable inlining inside SEH __try blocks.
3812 if (isSEHTryScope())
Reid Klecknera5930002015-02-11 21:40:48 +00003813 Attrs =
3814 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3815 llvm::Attribute::NoInline);
3816
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003817 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003818 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003819
Adam Nemet1e217bc2016-03-28 22:18:53 +00003820 // Insert instrumentation or attach profile metadata at indirect call sites.
3821 // For more details, see the comment before the definition of
3822 // IPVK_IndirectCallTarget in InstrProfData.inc.
Betul Buyukkurt518276a2016-01-23 22:50:44 +00003823 if (!CS.getCalledFunction())
3824 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
3825 CS.getInstruction(), Callee);
3826
Dan Gohman515a60d2012-02-16 00:57:37 +00003827 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3828 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003829 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003830 AddObjCARCExceptionMetadata(CS.getInstruction());
3831
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003832 // If the call doesn't return, finish the basic block and clear the
3833 // insertion point; this allows the rest of IRgen to discard
3834 // unreachable code.
3835 if (CS.doesNotReturn()) {
Leny Kholodov6aab1112015-06-08 10:23:49 +00003836 if (UnusedReturnSize)
3837 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
John McCall7f416cc2015-09-08 08:05:57 +00003838 SRetPtr.getPointer());
Leny Kholodov6aab1112015-06-08 10:23:49 +00003839
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003840 Builder.CreateUnreachable();
3841 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003842
Mike Stump18bb9282009-05-16 07:57:57 +00003843 // FIXME: For now, emit a dummy basic block because expr emitters in
3844 // generally are not ready to handle emitting expressions at unreachable
3845 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003846 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003847
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003848 // Return a reasonable RValue.
3849 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00003850 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003851
3852 llvm::Instruction *CI = CS.getInstruction();
Mehdi Amini557c20a2016-03-13 21:05:23 +00003853 if (!CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00003854 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003855
John McCall31168b02011-06-15 23:02:42 +00003856 // Emit any writebacks immediately. Arguably this should happen
3857 // after any return-value munging.
3858 if (CallArgs.hasWritebacks())
3859 emitWritebacks(*this, CallArgs);
3860
Nico Weber8cdb3f92015-08-25 18:43:32 +00003861 // The stack cleanup for inalloca arguments has to run out of the normal
3862 // lexical order, so deactivate it and run it manually here.
3863 CallArgs.freeArgumentMemory(*this);
3864
Samuel Antao798f11c2015-11-23 22:04:44 +00003865 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
3866 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
Akira Hatanakac8667622015-11-06 23:56:15 +00003867 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
3868 Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
Samuel Antao798f11c2015-11-23 22:04:44 +00003869 }
Akira Hatanakac8667622015-11-06 23:56:15 +00003870
Hal Finkelee90a222014-09-26 05:04:30 +00003871 RValue Ret = [&] {
3872 switch (RetAI.getKind()) {
3873 case ABIArgInfo::InAlloca:
Leny Kholodov6aab1112015-06-08 10:23:49 +00003874 case ABIArgInfo::Indirect: {
3875 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
3876 if (UnusedReturnSize)
3877 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
John McCall7f416cc2015-09-08 08:05:57 +00003878 SRetPtr.getPointer());
Leny Kholodov6aab1112015-06-08 10:23:49 +00003879 return ret;
3880 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00003881
John McCallf26e73d2016-03-11 04:30:43 +00003882 case ABIArgInfo::CoerceAndExpand: {
3883 auto coercionType = RetAI.getCoerceAndExpandType();
3884 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
3885
3886 Address addr = SRetPtr;
3887 addr = Builder.CreateElementBitCast(addr, coercionType);
3888
3889 unsigned unpaddedIndex = 0;
3890 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3891 llvm::Type *eltType = coercionType->getElementType(i);
3892 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
3893 Address eltAddr = Builder.CreateStructGEP(addr, i, layout);
3894 llvm::Value *elt = Builder.CreateExtractValue(CI, unpaddedIndex++);
3895 Builder.CreateStore(elt, eltAddr);
3896 }
3897 break;
3898 }
3899
Hal Finkelee90a222014-09-26 05:04:30 +00003900 case ABIArgInfo::Ignore:
3901 // If we are ignoring an argument that had a result, make sure to
3902 // construct the appropriate return value for our caller.
3903 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003904
Hal Finkelee90a222014-09-26 05:04:30 +00003905 case ABIArgInfo::Extend:
3906 case ABIArgInfo::Direct: {
3907 llvm::Type *RetIRTy = ConvertType(RetTy);
3908 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
3909 switch (getEvaluationKind(RetTy)) {
3910 case TEK_Complex: {
3911 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
3912 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
3913 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003914 }
Hal Finkelee90a222014-09-26 05:04:30 +00003915 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +00003916 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00003917 bool DestIsVolatile = ReturnValue.isVolatile();
3918
John McCall7f416cc2015-09-08 08:05:57 +00003919 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00003920 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
3921 DestIsVolatile = false;
3922 }
John McCall7f416cc2015-09-08 08:05:57 +00003923 BuildAggStore(*this, CI, DestPtr, DestIsVolatile);
Hal Finkelee90a222014-09-26 05:04:30 +00003924 return RValue::getAggregate(DestPtr);
3925 }
3926 case TEK_Scalar: {
3927 // If the argument doesn't match, perform a bitcast to coerce it. This
3928 // can happen due to trivial type mismatches.
3929 llvm::Value *V = CI;
3930 if (V->getType() != RetIRTy)
3931 V = Builder.CreateBitCast(V, RetIRTy);
3932 return RValue::get(V);
3933 }
3934 }
3935 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003936 }
Hal Finkelee90a222014-09-26 05:04:30 +00003937
John McCall7f416cc2015-09-08 08:05:57 +00003938 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00003939 bool DestIsVolatile = ReturnValue.isVolatile();
3940
John McCall7f416cc2015-09-08 08:05:57 +00003941 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00003942 DestPtr = CreateMemTemp(RetTy, "coerce");
3943 DestIsVolatile = false;
John McCall47fb9502013-03-07 21:37:08 +00003944 }
Hal Finkelee90a222014-09-26 05:04:30 +00003945
3946 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00003947 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
3948 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Hal Finkelee90a222014-09-26 05:04:30 +00003949
3950 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003951 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003952
Hal Finkelee90a222014-09-26 05:04:30 +00003953 case ABIArgInfo::Expand:
3954 llvm_unreachable("Invalid ABI kind for return argument");
Anders Carlsson17490832009-12-24 20:40:36 +00003955 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003956
Hal Finkelee90a222014-09-26 05:04:30 +00003957 llvm_unreachable("Unhandled ABIArgInfo::Kind");
3958 } ();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003959
Samuel Antao798f11c2015-11-23 22:04:44 +00003960 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
3961
Hal Finkelee90a222014-09-26 05:04:30 +00003962 if (Ret.isScalar() && TargetDecl) {
3963 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
3964 llvm::Value *OffsetValue = nullptr;
3965 if (const auto *Offset = AA->getOffset())
3966 OffsetValue = EmitScalarExpr(Offset);
3967
3968 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
3969 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
3970 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
3971 OffsetValue);
3972 }
Daniel Dunbar573884e2008-09-10 07:04:09 +00003973 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00003974
Hal Finkelee90a222014-09-26 05:04:30 +00003975 return Ret;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003976}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00003977
3978/* VarArg handling */
3979
Charles Davisc7d5c942015-09-17 20:55:33 +00003980Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
3981 VAListAddr = VE->isMicrosoftABI()
3982 ? EmitMSVAListRef(VE->getSubExpr())
3983 : EmitVAListRef(VE->getSubExpr());
3984 QualType Ty = VE->getType();
3985 if (VE->isMicrosoftABI())
3986 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003987 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00003988}