blob: f3eaef369a6befb199382caf0db94913ffcf2f32 [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"
John McCall12f23522016-04-04 18:33:08 +000029#include "clang/CodeGen/SwiftCallingConv.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000030#include "clang/Frontend/CodeGenOptions.h"
Bill Wendling706469b2013-02-28 22:49:57 +000031#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/Attributes.h"
Nikolay Haustov8c6538b2016-06-30 09:06:33 +000033#include "llvm/IR/CallingConv.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000034#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000035#include "llvm/IR/DataLayout.h"
36#include "llvm/IR/InlineAsm.h"
Saleem Abdulrasool94cfc602016-04-07 17:49:44 +000037#include "llvm/IR/Intrinsics.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000038#include "llvm/IR/IntrinsicInst.h"
Eli Friedmanf7456192011-06-15 22:09:18 +000039#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000040using namespace clang;
41using namespace CodeGen;
42
43/***/
44
Nikolay Haustov8c6538b2016-06-30 09:06:33 +000045unsigned CodeGenTypes::ClangCallConvToLLVMCallConv(CallingConv CC) {
John McCallab26cfa2010-02-05 21:31:56 +000046 switch (CC) {
47 default: return llvm::CallingConv::C;
48 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
49 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
Douglas Gregora941dca2010-05-18 16:57:00 +000050 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Charles Davisb5a214e2013-08-30 04:39:01 +000051 case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64;
52 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
Anton Korobeynikov231e8752011-04-14 20:06:49 +000053 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
54 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Guy Benyeif0a014b2012-12-25 08:53:55 +000055 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Reid Klecknerd7857f02014-10-24 17:42:17 +000056 // TODO: Add support for __pascal to LLVM.
57 case CC_X86Pascal: return llvm::CallingConv::C;
58 // TODO: Add support for __vectorcall to LLVM.
Reid Kleckner80944df2014-10-31 22:00:51 +000059 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
Alexander Kornienko21de0ae2015-01-20 11:20:41 +000060 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +000061 case CC_OpenCLKernel: return CGM.getTargetCodeGenInfo().getOpenCLKernelCallingConv();
Roman Levenstein35aa5ce2016-03-16 18:00:46 +000062 case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
63 case CC_PreserveAll: return llvm::CallingConv::PreserveAll;
John McCall12f23522016-04-04 18:33:08 +000064 case CC_Swift: return llvm::CallingConv::Swift;
John McCallab26cfa2010-02-05 21:31:56 +000065 }
66}
67
John McCall8ee376f2010-02-24 07:14:12 +000068/// Derives the 'this' type for codegen purposes, i.e. ignoring method
69/// qualification.
70/// FIXME: address space qualification?
John McCall2da83a32010-02-26 00:48:12 +000071static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
72 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
73 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000074}
75
John McCall8ee376f2010-02-24 07:14:12 +000076/// Returns the canonical formal type of the given C++ method.
John McCall2da83a32010-02-26 00:48:12 +000077static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
78 return MD->getType()->getCanonicalTypeUnqualified()
79 .getAs<FunctionProtoType>();
John McCall8ee376f2010-02-24 07:14:12 +000080}
81
82/// Returns the "extra-canonicalized" return type, which discards
83/// qualifiers on the return type. Codegen doesn't care about them,
84/// and it makes ABI code a little easier to be able to assume that
85/// all parameter and return types are top-level unqualified.
John McCall2da83a32010-02-26 00:48:12 +000086static CanQualType GetReturnType(QualType RetTy) {
87 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall8ee376f2010-02-24 07:14:12 +000088}
89
John McCall8dda7b22012-07-07 06:41:13 +000090/// Arrange the argument and result information for a value of the given
91/// unprototyped freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +000092const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +000093CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCalla729c622012-02-17 03:33:10 +000094 // When translating an unprototyped function type, always use a
95 // variadic type.
Alp Toker314cc812014-01-25 16:55:45 +000096 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
Peter Collingbournef7706832014-12-12 23:41:25 +000097 /*instanceMethod=*/false,
98 /*chainCall=*/false, None,
John McCallc56a8b32016-03-11 04:30:31 +000099 FTNP->getExtInfo(), {}, RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +0000100}
101
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000102/// Adds the formal paramaters in FPT to the given prefix. If any parameter in
103/// FPT has pass_object_size attrs, then we'll add parameters for those, too.
104static void appendParameterTypes(const CodeGenTypes &CGT,
105 SmallVectorImpl<CanQualType> &prefix,
John McCallc56a8b32016-03-11 04:30:31 +0000106 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
107 CanQual<FunctionProtoType> FPT,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000108 const FunctionDecl *FD) {
John McCallc56a8b32016-03-11 04:30:31 +0000109 // Fill out paramInfos.
110 if (FPT->hasExtParameterInfos() || !paramInfos.empty()) {
111 assert(paramInfos.size() <= prefix.size());
112 auto protoParamInfos = FPT->getExtParameterInfos();
113 paramInfos.reserve(prefix.size() + protoParamInfos.size());
114 paramInfos.resize(prefix.size());
John McCall12f23522016-04-04 18:33:08 +0000115 paramInfos.append(protoParamInfos.begin(), protoParamInfos.end());
John McCallc56a8b32016-03-11 04:30:31 +0000116 }
117
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000118 // Fast path: unknown target.
119 if (FD == nullptr) {
120 prefix.append(FPT->param_type_begin(), FPT->param_type_end());
121 return;
122 }
123
124 // In the vast majority cases, we'll have precisely FPT->getNumParams()
125 // parameters; the only thing that can change this is the presence of
126 // pass_object_size. So, we preallocate for the common case.
127 prefix.reserve(prefix.size() + FPT->getNumParams());
128
129 assert(FD->getNumParams() == FPT->getNumParams());
130 for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
131 prefix.push_back(FPT->getParamType(I));
132 if (FD->getParamDecl(I)->hasAttr<PassObjectSizeAttr>())
133 prefix.push_back(CGT.getContext().getSizeType());
134 }
135}
136
John McCall8dda7b22012-07-07 06:41:13 +0000137/// Arrange the LLVM function layout for a value of the given function
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000138/// type, on top of any implicit parameters already stored.
139static const CGFunctionInfo &
Peter Collingbournef7706832014-12-12 23:41:25 +0000140arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000141 SmallVectorImpl<CanQualType> &prefix,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000142 CanQual<FunctionProtoType> FTP,
143 const FunctionDecl *FD) {
John McCallc56a8b32016-03-11 04:30:31 +0000144 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
George Burgess IV419996c2016-06-16 23:06:04 +0000145 RequiredArgs Required =
146 RequiredArgs::forPrototypePlus(FTP, prefix.size(), FD);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000147 // FIXME: Kill copy.
John McCallc56a8b32016-03-11 04:30:31 +0000148 appendParameterTypes(CGT, prefix, paramInfos, FTP, FD);
Alp Toker314cc812014-01-25 16:55:45 +0000149 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
John McCallc56a8b32016-03-11 04:30:31 +0000150
Peter Collingbournef7706832014-12-12 23:41:25 +0000151 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
152 /*chainCall=*/false, prefix,
John McCallc56a8b32016-03-11 04:30:31 +0000153 FTP->getExtInfo(), paramInfos,
George Burgess IV419996c2016-06-16 23:06:04 +0000154 Required);
John McCall8ee376f2010-02-24 07:14:12 +0000155}
156
John McCalla729c622012-02-17 03:33:10 +0000157/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000158/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000159const CGFunctionInfo &
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000160CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP,
161 const FunctionDecl *FD) {
John McCalla729c622012-02-17 03:33:10 +0000162 SmallVector<CanQualType, 16> argTypes;
Peter Collingbournef7706832014-12-12 23:41:25 +0000163 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000164 FTP, FD);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000165}
166
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000167static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000168 // Set the appropriate calling convention for the Function.
169 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000170 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000171
172 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000173 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000174
Douglas Gregora941dca2010-05-18 16:57:00 +0000175 if (D->hasAttr<ThisCallAttr>())
176 return CC_X86ThisCall;
177
Reid Klecknerd7857f02014-10-24 17:42:17 +0000178 if (D->hasAttr<VectorCallAttr>())
179 return CC_X86VectorCall;
180
Dawn Perchik335e16b2010-09-03 01:29:35 +0000181 if (D->hasAttr<PascalAttr>())
182 return CC_X86Pascal;
183
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000184 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
185 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
186
Guy Benyeif0a014b2012-12-25 08:53:55 +0000187 if (D->hasAttr<IntelOclBiccAttr>())
188 return CC_IntelOclBicc;
189
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000190 if (D->hasAttr<MSABIAttr>())
191 return IsWindows ? CC_C : CC_X86_64Win64;
192
193 if (D->hasAttr<SysVABIAttr>())
194 return IsWindows ? CC_X86_64SysV : CC_C;
195
Roman Levenstein35aa5ce2016-03-16 18:00:46 +0000196 if (D->hasAttr<PreserveMostAttr>())
197 return CC_PreserveMost;
198
199 if (D->hasAttr<PreserveAllAttr>())
200 return CC_PreserveAll;
201
John McCallab26cfa2010-02-05 21:31:56 +0000202 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000203}
204
John McCalla729c622012-02-17 03:33:10 +0000205/// Arrange the argument and result information for a call to an
206/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000207/// (Zero value of RD means we don't have any meaningful "this" argument type,
208/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000209/// The member function must be an ordinary function, i.e. not a
210/// constructor or destructor.
211const CGFunctionInfo &
212CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000213 const FunctionProtoType *FTP,
214 const CXXMethodDecl *MD) {
John McCalla729c622012-02-17 03:33:10 +0000215 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000216
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000217 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000218 if (RD)
219 argTypes.push_back(GetThisType(Context, RD));
220 else
221 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000222
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000223 return ::arrangeLLVMFunctionInfo(
224 *this, true, argTypes,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000225 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>(), MD);
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000226}
227
John McCalla729c622012-02-17 03:33:10 +0000228/// Arrange the argument and result information for a declaration or
229/// definition of the given C++ non-static member function. The
230/// member function must be an ordinary function, i.e. not a
231/// constructor or destructor.
232const CGFunctionInfo &
233CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000234 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000235 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
236
John McCalla729c622012-02-17 03:33:10 +0000237 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000238
John McCalla729c622012-02-17 03:33:10 +0000239 if (MD->isInstance()) {
240 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000241 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000242 return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
John McCalla729c622012-02-17 03:33:10 +0000243 }
244
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000245 return arrangeFreeFunctionType(prototype, MD);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000246}
247
Richard Smith5179eb72016-06-28 19:03:57 +0000248bool CodeGenTypes::inheritingCtorHasParams(
249 const InheritedConstructor &Inherited, CXXCtorType Type) {
250 // Parameters are unnecessary if we're constructing a base class subobject
251 // and the inherited constructor lives in a virtual base.
252 return Type == Ctor_Complete ||
253 !Inherited.getShadowDecl()->constructsVirtualBase() ||
254 !Target.getCXXABI().hasConstructorVariants();
255 }
256
John McCalla729c622012-02-17 03:33:10 +0000257const CGFunctionInfo &
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000258CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
259 StructorType Type) {
260
John McCalla729c622012-02-17 03:33:10 +0000261 SmallVector<CanQualType, 16> argTypes;
John McCallc56a8b32016-03-11 04:30:31 +0000262 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000263 argTypes.push_back(GetThisType(Context, MD->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000264
Richard Smith5179eb72016-06-28 19:03:57 +0000265 bool PassParams = true;
266
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000267 GlobalDecl GD;
268 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
269 GD = GlobalDecl(CD, toCXXCtorType(Type));
Richard Smith5179eb72016-06-28 19:03:57 +0000270
271 // A base class inheriting constructor doesn't get forwarded arguments
272 // needed to construct a virtual base (or base class thereof).
273 if (auto Inherited = CD->getInheritedConstructor())
274 PassParams = inheritingCtorHasParams(Inherited, toCXXCtorType(Type));
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000275 } else {
276 auto *DD = dyn_cast<CXXDestructorDecl>(MD);
277 GD = GlobalDecl(DD, toCXXDtorType(Type));
278 }
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000279
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000280 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
John McCall5d865c322010-08-31 07:33:07 +0000281
282 // Add the formal parameters.
Richard Smith5179eb72016-06-28 19:03:57 +0000283 if (PassParams)
284 appendParameterTypes(*this, argTypes, paramInfos, FTP, MD);
John McCall5d865c322010-08-31 07:33:07 +0000285
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000286 TheCXXABI.buildStructorSignature(MD, Type, argTypes);
Reid Kleckner89077a12013-12-17 19:46:40 +0000287
288 RequiredArgs required =
Richard Smith5179eb72016-06-28 19:03:57 +0000289 (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size())
290 : RequiredArgs::All);
Reid Kleckner89077a12013-12-17 19:46:40 +0000291
John McCall8dda7b22012-07-07 06:41:13 +0000292 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000293 CanQualType resultType = TheCXXABI.HasThisReturn(GD)
294 ? argTypes.front()
295 : TheCXXABI.hasMostDerivedReturn(GD)
296 ? CGM.getContext().VoidPtrTy
297 : Context.VoidTy;
Peter Collingbournef7706832014-12-12 23:41:25 +0000298 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
299 /*chainCall=*/false, argTypes, extInfo,
John McCallc56a8b32016-03-11 04:30:31 +0000300 paramInfos, required);
301}
302
303static SmallVector<CanQualType, 16>
304getArgTypesForCall(ASTContext &ctx, const CallArgList &args) {
305 SmallVector<CanQualType, 16> argTypes;
306 for (auto &arg : args)
307 argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
308 return argTypes;
309}
310
311static SmallVector<CanQualType, 16>
312getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) {
313 SmallVector<CanQualType, 16> argTypes;
314 for (auto &arg : args)
315 argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
316 return argTypes;
317}
318
319static void addExtParameterInfosForCall(
320 llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
321 const FunctionProtoType *proto,
322 unsigned prefixArgs,
323 unsigned totalArgs) {
324 assert(proto->hasExtParameterInfos());
325 assert(paramInfos.size() <= prefixArgs);
326 assert(proto->getNumParams() + prefixArgs <= totalArgs);
327
328 // Add default infos for any prefix args that don't already have infos.
329 paramInfos.resize(prefixArgs);
330
331 // Add infos for the prototype.
332 auto protoInfos = proto->getExtParameterInfos();
333 paramInfos.append(protoInfos.begin(), protoInfos.end());
334
335 // Add default infos for the variadic arguments.
336 paramInfos.resize(totalArgs);
337}
338
339static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16>
340getExtParameterInfosForCall(const FunctionProtoType *proto,
341 unsigned prefixArgs, unsigned totalArgs) {
342 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result;
343 if (proto->hasExtParameterInfos()) {
344 addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
345 }
346 return result;
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000347}
348
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000349/// Arrange a call to a C++ method, passing the given arguments.
350const CGFunctionInfo &
351CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
352 const CXXConstructorDecl *D,
353 CXXCtorType CtorKind,
354 unsigned ExtraArgs) {
355 // FIXME: Kill copy.
356 SmallVector<CanQualType, 16> ArgTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000357 for (const auto &Arg : args)
358 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000359
360 CanQual<FunctionProtoType> FPT = GetFormalType(D);
George Burgess IV419996c2016-06-16 23:06:04 +0000361 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs, D);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000362 GlobalDecl GD(D, CtorKind);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000363 CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
364 ? ArgTypes.front()
365 : TheCXXABI.hasMostDerivedReturn(GD)
366 ? CGM.getContext().VoidPtrTy
367 : Context.VoidTy;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000368
369 FunctionType::ExtInfo Info = FPT->getExtInfo();
John McCallc56a8b32016-03-11 04:30:31 +0000370 auto ParamInfos = getExtParameterInfosForCall(FPT.getTypePtr(), 1 + ExtraArgs,
371 ArgTypes.size());
Peter Collingbournef7706832014-12-12 23:41:25 +0000372 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
373 /*chainCall=*/false, ArgTypes, Info,
John McCallc56a8b32016-03-11 04:30:31 +0000374 ParamInfos, Required);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000375}
376
John McCalla729c622012-02-17 03:33:10 +0000377/// Arrange the argument and result information for the declaration or
378/// definition of the given function.
379const CGFunctionInfo &
380CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000381 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000382 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000383 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000384
John McCall2da83a32010-02-26 00:48:12 +0000385 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000386
John McCall2da83a32010-02-26 00:48:12 +0000387 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000388
389 // When declaring a function without a prototype, always use a
390 // non-variadic type.
391 if (isa<FunctionNoProtoType>(FTy)) {
392 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Peter Collingbournef7706832014-12-12 23:41:25 +0000393 return arrangeLLVMFunctionInfo(
394 noProto->getReturnType(), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000395 /*chainCall=*/false, None, noProto->getExtInfo(), {},RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000396 }
397
John McCall2da83a32010-02-26 00:48:12 +0000398 assert(isa<FunctionProtoType>(FTy));
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000399 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>(), FD);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000400}
401
John McCalla729c622012-02-17 03:33:10 +0000402/// Arrange the argument and result information for the declaration or
403/// definition of an Objective-C method.
404const CGFunctionInfo &
405CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
406 // It happens that this is the same as a call with no optional
407 // arguments, except also using the formal 'self' type.
408 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
409}
410
411/// Arrange the argument and result information for the function type
412/// through which to perform a send to the given Objective-C method,
413/// using the given receiver type. The receiver type is not always
414/// the 'self' type of the method or even an Objective-C pointer type.
415/// This is *not* the right method for actually performing such a
416/// message send, due to the possibility of optional arguments.
417const CGFunctionInfo &
418CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
419 QualType receiverType) {
420 SmallVector<CanQualType, 16> argTys;
421 argTys.push_back(Context.getCanonicalParamType(receiverType));
422 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000423 // FIXME: Kill copy?
David Majnemer59f77922016-06-24 04:05:48 +0000424 for (const auto *I : MD->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000425 argTys.push_back(Context.getCanonicalParamType(I->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000426 }
John McCall31168b02011-06-15 23:02:42 +0000427
428 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000429 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
430 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000431
David Blaikiebbafb8a2012-03-11 07:00:24 +0000432 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000433 MD->hasAttr<NSReturnsRetainedAttr>())
434 einfo = einfo.withProducesResult(true);
435
John McCalla729c622012-02-17 03:33:10 +0000436 RequiredArgs required =
437 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
438
Peter Collingbournef7706832014-12-12 23:41:25 +0000439 return arrangeLLVMFunctionInfo(
440 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000441 /*chainCall=*/false, argTys, einfo, {}, required);
442}
443
444const CGFunctionInfo &
445CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType,
446 const CallArgList &args) {
447 auto argTypes = getArgTypesForCall(Context, args);
448 FunctionType::ExtInfo einfo;
449
450 return arrangeLLVMFunctionInfo(
451 GetReturnType(returnType), /*instanceMethod=*/false,
452 /*chainCall=*/false, argTypes, einfo, {}, RequiredArgs::All);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000453}
454
John McCalla729c622012-02-17 03:33:10 +0000455const CGFunctionInfo &
456CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000457 // FIXME: Do we need to handle ObjCMethodDecl?
458 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000459
Anders Carlsson6710c532010-02-06 02:44:09 +0000460 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000461 return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
Anders Carlsson6710c532010-02-06 02:44:09 +0000462
463 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000464 return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000465
John McCalla729c622012-02-17 03:33:10 +0000466 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000467}
468
Reid Klecknerc3473512014-08-29 21:43:29 +0000469/// Arrange a thunk that takes 'this' as the first parameter followed by
470/// varargs. Return a void pointer, regardless of the actual return type.
471/// The body of the thunk will end in a musttail call to a function of the
472/// correct type, and the caller will bitcast the function to the correct
473/// prototype.
474const CGFunctionInfo &
475CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) {
476 assert(MD->isVirtual() && "only virtual memptrs have thunks");
477 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
478 CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
Peter Collingbournef7706832014-12-12 23:41:25 +0000479 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
480 /*chainCall=*/false, ArgTys,
John McCallc56a8b32016-03-11 04:30:31 +0000481 FTP->getExtInfo(), {}, RequiredArgs(1));
Reid Klecknerc3473512014-08-29 21:43:29 +0000482}
483
David Majnemerdfa6d202015-03-11 18:36:39 +0000484const CGFunctionInfo &
David Majnemer37fd66e2015-03-13 22:36:55 +0000485CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
486 CXXCtorType CT) {
487 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
488
David Majnemerdfa6d202015-03-11 18:36:39 +0000489 CanQual<FunctionProtoType> FTP = GetFormalType(CD);
490 SmallVector<CanQualType, 2> ArgTys;
491 const CXXRecordDecl *RD = CD->getParent();
492 ArgTys.push_back(GetThisType(Context, RD));
David Majnemer37fd66e2015-03-13 22:36:55 +0000493 if (CT == Ctor_CopyingClosure)
494 ArgTys.push_back(*FTP->param_type_begin());
David Majnemerdfa6d202015-03-11 18:36:39 +0000495 if (RD->getNumVBases() > 0)
496 ArgTys.push_back(Context.IntTy);
497 CallingConv CC = Context.getDefaultCallingConvention(
498 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
499 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
500 /*chainCall=*/false, ArgTys,
John McCallc56a8b32016-03-11 04:30:31 +0000501 FunctionType::ExtInfo(CC), {},
502 RequiredArgs::All);
David Majnemerdfa6d202015-03-11 18:36:39 +0000503}
504
John McCallc818bbb2012-12-07 07:03:17 +0000505/// Arrange a call as unto a free function, except possibly with an
506/// additional number of formal parameters considered required.
507static const CGFunctionInfo &
508arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000509 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000510 const CallArgList &args,
511 const FunctionType *fnType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000512 unsigned numExtraRequiredArgs,
513 bool chainCall) {
John McCallc818bbb2012-12-07 07:03:17 +0000514 assert(args.size() >= numExtraRequiredArgs);
515
John McCallc56a8b32016-03-11 04:30:31 +0000516 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
517
John McCallc818bbb2012-12-07 07:03:17 +0000518 // In most cases, there are no optional arguments.
519 RequiredArgs required = RequiredArgs::All;
520
521 // If we have a variadic prototype, the required arguments are the
522 // extra prefix plus the arguments in the prototype.
523 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
524 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000525 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000526
John McCallc56a8b32016-03-11 04:30:31 +0000527 if (proto->hasExtParameterInfos())
528 addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
529 args.size());
530
John McCallc818bbb2012-12-07 07:03:17 +0000531 // If we don't have a prototype at all, but we're supposed to
532 // explicitly use the variadic convention for unprototyped calls,
533 // treat all of the arguments as required but preserve the nominal
534 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000535 } else if (CGM.getTargetCodeGenInfo()
536 .isNoProtoCallVariadic(args,
537 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000538 required = RequiredArgs(args.size());
539 }
540
Peter Collingbournef7706832014-12-12 23:41:25 +0000541 // FIXME: Kill copy.
542 SmallVector<CanQualType, 16> argTypes;
543 for (const auto &arg : args)
544 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
545 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
546 /*instanceMethod=*/false, chainCall,
John McCallc56a8b32016-03-11 04:30:31 +0000547 argTypes, fnType->getExtInfo(), paramInfos,
548 required);
John McCallc818bbb2012-12-07 07:03:17 +0000549}
550
John McCalla729c622012-02-17 03:33:10 +0000551/// Figure out the rules for calling a function with the given formal
552/// type using the given arguments. The arguments are necessary
553/// because the function might be unprototyped, in which case it's
554/// target-dependent in crazy ways.
555const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000556CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
Peter Collingbournef7706832014-12-12 23:41:25 +0000557 const FunctionType *fnType,
558 bool chainCall) {
559 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
560 chainCall ? 1 : 0, chainCall);
John McCallc818bbb2012-12-07 07:03:17 +0000561}
John McCalla729c622012-02-17 03:33:10 +0000562
John McCallc56a8b32016-03-11 04:30:31 +0000563/// A block function is essentially a free function with an
John McCallc818bbb2012-12-07 07:03:17 +0000564/// extra implicit argument.
565const CGFunctionInfo &
566CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
567 const FunctionType *fnType) {
Peter Collingbournef7706832014-12-12 23:41:25 +0000568 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
569 /*chainCall=*/false);
John McCalla729c622012-02-17 03:33:10 +0000570}
571
572const CGFunctionInfo &
John McCallc56a8b32016-03-11 04:30:31 +0000573CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto,
574 const FunctionArgList &params) {
575 auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
576 auto argTypes = getArgTypesForDeclaration(Context, params);
577
George Burgess IV419996c2016-06-16 23:06:04 +0000578 return arrangeLLVMFunctionInfo(
579 GetReturnType(proto->getReturnType()),
580 /*instanceMethod*/ false, /*chainCall*/ false, argTypes,
581 proto->getExtInfo(), paramInfos,
582 RequiredArgs::forPrototypePlus(proto, 1, nullptr));
John McCallc56a8b32016-03-11 04:30:31 +0000583}
584
585const CGFunctionInfo &
586CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType,
587 const CallArgList &args) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000588 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000589 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000590 for (const auto &Arg : args)
591 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Peter Collingbournef7706832014-12-12 23:41:25 +0000592 return arrangeLLVMFunctionInfo(
593 GetReturnType(resultType), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000594 /*chainCall=*/false, argTypes, FunctionType::ExtInfo(),
595 /*paramInfos=*/ {}, RequiredArgs::All);
John McCall8dda7b22012-07-07 06:41:13 +0000596}
597
John McCallc56a8b32016-03-11 04:30:31 +0000598const CGFunctionInfo &
599CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType,
600 const FunctionArgList &args) {
601 auto argTypes = getArgTypesForDeclaration(Context, args);
602
603 return arrangeLLVMFunctionInfo(
604 GetReturnType(resultType), /*instanceMethod=*/false, /*chainCall=*/false,
605 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
606}
607
608const CGFunctionInfo &
609CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType,
610 ArrayRef<CanQualType> argTypes) {
611 return arrangeLLVMFunctionInfo(
612 resultType, /*instanceMethod=*/false, /*chainCall=*/false,
613 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
614}
615
John McCall8dda7b22012-07-07 06:41:13 +0000616/// Arrange a call to a C++ method, passing the given arguments.
617const CGFunctionInfo &
618CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
John McCallc56a8b32016-03-11 04:30:31 +0000619 const FunctionProtoType *proto,
John McCall8dda7b22012-07-07 06:41:13 +0000620 RequiredArgs required) {
John McCallc56a8b32016-03-11 04:30:31 +0000621 unsigned numRequiredArgs =
622 (proto->isVariadic() ? required.getNumRequiredArgs() : args.size());
623 unsigned numPrefixArgs = numRequiredArgs - proto->getNumParams();
624 auto paramInfos =
625 getExtParameterInfosForCall(proto, numPrefixArgs, args.size());
626
John McCall8dda7b22012-07-07 06:41:13 +0000627 // FIXME: Kill copy.
John McCallc56a8b32016-03-11 04:30:31 +0000628 auto argTypes = getArgTypesForCall(Context, args);
John McCall8dda7b22012-07-07 06:41:13 +0000629
John McCallc56a8b32016-03-11 04:30:31 +0000630 FunctionType::ExtInfo info = proto->getExtInfo();
Peter Collingbournef7706832014-12-12 23:41:25 +0000631 return arrangeLLVMFunctionInfo(
John McCallc56a8b32016-03-11 04:30:31 +0000632 GetReturnType(proto->getReturnType()), /*instanceMethod=*/true,
633 /*chainCall=*/false, argTypes, info, paramInfos, required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000634}
635
John McCalla729c622012-02-17 03:33:10 +0000636const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Peter Collingbournef7706832014-12-12 23:41:25 +0000637 return arrangeLLVMFunctionInfo(
638 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000639 None, FunctionType::ExtInfo(), {}, RequiredArgs::All);
640}
641
642const CGFunctionInfo &
643CodeGenTypes::arrangeCall(const CGFunctionInfo &signature,
644 const CallArgList &args) {
645 assert(signature.arg_size() <= args.size());
646 if (signature.arg_size() == args.size())
647 return signature;
648
649 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
650 auto sigParamInfos = signature.getExtParameterInfos();
651 if (!sigParamInfos.empty()) {
652 paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
653 paramInfos.resize(args.size());
654 }
655
656 auto argTypes = getArgTypesForCall(Context, args);
657
658 assert(signature.getRequiredArgs().allowsOptionalArgs());
659 return arrangeLLVMFunctionInfo(signature.getReturnType(),
660 signature.isInstanceMethod(),
661 signature.isChainCall(),
662 argTypes,
663 signature.getExtInfo(),
664 paramInfos,
665 signature.getRequiredArgs());
John McCalla738c252011-03-09 04:27:21 +0000666}
667
John McCalla729c622012-02-17 03:33:10 +0000668/// Arrange the argument and result information for an abstract value
669/// of a given function type. This is the method which all of the
670/// above functions ultimately defer to.
671const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000672CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000673 bool instanceMethod,
674 bool chainCall,
John McCall8dda7b22012-07-07 06:41:13 +0000675 ArrayRef<CanQualType> argTypes,
676 FunctionType::ExtInfo info,
John McCallc56a8b32016-03-11 04:30:31 +0000677 ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
John McCall8dda7b22012-07-07 06:41:13 +0000678 RequiredArgs required) {
Saleem Abdulrasool32d1a962014-11-25 03:49:50 +0000679 assert(std::all_of(argTypes.begin(), argTypes.end(),
680 std::mem_fun_ref(&CanQualType::isCanonicalAsParam)));
John McCall2da83a32010-02-26 00:48:12 +0000681
Daniel Dunbare0be8292009-02-03 00:07:12 +0000682 // Lookup or create unique function info.
683 llvm::FoldingSetNodeID ID;
John McCallc56a8b32016-03-11 04:30:31 +0000684 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos,
685 required, resultType, argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000686
Craig Topper8a13c412014-05-21 05:09:00 +0000687 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000688 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000689 if (FI)
690 return *FI;
691
John McCallc56a8b32016-03-11 04:30:31 +0000692 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
693
John McCalla729c622012-02-17 03:33:10 +0000694 // Construct the function info. We co-allocate the ArgInfos.
Peter Collingbournef7706832014-12-12 23:41:25 +0000695 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
John McCallc56a8b32016-03-11 04:30:31 +0000696 paramInfos, resultType, argTypes, required);
John McCalla729c622012-02-17 03:33:10 +0000697 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000698
David Blaikie82e95a32014-11-19 07:49:47 +0000699 bool inserted = FunctionsBeingProcessed.insert(FI).second;
700 (void)inserted;
John McCalla729c622012-02-17 03:33:10 +0000701 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000702
Daniel Dunbar313321e2009-02-03 05:31:23 +0000703 // Compute ABI information.
John McCall12f23522016-04-04 18:33:08 +0000704 if (info.getCC() != CC_Swift) {
705 getABIInfo().computeInfo(*FI);
706 } else {
707 swiftcall::computeABIInfo(CGM, *FI);
708 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000709
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000710 // Loop over all of the computed argument and return value info. If any of
711 // them are direct or extend without a specified coerce type, specify the
712 // default now.
John McCalla729c622012-02-17 03:33:10 +0000713 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000714 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000715 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000716
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000717 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000718 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000719 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000720
John McCalla729c622012-02-17 03:33:10 +0000721 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
722 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000723
Daniel Dunbare0be8292009-02-03 00:07:12 +0000724 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000725}
726
John McCalla729c622012-02-17 03:33:10 +0000727CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Peter Collingbournef7706832014-12-12 23:41:25 +0000728 bool instanceMethod,
729 bool chainCall,
John McCalla729c622012-02-17 03:33:10 +0000730 const FunctionType::ExtInfo &info,
John McCallc56a8b32016-03-11 04:30:31 +0000731 ArrayRef<ExtParameterInfo> paramInfos,
John McCalla729c622012-02-17 03:33:10 +0000732 CanQualType resultType,
733 ArrayRef<CanQualType> argTypes,
734 RequiredArgs required) {
John McCallc56a8b32016-03-11 04:30:31 +0000735 assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
736
737 void *buffer =
738 operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
739 argTypes.size() + 1, paramInfos.size()));
740
John McCalla729c622012-02-17 03:33:10 +0000741 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
742 FI->CallingConvention = llvmCC;
743 FI->EffectiveCallingConvention = llvmCC;
744 FI->ASTCallingConvention = info.getCC();
Peter Collingbournef7706832014-12-12 23:41:25 +0000745 FI->InstanceMethod = instanceMethod;
746 FI->ChainCall = chainCall;
John McCalla729c622012-02-17 03:33:10 +0000747 FI->NoReturn = info.getNoReturn();
748 FI->ReturnsRetained = info.getProducesResult();
749 FI->Required = required;
750 FI->HasRegParm = info.getHasRegParm();
751 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000752 FI->ArgStruct = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +0000753 FI->ArgStructAlign = 0;
John McCalla729c622012-02-17 03:33:10 +0000754 FI->NumArgs = argTypes.size();
John McCallc56a8b32016-03-11 04:30:31 +0000755 FI->HasExtParameterInfos = !paramInfos.empty();
John McCalla729c622012-02-17 03:33:10 +0000756 FI->getArgsBuffer()[0].type = resultType;
757 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
758 FI->getArgsBuffer()[i + 1].type = argTypes[i];
John McCallc56a8b32016-03-11 04:30:31 +0000759 for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
760 FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
John McCalla729c622012-02-17 03:33:10 +0000761 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000762}
763
764/***/
765
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000766namespace {
767// ABIArgInfo::Expand implementation.
768
769// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
770struct TypeExpansion {
771 enum TypeExpansionKind {
772 // Elements of constant arrays are expanded recursively.
773 TEK_ConstantArray,
774 // Record fields are expanded recursively (but if record is a union, only
775 // the field with the largest size is expanded).
776 TEK_Record,
777 // For complex types, real and imaginary parts are expanded recursively.
778 TEK_Complex,
779 // All other types are not expandable.
780 TEK_None
781 };
782
783 const TypeExpansionKind Kind;
784
785 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000786 virtual ~TypeExpansion() {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000787};
788
789struct ConstantArrayExpansion : TypeExpansion {
790 QualType EltTy;
791 uint64_t NumElts;
792
793 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
794 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
795 static bool classof(const TypeExpansion *TE) {
796 return TE->Kind == TEK_ConstantArray;
797 }
798};
799
800struct RecordExpansion : TypeExpansion {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000801 SmallVector<const CXXBaseSpecifier *, 1> Bases;
802
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000803 SmallVector<const FieldDecl *, 1> Fields;
804
Reid Klecknere9f6a712014-10-31 17:10:41 +0000805 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
806 SmallVector<const FieldDecl *, 1> &&Fields)
Benjamin Kramer0bb97742016-02-13 16:00:13 +0000807 : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
808 Fields(std::move(Fields)) {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000809 static bool classof(const TypeExpansion *TE) {
810 return TE->Kind == TEK_Record;
811 }
812};
813
814struct ComplexExpansion : TypeExpansion {
815 QualType EltTy;
816
817 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
818 static bool classof(const TypeExpansion *TE) {
819 return TE->Kind == TEK_Complex;
820 }
821};
822
823struct NoExpansion : TypeExpansion {
824 NoExpansion() : TypeExpansion(TEK_None) {}
825 static bool classof(const TypeExpansion *TE) {
826 return TE->Kind == TEK_None;
827 }
828};
829} // namespace
830
831static std::unique_ptr<TypeExpansion>
832getTypeExpansion(QualType Ty, const ASTContext &Context) {
833 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
834 return llvm::make_unique<ConstantArrayExpansion>(
835 AT->getElementType(), AT->getSize().getZExtValue());
836 }
837 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000838 SmallVector<const CXXBaseSpecifier *, 1> Bases;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000839 SmallVector<const FieldDecl *, 1> Fields;
Bob Wilsone826a2a2011-08-03 05:58:22 +0000840 const RecordDecl *RD = RT->getDecl();
841 assert(!RD->hasFlexibleArrayMember() &&
842 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000843 if (RD->isUnion()) {
844 // Unions can be here only in degenerative cases - all the fields are same
845 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000846 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000847 CharUnits UnionSize = CharUnits::Zero();
848
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000849 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000850 // Skip zero length bitfields.
851 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
852 continue;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000853 assert(!FD->isBitField() &&
854 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000855 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000856 if (UnionSize < FieldSize) {
857 UnionSize = FieldSize;
858 LargestFD = FD;
859 }
860 }
861 if (LargestFD)
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000862 Fields.push_back(LargestFD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000863 } else {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000864 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
865 assert(!CXXRD->isDynamicClass() &&
866 "cannot expand vtable pointers in dynamic classes");
867 for (const CXXBaseSpecifier &BS : CXXRD->bases())
868 Bases.push_back(&BS);
869 }
870
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000871 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000872 // Skip zero length bitfields.
873 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
874 continue;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000875 assert(!FD->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000876 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000877 Fields.push_back(FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000878 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000879 }
Reid Klecknere9f6a712014-10-31 17:10:41 +0000880 return llvm::make_unique<RecordExpansion>(std::move(Bases),
881 std::move(Fields));
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000882 }
883 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
884 return llvm::make_unique<ComplexExpansion>(CT->getElementType());
885 }
886 return llvm::make_unique<NoExpansion>();
887}
888
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000889static int getExpansionSize(QualType Ty, const ASTContext &Context) {
890 auto Exp = getTypeExpansion(Ty, Context);
891 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
892 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
893 }
894 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
895 int Res = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +0000896 for (auto BS : RExp->Bases)
897 Res += getExpansionSize(BS->getType(), Context);
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000898 for (auto FD : RExp->Fields)
899 Res += getExpansionSize(FD->getType(), Context);
900 return Res;
901 }
902 if (isa<ComplexExpansion>(Exp.get()))
903 return 2;
904 assert(isa<NoExpansion>(Exp.get()));
905 return 1;
906}
907
Alexey Samsonov153004f2014-09-29 22:08:00 +0000908void
909CodeGenTypes::getExpandedTypes(QualType Ty,
910 SmallVectorImpl<llvm::Type *>::iterator &TI) {
911 auto Exp = getTypeExpansion(Ty, Context);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000912 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
913 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
Alexey Samsonov153004f2014-09-29 22:08:00 +0000914 getExpandedTypes(CAExp->EltTy, TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000915 }
916 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000917 for (auto BS : RExp->Bases)
918 getExpandedTypes(BS->getType(), TI);
919 for (auto FD : RExp->Fields)
Alexey Samsonov153004f2014-09-29 22:08:00 +0000920 getExpandedTypes(FD->getType(), TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000921 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
922 llvm::Type *EltTy = ConvertType(CExp->EltTy);
Alexey Samsonov153004f2014-09-29 22:08:00 +0000923 *TI++ = EltTy;
924 *TI++ = EltTy;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000925 } else {
926 assert(isa<NoExpansion>(Exp.get()));
Alexey Samsonov153004f2014-09-29 22:08:00 +0000927 *TI++ = ConvertType(Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000928 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000929}
930
John McCall7f416cc2015-09-08 08:05:57 +0000931static void forConstantArrayExpansion(CodeGenFunction &CGF,
932 ConstantArrayExpansion *CAE,
933 Address BaseAddr,
934 llvm::function_ref<void(Address)> Fn) {
935 CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
936 CharUnits EltAlign =
937 BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
938
939 for (int i = 0, n = CAE->NumElts; i < n; i++) {
940 llvm::Value *EltAddr =
941 CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i);
942 Fn(Address(EltAddr, EltAlign));
943 }
944}
945
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000946void CodeGenFunction::ExpandTypeFromArgs(
John McCall12f23522016-04-04 18:33:08 +0000947 QualType Ty, LValue LV, SmallVectorImpl<llvm::Value *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000948 assert(LV.isSimple() &&
949 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000950
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000951 auto Exp = getTypeExpansion(Ty, getContext());
952 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000953 forConstantArrayExpansion(*this, CAExp, LV.getAddress(),
954 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000955 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
956 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
John McCall7f416cc2015-09-08 08:05:57 +0000957 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000958 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000959 Address This = LV.getAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +0000960 for (const CXXBaseSpecifier *BS : RExp->Bases) {
961 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +0000962 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +0000963 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
964 /*NullCheckValue=*/false, SourceLocation());
965 LValue SubLV = MakeAddrLValue(Base, BS->getType());
966
967 // Recurse onto bases.
968 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
969 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000970 for (auto FD : RExp->Fields) {
971 // FIXME: What are the right qualifiers here?
Reid Kleckner9d031092016-05-02 22:42:34 +0000972 LValue SubLV = EmitLValueForFieldInitialization(LV, FD);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000973 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000974 }
John McCall7f416cc2015-09-08 08:05:57 +0000975 } else if (isa<ComplexExpansion>(Exp.get())) {
976 auto realValue = *AI++;
977 auto imagValue = *AI++;
978 EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000979 } else {
980 assert(isa<NoExpansion>(Exp.get()));
981 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000982 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000983}
984
985void CodeGenFunction::ExpandTypeToArgs(
986 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
987 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
988 auto Exp = getTypeExpansion(Ty, getContext());
989 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000990 forConstantArrayExpansion(*this, CAExp, RV.getAggregateAddress(),
991 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000992 RValue EltRV =
993 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
994 ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
John McCall7f416cc2015-09-08 08:05:57 +0000995 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000996 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000997 Address This = RV.getAggregateAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +0000998 for (const CXXBaseSpecifier *BS : RExp->Bases) {
999 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +00001000 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +00001001 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1002 /*NullCheckValue=*/false, SourceLocation());
1003 RValue BaseRV = RValue::getAggregate(Base);
1004
1005 // Recurse onto bases.
1006 ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
1007 IRCallArgPos);
1008 }
1009
1010 LValue LV = MakeAddrLValue(This, Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001011 for (auto FD : RExp->Fields) {
1012 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
1013 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
1014 IRCallArgPos);
1015 }
1016 } else if (isa<ComplexExpansion>(Exp.get())) {
1017 ComplexPairTy CV = RV.getComplexVal();
1018 IRCallArgs[IRCallArgPos++] = CV.first;
1019 IRCallArgs[IRCallArgPos++] = CV.second;
1020 } else {
1021 assert(isa<NoExpansion>(Exp.get()));
1022 assert(RV.isScalar() &&
1023 "Unexpected non-scalar rvalue during struct expansion.");
1024
1025 // Insert a bitcast as needed.
1026 llvm::Value *V = RV.getScalarVal();
1027 if (IRCallArgPos < IRFuncTy->getNumParams() &&
1028 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
1029 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
1030
1031 IRCallArgs[IRCallArgPos++] = V;
1032 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001033}
1034
John McCall7f416cc2015-09-08 08:05:57 +00001035/// Create a temporary allocation for the purposes of coercion.
1036static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
1037 CharUnits MinAlign) {
1038 // Don't use an alignment that's worse than what LLVM would prefer.
1039 auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty);
1040 CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
1041
1042 return CGF.CreateTempAlloca(Ty, Align);
1043}
1044
Chris Lattner895c52b2010-06-27 06:04:18 +00001045/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +00001046/// accessing some number of bytes out of it, try to gep into the struct to get
1047/// at its inner goodness. Dive as deep as possible without entering an element
1048/// with an in-memory size smaller than DstSize.
John McCall7f416cc2015-09-08 08:05:57 +00001049static Address
1050EnterStructPointerForCoercedAccess(Address SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +00001051 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +00001052 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +00001053 // We can't dive into a zero-element struct.
1054 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001055
Chris Lattner2192fe52011-07-18 04:24:23 +00001056 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001057
Chris Lattner1cd66982010-06-27 05:56:15 +00001058 // 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 +00001059 // first element is the same size as the whole struct, we can enter it. The
1060 // comparison must be made on the store size and not the alloca size. Using
1061 // the alloca size may overstate the size of the load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001062 uint64_t FirstEltSize =
James Molloy90d61012014-08-29 10:17:52 +00001063 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001064 if (FirstEltSize < DstSize &&
James Molloy90d61012014-08-29 10:17:52 +00001065 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +00001066 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001067
Chris Lattner1cd66982010-06-27 05:56:15 +00001068 // GEP into the first element.
John McCall7f416cc2015-09-08 08:05:57 +00001069 SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, CharUnits(), "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001070
Chris Lattner1cd66982010-06-27 05:56:15 +00001071 // If the first element is a struct, recurse.
John McCall7f416cc2015-09-08 08:05:57 +00001072 llvm::Type *SrcTy = SrcPtr.getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001073 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +00001074 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +00001075
1076 return SrcPtr;
1077}
1078
Chris Lattner055097f2010-06-27 06:26:04 +00001079/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
1080/// are either integers or pointers. This does a truncation of the value if it
1081/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001082///
1083/// This behaves as if the value were coerced through memory, so on big-endian
1084/// targets the high bits are preserved in a truncation, while little-endian
1085/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +00001086static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +00001087 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +00001088 CodeGenFunction &CGF) {
1089 if (Val->getType() == Ty)
1090 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001091
Chris Lattner055097f2010-06-27 06:26:04 +00001092 if (isa<llvm::PointerType>(Val->getType())) {
1093 // If this is Pointer->Pointer avoid conversion to and from int.
1094 if (isa<llvm::PointerType>(Ty))
1095 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001096
Chris Lattner055097f2010-06-27 06:26:04 +00001097 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +00001098 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +00001099 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001100
Chris Lattner2192fe52011-07-18 04:24:23 +00001101 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +00001102 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +00001103 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001104
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001105 if (Val->getType() != DestIntTy) {
1106 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
1107 if (DL.isBigEndian()) {
1108 // Preserve the high bits on big-endian targets.
1109 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +00001110 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
1111 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
1112
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001113 if (SrcSize > DstSize) {
1114 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
1115 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
1116 } else {
1117 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
1118 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
1119 }
1120 } else {
1121 // Little-endian targets preserve the low bits. No shifts required.
1122 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
1123 }
1124 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001125
Chris Lattner055097f2010-06-27 06:26:04 +00001126 if (isa<llvm::PointerType>(Ty))
1127 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
1128 return Val;
1129}
1130
Chris Lattner1cd66982010-06-27 05:56:15 +00001131
1132
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001133/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001134/// a pointer to an object of type \arg Ty, known to be aligned to
1135/// \arg SrcAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001136///
1137/// This safely handles the case when the src type is smaller than the
1138/// destination type; in this situation the values of bits which not
1139/// present in the src are undefined.
John McCall7f416cc2015-09-08 08:05:57 +00001140static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001141 CodeGenFunction &CGF) {
John McCall7f416cc2015-09-08 08:05:57 +00001142 llvm::Type *SrcTy = Src.getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001143
Chris Lattnerd200eda2010-06-28 22:51:39 +00001144 // If SrcTy and Ty are the same, just do a load.
1145 if (SrcTy == Ty)
John McCall7f416cc2015-09-08 08:05:57 +00001146 return CGF.Builder.CreateLoad(Src);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001147
Micah Villmowdd31ca12012-10-08 16:25:52 +00001148 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001149
Chris Lattner2192fe52011-07-18 04:24:23 +00001150 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001151 Src = EnterStructPointerForCoercedAccess(Src, SrcSTy, DstSize, CGF);
1152 SrcTy = Src.getType()->getElementType();
Chris Lattner1cd66982010-06-27 05:56:15 +00001153 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001154
Micah Villmowdd31ca12012-10-08 16:25:52 +00001155 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001156
Chris Lattner055097f2010-06-27 06:26:04 +00001157 // If the source and destination are integer or pointer types, just do an
1158 // extension or truncation to the desired type.
1159 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
1160 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
John McCall7f416cc2015-09-08 08:05:57 +00001161 llvm::Value *Load = CGF.Builder.CreateLoad(Src);
Chris Lattner055097f2010-06-27 06:26:04 +00001162 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
1163 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001164
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001165 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +00001166 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +00001167 // Generally SrcSize is never greater than DstSize, since this means we are
1168 // losing bits. However, this can happen in cases where the structure has
1169 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +00001170 //
Mike Stump18bb9282009-05-16 07:57:57 +00001171 // FIXME: Assert that we aren't truncating non-padding bits when have access
1172 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001173 Src = CGF.Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(Ty));
1174 return CGF.Builder.CreateLoad(Src);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001175 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001176
John McCall7f416cc2015-09-08 08:05:57 +00001177 // Otherwise do coercion through memory. This is stupid, but simple.
1178 Address Tmp = CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment());
1179 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1180 Address SrcCasted = CGF.Builder.CreateBitCast(Src, CGF.Int8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001181 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
1182 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
John McCall7f416cc2015-09-08 08:05:57 +00001183 false);
1184 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001185}
1186
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001187// Function to store a first-class aggregate into memory. We prefer to
1188// store the elements rather than the aggregate to be more friendly to
1189// fast-isel.
1190// FIXME: Do we need to recurse here?
1191static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
John McCall7f416cc2015-09-08 08:05:57 +00001192 Address Dest, bool DestIsVolatile) {
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001193 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +00001194 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001195 dyn_cast<llvm::StructType>(Val->getType())) {
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001196 const llvm::StructLayout *Layout =
1197 CGF.CGM.getDataLayout().getStructLayout(STy);
1198
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001199 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00001200 auto EltOffset = CharUnits::fromQuantity(Layout->getElementOffset(i));
1201 Address EltPtr = CGF.Builder.CreateStructGEP(Dest, i, EltOffset);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001202 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
John McCall7f416cc2015-09-08 08:05:57 +00001203 CGF.Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001204 }
1205 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001206 CGF.Builder.CreateStore(Val, Dest, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001207 }
1208}
1209
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001210/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001211/// where the source and destination may have different types. The
1212/// destination is known to be aligned to \arg DstAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001213///
1214/// This safely handles the case when the src type is larger than the
1215/// destination type; the upper bits of the src will be lost.
1216static void CreateCoercedStore(llvm::Value *Src,
John McCall7f416cc2015-09-08 08:05:57 +00001217 Address Dst,
Anders Carlsson17490832009-12-24 20:40:36 +00001218 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001219 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001220 llvm::Type *SrcTy = Src->getType();
John McCall7f416cc2015-09-08 08:05:57 +00001221 llvm::Type *DstTy = Dst.getType()->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +00001222 if (SrcTy == DstTy) {
John McCall7f416cc2015-09-08 08:05:57 +00001223 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattnerd200eda2010-06-28 22:51:39 +00001224 return;
1225 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001226
Micah Villmowdd31ca12012-10-08 16:25:52 +00001227 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001228
Chris Lattner2192fe52011-07-18 04:24:23 +00001229 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001230 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy, SrcSize, CGF);
1231 DstTy = Dst.getType()->getElementType();
Chris Lattner895c52b2010-06-27 06:04:18 +00001232 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001233
Chris Lattner055097f2010-06-27 06:26:04 +00001234 // If the source and destination are integer or pointer types, just do an
1235 // extension or truncation to the desired type.
1236 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1237 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1238 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
John McCall7f416cc2015-09-08 08:05:57 +00001239 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattner055097f2010-06-27 06:26:04 +00001240 return;
1241 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001242
Micah Villmowdd31ca12012-10-08 16:25:52 +00001243 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001244
Daniel Dunbar313321e2009-02-03 05:31:23 +00001245 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001246 if (SrcSize <= DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00001247 Dst = CGF.Builder.CreateBitCast(Dst, llvm::PointerType::getUnqual(SrcTy));
1248 BuildAggStore(CGF, Src, Dst, DstIsVolatile);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001249 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001250 // Otherwise do coercion through memory. This is stupid, but
1251 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001252
1253 // Generally SrcSize is never greater than DstSize, since this means we are
1254 // losing bits. However, this can happen in cases where the structure has
1255 // additional padding, for example due to a user specified alignment.
1256 //
1257 // FIXME: Assert that we aren't truncating non-padding bits when have access
1258 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001259 Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
1260 CGF.Builder.CreateStore(Src, Tmp);
1261 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1262 Address DstCasted = CGF.Builder.CreateBitCast(Dst, CGF.Int8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001263 CGF.Builder.CreateMemCpy(DstCasted, Casted,
1264 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
John McCall7f416cc2015-09-08 08:05:57 +00001265 false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001266 }
1267}
1268
John McCall7f416cc2015-09-08 08:05:57 +00001269static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
1270 const ABIArgInfo &info) {
1271 if (unsigned offset = info.getDirectOffset()) {
1272 addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
1273 addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
1274 CharUnits::fromQuantity(offset));
1275 addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
1276 }
1277 return addr;
1278}
1279
Alexey Samsonov153004f2014-09-29 22:08:00 +00001280namespace {
1281
1282/// Encapsulates information about the way function arguments from
1283/// CGFunctionInfo should be passed to actual LLVM IR function.
1284class ClangToLLVMArgMapping {
1285 static const unsigned InvalidIndex = ~0U;
1286 unsigned InallocaArgNo;
1287 unsigned SRetArgNo;
1288 unsigned TotalIRArgs;
1289
1290 /// Arguments of LLVM IR function corresponding to single Clang argument.
1291 struct IRArgs {
1292 unsigned PaddingArgIndex;
1293 // Argument is expanded to IR arguments at positions
1294 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1295 unsigned FirstArgIndex;
1296 unsigned NumberOfArgs;
1297
1298 IRArgs()
1299 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1300 NumberOfArgs(0) {}
1301 };
1302
1303 SmallVector<IRArgs, 8> ArgInfo;
1304
1305public:
1306 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1307 bool OnlyRequiredArgs = false)
1308 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1309 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1310 construct(Context, FI, OnlyRequiredArgs);
1311 }
1312
1313 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1314 unsigned getInallocaArgNo() const {
1315 assert(hasInallocaArg());
1316 return InallocaArgNo;
1317 }
1318
1319 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1320 unsigned getSRetArgNo() const {
1321 assert(hasSRetArg());
1322 return SRetArgNo;
1323 }
1324
1325 unsigned totalIRArgs() const { return TotalIRArgs; }
1326
1327 bool hasPaddingArg(unsigned ArgNo) const {
1328 assert(ArgNo < ArgInfo.size());
1329 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1330 }
1331 unsigned getPaddingArgNo(unsigned ArgNo) const {
1332 assert(hasPaddingArg(ArgNo));
1333 return ArgInfo[ArgNo].PaddingArgIndex;
1334 }
1335
1336 /// Returns index of first IR argument corresponding to ArgNo, and their
1337 /// quantity.
1338 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1339 assert(ArgNo < ArgInfo.size());
1340 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1341 ArgInfo[ArgNo].NumberOfArgs);
1342 }
1343
1344private:
1345 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1346 bool OnlyRequiredArgs);
1347};
1348
1349void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1350 const CGFunctionInfo &FI,
1351 bool OnlyRequiredArgs) {
1352 unsigned IRArgNo = 0;
1353 bool SwapThisWithSRet = false;
1354 const ABIArgInfo &RetAI = FI.getReturnInfo();
1355
1356 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1357 SwapThisWithSRet = RetAI.isSRetAfterThis();
1358 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1359 }
1360
1361 unsigned ArgNo = 0;
1362 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1363 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1364 ++I, ++ArgNo) {
1365 assert(I != FI.arg_end());
1366 QualType ArgType = I->type;
1367 const ABIArgInfo &AI = I->info;
1368 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1369 auto &IRArgs = ArgInfo[ArgNo];
1370
1371 if (AI.getPaddingType())
1372 IRArgs.PaddingArgIndex = IRArgNo++;
1373
1374 switch (AI.getKind()) {
1375 case ABIArgInfo::Extend:
1376 case ABIArgInfo::Direct: {
1377 // FIXME: handle sseregparm someday...
1378 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1379 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1380 IRArgs.NumberOfArgs = STy->getNumElements();
1381 } else {
1382 IRArgs.NumberOfArgs = 1;
1383 }
1384 break;
1385 }
1386 case ABIArgInfo::Indirect:
1387 IRArgs.NumberOfArgs = 1;
1388 break;
1389 case ABIArgInfo::Ignore:
1390 case ABIArgInfo::InAlloca:
1391 // ignore and inalloca doesn't have matching LLVM parameters.
1392 IRArgs.NumberOfArgs = 0;
1393 break;
John McCallf26e73d2016-03-11 04:30:43 +00001394 case ABIArgInfo::CoerceAndExpand:
1395 IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
1396 break;
1397 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001398 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1399 break;
1400 }
Alexey Samsonov153004f2014-09-29 22:08:00 +00001401
1402 if (IRArgs.NumberOfArgs > 0) {
1403 IRArgs.FirstArgIndex = IRArgNo;
1404 IRArgNo += IRArgs.NumberOfArgs;
1405 }
1406
1407 // Skip over the sret parameter when it comes second. We already handled it
1408 // above.
1409 if (IRArgNo == 1 && SwapThisWithSRet)
1410 IRArgNo++;
1411 }
1412 assert(ArgNo == ArgInfo.size());
1413
1414 if (FI.usesInAlloca())
1415 InallocaArgNo = IRArgNo++;
1416
1417 TotalIRArgs = IRArgNo;
1418}
1419} // namespace
1420
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001421/***/
1422
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001423bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001424 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00001425}
1426
Tim Northovere77cc392014-03-29 13:28:05 +00001427bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1428 return ReturnTypeUsesSRet(FI) &&
1429 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1430}
1431
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001432bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1433 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1434 switch (BT->getKind()) {
1435 default:
1436 return false;
1437 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +00001438 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001439 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +00001440 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001441 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +00001442 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001443 }
1444 }
1445
1446 return false;
1447}
1448
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001449bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1450 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1451 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1452 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +00001453 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001454 }
1455 }
1456
1457 return false;
1458}
1459
Chris Lattnera5f58b02011-07-09 17:41:47 +00001460llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +00001461 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1462 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +00001463}
1464
Chris Lattnera5f58b02011-07-09 17:41:47 +00001465llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +00001466CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001467
David Blaikie82e95a32014-11-19 07:49:47 +00001468 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1469 (void)Inserted;
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001470 assert(Inserted && "Recursively being processed?");
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001471
Alexey Samsonov153004f2014-09-29 22:08:00 +00001472 llvm::Type *resultType = nullptr;
John McCall85dd2c52011-05-15 02:19:42 +00001473 const ABIArgInfo &retAI = FI.getReturnInfo();
1474 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +00001475 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +00001476 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +00001477
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001478 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001479 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +00001480 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +00001481 break;
1482
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001483 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001484 if (retAI.getInAllocaSRet()) {
1485 // sret things on win32 aren't void, they return the sret pointer.
1486 QualType ret = FI.getReturnType();
1487 llvm::Type *ty = ConvertType(ret);
1488 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1489 resultType = llvm::PointerType::get(ty, addressSpace);
1490 } else {
1491 resultType = llvm::Type::getVoidTy(getLLVMContext());
1492 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001493 break;
1494
John McCall7f416cc2015-09-08 08:05:57 +00001495 case ABIArgInfo::Indirect:
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001496 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +00001497 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001498 break;
John McCallf26e73d2016-03-11 04:30:43 +00001499
1500 case ABIArgInfo::CoerceAndExpand:
1501 resultType = retAI.getUnpaddedCoerceAndExpandType();
1502 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001503 }
Mike Stump11289f42009-09-09 15:08:12 +00001504
Alexey Samsonov153004f2014-09-29 22:08:00 +00001505 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1506 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1507
1508 // Add type for sret argument.
1509 if (IRFunctionArgs.hasSRetArg()) {
1510 QualType Ret = FI.getReturnType();
1511 llvm::Type *Ty = ConvertType(Ret);
1512 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1513 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1514 llvm::PointerType::get(Ty, AddressSpace);
1515 }
1516
1517 // Add type for inalloca argument.
1518 if (IRFunctionArgs.hasInallocaArg()) {
1519 auto ArgStruct = FI.getArgStruct();
1520 assert(ArgStruct);
1521 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1522 }
1523
John McCallc818bbb2012-12-07 07:03:17 +00001524 // Add in all of the required arguments.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001525 unsigned ArgNo = 0;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00001526 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1527 ie = it + FI.getNumRequiredArgs();
Alexey Samsonov153004f2014-09-29 22:08:00 +00001528 for (; it != ie; ++it, ++ArgNo) {
1529 const ABIArgInfo &ArgInfo = it->info;
Mike Stump11289f42009-09-09 15:08:12 +00001530
Rafael Espindolafad28de2012-10-24 01:59:00 +00001531 // Insert a padding type to ensure proper alignment.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001532 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1533 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1534 ArgInfo.getPaddingType();
Rafael Espindolafad28de2012-10-24 01:59:00 +00001535
Alexey Samsonov153004f2014-09-29 22:08:00 +00001536 unsigned FirstIRArg, NumIRArgs;
1537 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1538
1539 switch (ArgInfo.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001540 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001541 case ABIArgInfo::InAlloca:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001542 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001543 break;
1544
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001545 case ABIArgInfo::Indirect: {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001546 assert(NumIRArgs == 1);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001547 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +00001548 llvm::Type *LTy = ConvertTypeForMem(it->type);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001549 ArgTypes[FirstIRArg] = LTy->getPointerTo();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001550 break;
1551 }
1552
1553 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +00001554 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001555 // Fast-isel and the optimizer generally like scalar values better than
1556 // FCAs, so we flatten them if this is safe to do for this argument.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001557 llvm::Type *argType = ArgInfo.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +00001558 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001559 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1560 assert(NumIRArgs == st->getNumElements());
John McCall85dd2c52011-05-15 02:19:42 +00001561 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
Alexey Samsonov153004f2014-09-29 22:08:00 +00001562 ArgTypes[FirstIRArg + i] = st->getElementType(i);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001563 } else {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001564 assert(NumIRArgs == 1);
1565 ArgTypes[FirstIRArg] = argType;
Chris Lattner3dd716c2010-06-28 23:44:11 +00001566 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001567 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001568 }
Mike Stump11289f42009-09-09 15:08:12 +00001569
John McCallf26e73d2016-03-11 04:30:43 +00001570 case ABIArgInfo::CoerceAndExpand: {
1571 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1572 for (auto EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
1573 *ArgTypesIter++ = EltTy;
1574 }
1575 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1576 break;
1577 }
1578
Daniel Dunbard3674e62008-09-11 01:48:57 +00001579 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001580 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1581 getExpandedTypes(it->type, ArgTypesIter);
1582 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001583 break;
1584 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001585 }
1586
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001587 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1588 assert(Erased && "Not in set?");
Alexey Samsonov153004f2014-09-29 22:08:00 +00001589
1590 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001591}
1592
Chris Lattner2192fe52011-07-18 04:24:23 +00001593llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001594 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001595 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001596
Chris Lattner8806e322011-07-10 00:18:59 +00001597 if (!isFuncTypeConvertible(FPT))
1598 return llvm::StructType::get(getLLVMContext());
1599
1600 const CGFunctionInfo *Info;
1601 if (isa<CXXDestructorDecl>(MD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001602 Info =
1603 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
Chris Lattner8806e322011-07-10 00:18:59 +00001604 else
John McCalla729c622012-02-17 03:33:10 +00001605 Info = &arrangeCXXMethodDeclaration(MD);
1606 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001607}
1608
Samuel Antao798f11c2015-11-23 22:04:44 +00001609static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
1610 llvm::AttrBuilder &FuncAttrs,
1611 const FunctionProtoType *FPT) {
1612 if (!FPT)
1613 return;
1614
1615 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
1616 FPT->isNothrow(Ctx))
1617 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1618}
1619
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00001620void CodeGenModule::ConstructAttributeList(
1621 StringRef Name, const CGFunctionInfo &FI, CGCalleeInfo CalleeInfo,
1622 AttributeListType &PAL, unsigned &CallingConv, bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001623 llvm::AttrBuilder FuncAttrs;
1624 llvm::AttrBuilder RetAttrs;
Paul Robinson08556952014-12-11 20:14:04 +00001625 bool HasOptnone = false;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001626
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001627 CallingConv = FI.getEffectiveCallingConvention();
1628
John McCallab26cfa2010-02-05 21:31:56 +00001629 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001630 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001631
Samuel Antao798f11c2015-11-23 22:04:44 +00001632 // If we have information about the function prototype, we can learn
1633 // attributes form there.
1634 AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
1635 CalleeInfo.getCalleeFunctionProtoType());
1636
1637 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
1638
Amjad Aboudfaea5602016-03-07 14:22:46 +00001639 bool HasAnyX86InterruptAttr = false;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001640 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001641 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001642 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001643 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001644 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001645 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001646 if (TargetDecl->hasAttr<NoReturnAttr>())
1647 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001648 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1649 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smithdebc59d2013-01-30 05:45:05 +00001650
1651 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
Samuel Antao798f11c2015-11-23 22:04:44 +00001652 AddAttributesFromFunctionProtoType(
1653 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
Richard Smith49af6292013-03-05 08:30:04 +00001654 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1655 // These attributes are not inherited by overloads.
1656 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1657 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001658 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001659 }
1660
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001661 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
Eric Christopherbf005ec2011-08-15 22:38:22 +00001662 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001663 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1664 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001665 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001666 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1667 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001668 } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
1669 FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
1670 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001671 }
David Majnemer631a90b2015-02-04 07:23:21 +00001672 if (TargetDecl->hasAttr<RestrictAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001673 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001674 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1675 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Paul Robinson08556952014-12-11 20:14:04 +00001676
Amjad Aboudfaea5602016-03-07 14:22:46 +00001677 HasAnyX86InterruptAttr = TargetDecl->hasAttr<AnyX86InterruptAttr>();
Paul Robinson08556952014-12-11 20:14:04 +00001678 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001679 }
1680
Paul Robinson08556952014-12-11 20:14:04 +00001681 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1682 if (!HasOptnone) {
1683 if (CodeGenOpts.OptimizeSize)
1684 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1685 if (CodeGenOpts.OptimizeSize == 2)
1686 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1687 }
1688
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001689 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001690 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001691 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001692 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001693 if (CodeGenOpts.EnableSegmentedStacks &&
1694 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001695 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001696
Bill Wendling2f81db62013-02-22 20:53:29 +00001697 if (AttrOnCallSite) {
1698 // Attributes that should go on the call site only.
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00001699 if (!CodeGenOpts.SimplifyLibCalls ||
1700 CodeGenOpts.isNoBuiltinFunc(Name.data()))
Bill Wendling2f81db62013-02-22 20:53:29 +00001701 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00001702 if (!CodeGenOpts.TrapFuncName.empty())
1703 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
Bill Wendling706469b2013-02-28 22:49:57 +00001704 } else {
1705 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001706 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001707 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001708 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001709 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001710 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001711 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001712 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001713 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001714 }
1715
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001716 bool DisableTailCalls =
Amjad Aboudfaea5602016-03-07 14:22:46 +00001717 CodeGenOpts.DisableTailCalls || HasAnyX86InterruptAttr ||
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001718 (TargetDecl && TargetDecl->hasAttr<DisableTailCallsAttr>());
Amjad Aboudfaea5602016-03-07 14:22:46 +00001719 FuncAttrs.addAttribute(
1720 "disable-tail-calls",
1721 llvm::toStringRef(DisableTailCalls));
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001722
Bill Wendlingdabafea2013-03-13 22:24:33 +00001723 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001724 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Sjoerd Meijer0a8d4212016-08-30 08:09:45 +00001725
1726 if (!CodeGenOpts.FPDenormalMode.empty())
1727 FuncAttrs.addAttribute("denormal-fp-math",
1728 CodeGenOpts.FPDenormalMode);
1729
1730 FuncAttrs.addAttribute("no-trapping-math",
1731 llvm::toStringRef(CodeGenOpts.NoTrappingMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001732 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001733 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001734 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001735 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001736 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001737 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001738 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001739 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001740 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001741 llvm::utostr(CodeGenOpts.SSPBufferSize));
Yaxun Liu79c99fb2016-07-08 20:28:29 +00001742 FuncAttrs.addAttribute("no-signed-zeros-fp-math",
1743 llvm::toStringRef(CodeGenOpts.NoSignedZeros));
Yaxun Liuffb60902016-08-09 20:10:18 +00001744 FuncAttrs.addAttribute(
1745 "correctly-rounded-divide-sqrt-fp-math",
1746 llvm::toStringRef(CodeGenOpts.CorrectlyRoundedDivSqrt));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001747
Akira Hatanakaaecca042015-09-11 18:55:09 +00001748 if (CodeGenOpts.StackRealignment)
1749 FuncAttrs.addAttribute("stackrealign");
Marcin Koscielnickib31ee6d2016-05-04 23:37:40 +00001750 if (CodeGenOpts.Backchain)
1751 FuncAttrs.addAttribute("backchain");
Eric Christopher70c16652015-03-25 23:14:47 +00001752
Eric Christopher11acf732015-06-12 01:35:52 +00001753 // Add target-cpu and target-features attributes to functions. If
1754 // we have a decl for the function and it has a target attribute then
1755 // parse that and add it to the feature set.
1756 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
Eric Christopher11acf732015-06-12 01:35:52 +00001757 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
Eric Christopherb57804a2015-09-01 22:03:56 +00001758 if (FD && FD->hasAttr<TargetAttr>()) {
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001759 llvm::StringMap<bool> FeatureMap;
Eric Christopher2b90a642015-11-11 23:05:08 +00001760 getFunctionFeatureMap(FeatureMap, FD);
Eric Christopher11acf732015-06-12 01:35:52 +00001761
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001762 // Produce the canonical string for this set of features.
1763 std::vector<std::string> Features;
1764 for (llvm::StringMap<bool>::const_iterator it = FeatureMap.begin(),
1765 ie = FeatureMap.end();
1766 it != ie; ++it)
1767 Features.push_back((it->second ? "+" : "-") + it->first().str());
Eric Christopher2249b812015-07-01 00:08:29 +00001768
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001769 // Now add the target-cpu and target-features to the function.
Eric Christopher2b90a642015-11-11 23:05:08 +00001770 // While we populated the feature map above, we still need to
1771 // get and parse the target attribute so we can get the cpu for
1772 // the function.
1773 const auto *TD = FD->getAttr<TargetAttr>();
1774 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
1775 if (ParsedAttr.second != "")
1776 TargetCPU = ParsedAttr.second;
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001777 if (TargetCPU != "")
1778 FuncAttrs.addAttribute("target-cpu", TargetCPU);
1779 if (!Features.empty()) {
1780 std::sort(Features.begin(), Features.end());
1781 FuncAttrs.addAttribute(
1782 "target-features",
1783 llvm::join(Features.begin(), Features.end(), ","));
1784 }
1785 } else {
1786 // Otherwise just add the existing target cpu and target features to the
1787 // function.
1788 std::vector<std::string> &Features = getTarget().getTargetOpts().Features;
1789 if (TargetCPU != "")
1790 FuncAttrs.addAttribute("target-cpu", TargetCPU);
1791 if (!Features.empty()) {
1792 std::sort(Features.begin(), Features.end());
1793 FuncAttrs.addAttribute(
1794 "target-features",
1795 llvm::join(Features.begin(), Features.end(), ","));
1796 }
Eric Christopher70c16652015-03-25 23:14:47 +00001797 }
Bill Wendling985d1c52013-02-15 21:30:01 +00001798 }
1799
Justin Lebarddd97fa2016-02-24 21:55:11 +00001800 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
1801 // Conservatively, mark all functions and calls in CUDA as convergent
1802 // (meaning, they may call an intrinsically convergent op, such as
1803 // __syncthreads(), and so can't have certain optimizations applied around
1804 // them). LLVM will remove this attribute where it safely can.
1805 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
Justin Lebard3a44f62016-04-05 18:26:20 +00001806
1807 // Respect -fcuda-flush-denormals-to-zero.
1808 if (getLangOpts().CUDADeviceFlushDenormalsToZero)
1809 FuncAttrs.addAttribute("nvptx-f32ftz", "true");
Justin Lebarddd97fa2016-02-24 21:55:11 +00001810 }
1811
Alexey Samsonov153004f2014-09-29 22:08:00 +00001812 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001813
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001814 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001815 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001816 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001817 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001818 if (RetTy->hasSignedIntegerRepresentation())
1819 RetAttrs.addAttribute(llvm::Attribute::SExt);
1820 else if (RetTy->hasUnsignedIntegerRepresentation())
1821 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001822 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001823 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001824 if (RetAI.getInReg())
1825 RetAttrs.addAttribute(llvm::Attribute::InReg);
1826 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001827 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001828 break;
1829
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001830 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001831 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001832 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001833 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1834 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001835 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001836 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001837
John McCallf26e73d2016-03-11 04:30:43 +00001838 case ABIArgInfo::CoerceAndExpand:
1839 break;
1840
Daniel Dunbard3674e62008-09-11 01:48:57 +00001841 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001842 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001843 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001844
Hal Finkela2347ba2014-07-18 15:52:10 +00001845 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1846 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00001847 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00001848 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1849 .getQuantity());
1850 else if (getContext().getTargetAddressSpace(PTy) == 0)
1851 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1852 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001853
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001854 // Attach return attributes.
1855 if (RetAttrs.hasAttributes()) {
1856 PAL.push_back(llvm::AttributeSet::get(
1857 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1858 }
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001859
John McCall12f23522016-04-04 18:33:08 +00001860 bool hasUsedSRet = false;
1861
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001862 // Attach attributes to sret.
1863 if (IRFunctionArgs.hasSRetArg()) {
1864 llvm::AttrBuilder SRETAttrs;
1865 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
John McCall12f23522016-04-04 18:33:08 +00001866 hasUsedSRet = true;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001867 if (RetAI.getInReg())
1868 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1869 PAL.push_back(llvm::AttributeSet::get(
1870 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1871 }
1872
1873 // Attach attributes to inalloca argument.
1874 if (IRFunctionArgs.hasInallocaArg()) {
1875 llvm::AttrBuilder Attrs;
1876 Attrs.addAttribute(llvm::Attribute::InAlloca);
1877 PAL.push_back(llvm::AttributeSet::get(
1878 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1879 }
1880
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001881 unsigned ArgNo = 0;
1882 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1883 E = FI.arg_end();
1884 I != E; ++I, ++ArgNo) {
1885 QualType ParamType = I->type;
1886 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001887 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001888
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001889 // Add attribute for padding argument, if necessary.
1890 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendling290d9522013-01-27 02:46:53 +00001891 if (AI.getPaddingInReg())
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001892 PAL.push_back(llvm::AttributeSet::get(
1893 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1894 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001895 }
1896
John McCall39ec71f2010-03-27 00:47:27 +00001897 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1898 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001899 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001900 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001901 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001902 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001903 Attrs.addAttribute(llvm::Attribute::SExt);
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00001904 else if (ParamType->isUnsignedIntegerOrEnumerationType()) {
1905 if (getTypes().getABIInfo().shouldSignExtUnsignedType(ParamType))
1906 Attrs.addAttribute(llvm::Attribute::SExt);
1907 else
1908 Attrs.addAttribute(llvm::Attribute::ZExt);
1909 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001910 // FALL THROUGH
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001911 case ABIArgInfo::Direct:
Peter Collingbournef7706832014-12-12 23:41:25 +00001912 if (ArgNo == 0 && FI.isChainCall())
1913 Attrs.addAttribute(llvm::Attribute::Nest);
1914 else if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001915 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001916 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001917
James Y Knight71608572015-08-21 18:19:06 +00001918 case ABIArgInfo::Indirect: {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001919 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001920 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001921
Anders Carlsson20759ad2009-09-16 15:53:40 +00001922 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001923 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001924
John McCall7f416cc2015-09-08 08:05:57 +00001925 CharUnits Align = AI.getIndirectAlign();
James Y Knight71608572015-08-21 18:19:06 +00001926
1927 // In a byval argument, it is important that the required
1928 // alignment of the type is honored, as LLVM might be creating a
1929 // *new* stack object, and needs to know what alignment to give
1930 // it. (Sometimes it can deduce a sensible alignment on its own,
1931 // but not if clang decides it must emit a packed struct, or the
1932 // user specifies increased alignment requirements.)
1933 //
1934 // This is different from indirect *not* byval, where the object
1935 // exists already, and the align attribute is purely
1936 // informative.
John McCall7f416cc2015-09-08 08:05:57 +00001937 assert(!Align.isZero());
James Y Knight71608572015-08-21 18:19:06 +00001938
John McCall7f416cc2015-09-08 08:05:57 +00001939 // For now, only add this when we have a byval argument.
1940 // TODO: be less lazy about updating test cases.
1941 if (AI.getIndirectByVal())
1942 Attrs.addAlignmentAttr(Align.getQuantity());
Bill Wendlinga7912f82012-10-10 07:36:56 +00001943
Daniel Dunbarc2304432009-03-18 19:51:01 +00001944 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001945 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1946 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001947 break;
James Y Knight71608572015-08-21 18:19:06 +00001948 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001949 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001950 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00001951 case ABIArgInfo::CoerceAndExpand:
1952 break;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001953
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001954 case ABIArgInfo::InAlloca:
1955 // inalloca disables readnone and readonly.
1956 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1957 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001958 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001959 }
Mike Stump11289f42009-09-09 15:08:12 +00001960
Hal Finkela2347ba2014-07-18 15:52:10 +00001961 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1962 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00001963 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00001964 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1965 .getQuantity());
1966 else if (getContext().getTargetAddressSpace(PTy) == 0)
1967 Attrs.addAttribute(llvm::Attribute::NonNull);
1968 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001969
John McCall12f23522016-04-04 18:33:08 +00001970 switch (FI.getExtParameterInfo(ArgNo).getABI()) {
1971 case ParameterABI::Ordinary:
1972 break;
1973
1974 case ParameterABI::SwiftIndirectResult: {
1975 // Add 'sret' if we haven't already used it for something, but
1976 // only if the result is void.
1977 if (!hasUsedSRet && RetTy->isVoidType()) {
1978 Attrs.addAttribute(llvm::Attribute::StructRet);
1979 hasUsedSRet = true;
1980 }
1981
1982 // Add 'noalias' in either case.
1983 Attrs.addAttribute(llvm::Attribute::NoAlias);
1984
1985 // Add 'dereferenceable' and 'alignment'.
1986 auto PTy = ParamType->getPointeeType();
1987 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
1988 auto info = getContext().getTypeInfoInChars(PTy);
1989 Attrs.addDereferenceableAttr(info.first.getQuantity());
1990 Attrs.addAttribute(llvm::Attribute::getWithAlignment(getLLVMContext(),
1991 info.second.getQuantity()));
1992 }
1993 break;
1994 }
1995
1996 case ParameterABI::SwiftErrorResult:
1997 Attrs.addAttribute(llvm::Attribute::SwiftError);
1998 break;
1999
2000 case ParameterABI::SwiftContext:
2001 Attrs.addAttribute(llvm::Attribute::SwiftSelf);
2002 break;
2003 }
2004
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002005 if (Attrs.hasAttributes()) {
2006 unsigned FirstIRArg, NumIRArgs;
2007 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2008 for (unsigned i = 0; i < NumIRArgs; i++)
2009 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
2010 FirstIRArg + i + 1, Attrs));
2011 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00002012 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002013 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002014
Bill Wendlinga7912f82012-10-10 07:36:56 +00002015 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00002016 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00002017 AttributeSet::get(getLLVMContext(),
2018 llvm::AttributeSet::FunctionIndex,
2019 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00002020}
2021
John McCalla738c252011-03-09 04:27:21 +00002022/// An argument came in as a promoted argument; demote it back to its
2023/// declared type.
2024static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
2025 const VarDecl *var,
2026 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002027 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00002028
2029 // This can happen with promotions that actually don't change the
2030 // underlying type, like the enum promotions.
2031 if (value->getType() == varType) return value;
2032
2033 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
2034 && "unexpected promotion type");
2035
2036 if (isa<llvm::IntegerType>(varType))
2037 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
2038
2039 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
2040}
2041
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002042/// Returns the attribute (either parameter attribute, or function
2043/// attribute), which declares argument ArgNo to be non-null.
2044static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
2045 QualType ArgType, unsigned ArgNo) {
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002046 // FIXME: __attribute__((nonnull)) can also be applied to:
2047 // - references to pointers, where the pointee is known to be
2048 // nonnull (apparently a Clang extension)
2049 // - transparent unions containing pointers
2050 // In the former case, LLVM IR cannot represent the constraint. In
2051 // the latter case, we have no guarantee that the transparent union
2052 // is in fact passed as a pointer.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002053 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
2054 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002055 // First, check attribute on parameter itself.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002056 if (PVD) {
2057 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
2058 return ParmNNAttr;
2059 }
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002060 // Check function attributes.
2061 if (!FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002062 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002063 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002064 if (NNAttr->isNonNull(ArgNo))
2065 return NNAttr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002066 }
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002067 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002068}
2069
John McCall12f23522016-04-04 18:33:08 +00002070namespace {
2071 struct CopyBackSwiftError final : EHScopeStack::Cleanup {
2072 Address Temp;
2073 Address Arg;
2074 CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
2075 void Emit(CodeGenFunction &CGF, Flags flags) override {
2076 llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
2077 CGF.Builder.CreateStore(errorValue, Arg);
2078 }
2079 };
2080}
2081
Daniel Dunbard931a872009-02-02 22:03:45 +00002082void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
2083 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00002084 const FunctionArgList &Args) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002085 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
2086 // Naked functions don't have prologues.
2087 return;
2088
John McCallcaa19452009-07-28 01:00:58 +00002089 // If this is an implicit-return-zero function, go ahead and
2090 // initialize the return value. TODO: it might be nice to have
2091 // a more general mechanism for this that didn't require synthesized
2092 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00002093 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00002094 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00002095 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00002096 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00002097 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00002098 Builder.CreateStore(Zero, ReturnValue);
2099 }
2100 }
2101
Mike Stump18bb9282009-05-16 07:57:57 +00002102 // FIXME: We no longer need the types from FunctionArgList; lift up and
2103 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00002104
Alexey Samsonov153004f2014-09-29 22:08:00 +00002105 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002106 // Flattened function arguments.
John McCall12f23522016-04-04 18:33:08 +00002107 SmallVector<llvm::Value *, 16> FnArgs;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002108 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
2109 for (auto &Arg : Fn->args()) {
2110 FnArgs.push_back(&Arg);
2111 }
2112 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00002113
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002114 // If we're using inalloca, all the memory arguments are GEPs off of the last
2115 // parameter, which is a pointer to the complete memory area.
John McCall7f416cc2015-09-08 08:05:57 +00002116 Address ArgStruct = Address::invalid();
2117 const llvm::StructLayout *ArgStructLayout = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002118 if (IRFunctionArgs.hasInallocaArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00002119 ArgStructLayout = CGM.getDataLayout().getStructLayout(FI.getArgStruct());
2120 ArgStruct = Address(FnArgs[IRFunctionArgs.getInallocaArgNo()],
2121 FI.getArgStructAlignment());
2122
2123 assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002124 }
2125
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002126 // Name the struct return parameter.
2127 if (IRFunctionArgs.hasSRetArg()) {
John McCall12f23522016-04-04 18:33:08 +00002128 auto AI = cast<llvm::Argument>(FnArgs[IRFunctionArgs.getSRetArgNo()]);
Daniel Dunbar613855c2008-09-09 23:27:19 +00002129 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00002130 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00002131 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002132 }
Mike Stump11289f42009-09-09 15:08:12 +00002133
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002134 // Track if we received the parameter as a pointer (indirect, byval, or
2135 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
2136 // into a local alloca for us.
John McCall7f416cc2015-09-08 08:05:57 +00002137 SmallVector<ParamValue, 16> ArgVals;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002138 ArgVals.reserve(Args.size());
2139
Reid Kleckner739756c2013-12-04 19:23:12 +00002140 // Create a pointer value for every parameter declaration. This usually
2141 // entails copying one or more LLVM IR arguments into an alloca. Don't push
2142 // any cleanups or do anything that might unwind. We do that separately, so
2143 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002144 assert(FI.arg_size() == Args.size() &&
2145 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002146 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002147 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002148 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00002149 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00002150 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002151 QualType Ty = info_it->type;
2152 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002153
John McCalla738c252011-03-09 04:27:21 +00002154 bool isPromoted =
2155 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
2156
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002157 unsigned FirstIRArg, NumIRArgs;
2158 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002159
Daniel Dunbard3674e62008-09-11 01:48:57 +00002160 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002161 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002162 assert(NumIRArgs == 0);
John McCall7f416cc2015-09-08 08:05:57 +00002163 auto FieldIndex = ArgI.getInAllocaFieldIndex();
2164 CharUnits FieldOffset =
2165 CharUnits::fromQuantity(ArgStructLayout->getElementOffset(FieldIndex));
2166 Address V = Builder.CreateStructGEP(ArgStruct, FieldIndex, FieldOffset,
2167 Arg->getName());
2168 ArgVals.push_back(ParamValue::forIndirect(V));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002169 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002170 }
2171
Daniel Dunbar747865a2009-02-05 09:16:39 +00002172 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002173 assert(NumIRArgs == 1);
John McCall7f416cc2015-09-08 08:05:57 +00002174 Address ParamAddr = Address(FnArgs[FirstIRArg], ArgI.getIndirectAlign());
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002175
John McCall47fb9502013-03-07 21:37:08 +00002176 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002177 // Aggregates and complex variables are accessed by reference. All we
John McCall7f416cc2015-09-08 08:05:57 +00002178 // need to do is realign the value, if requested.
2179 Address V = ParamAddr;
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002180 if (ArgI.getIndirectRealign()) {
John McCall7f416cc2015-09-08 08:05:57 +00002181 Address AlignedTemp = CreateMemTemp(Ty, "coerce");
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002182
2183 // Copy from the incoming argument pointer to the temporary with the
2184 // appropriate alignment.
2185 //
2186 // FIXME: We should have a common utility for generating an aggregate
2187 // copy.
Ken Dyck705ba072011-01-19 01:58:38 +00002188 CharUnits Size = getContext().getTypeSizeInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002189 auto SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity());
2190 Address Dst = Builder.CreateBitCast(AlignedTemp, Int8PtrTy);
2191 Address Src = Builder.CreateBitCast(ParamAddr, Int8PtrTy);
2192 Builder.CreateMemCpy(Dst, Src, SizeVal, false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002193 V = AlignedTemp;
2194 }
John McCall7f416cc2015-09-08 08:05:57 +00002195 ArgVals.push_back(ParamValue::forIndirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00002196 } else {
2197 // Load scalar value from indirect argument.
John McCall7f416cc2015-09-08 08:05:57 +00002198 llvm::Value *V =
2199 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00002200
2201 if (isPromoted)
2202 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002203 ArgVals.push_back(ParamValue::forDirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00002204 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002205 break;
2206 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002207
2208 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00002209 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00002210
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002211 // If we have the trivial case, handle it with no muss and fuss.
2212 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002213 ArgI.getCoerceToType() == ConvertType(Ty) &&
2214 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002215 assert(NumIRArgs == 1);
John McCall12f23522016-04-04 18:33:08 +00002216 llvm::Value *V = FnArgs[FirstIRArg];
2217 auto AI = cast<llvm::Argument>(V);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002218
Hal Finkel48d53e22014-07-19 01:41:07 +00002219 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002220 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
2221 PVD->getFunctionScopeIndex()))
Hal Finkel82504f02014-07-11 17:35:21 +00002222 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2223 AI->getArgNo() + 1,
2224 llvm::Attribute::NonNull));
2225
Hal Finkel48d53e22014-07-19 01:41:07 +00002226 QualType OTy = PVD->getOriginalType();
2227 if (const auto *ArrTy =
2228 getContext().getAsConstantArrayType(OTy)) {
2229 // A C99 array parameter declaration with the static keyword also
2230 // indicates dereferenceability, and if the size is constant we can
2231 // use the dereferenceable attribute (which requires the size in
2232 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00002233 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00002234 QualType ETy = ArrTy->getElementType();
2235 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
2236 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
2237 ArrSize) {
2238 llvm::AttrBuilder Attrs;
2239 Attrs.addDereferenceableAttr(
2240 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
2241 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2242 AI->getArgNo() + 1, Attrs));
2243 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
2244 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2245 AI->getArgNo() + 1,
2246 llvm::Attribute::NonNull));
2247 }
2248 }
2249 } else if (const auto *ArrTy =
2250 getContext().getAsVariableArrayType(OTy)) {
2251 // For C99 VLAs with the static keyword, we don't know the size so
2252 // we can't use the dereferenceable attribute, but in addrspace(0)
2253 // we know that it must be nonnull.
2254 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
2255 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
2256 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2257 AI->getArgNo() + 1,
2258 llvm::Attribute::NonNull));
2259 }
Hal Finkel1b0d24e2014-10-02 21:21:25 +00002260
2261 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
2262 if (!AVAttr)
2263 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
2264 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
2265 if (AVAttr) {
2266 llvm::Value *AlignmentValue =
2267 EmitScalarExpr(AVAttr->getAlignment());
2268 llvm::ConstantInt *AlignmentCI =
2269 cast<llvm::ConstantInt>(AlignmentValue);
2270 unsigned Alignment =
2271 std::min((unsigned) AlignmentCI->getZExtValue(),
2272 +llvm::Value::MaximumAlignment);
2273
2274 llvm::AttrBuilder Attrs;
2275 Attrs.addAlignmentAttr(Alignment);
2276 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2277 AI->getArgNo() + 1, Attrs));
2278 }
Hal Finkel48d53e22014-07-19 01:41:07 +00002279 }
2280
Bill Wendling507c3512012-10-16 05:23:44 +00002281 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00002282 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2283 AI->getArgNo() + 1,
2284 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00002285
John McCall12f23522016-04-04 18:33:08 +00002286 // LLVM expects swifterror parameters to be used in very restricted
2287 // ways. Copy the value into a less-restricted temporary.
2288 if (FI.getExtParameterInfo(ArgNo).getABI()
2289 == ParameterABI::SwiftErrorResult) {
2290 QualType pointeeTy = Ty->getPointeeType();
2291 assert(pointeeTy->isPointerType());
2292 Address temp =
2293 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
2294 Address arg = Address(V, getContext().getTypeAlignInChars(pointeeTy));
2295 llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
2296 Builder.CreateStore(incomingErrorValue, temp);
2297 V = temp.getPointer();
2298
2299 // Push a cleanup to copy the value back at the end of the function.
2300 // The convention does not guarantee that the value will be written
2301 // back if the function exits with an unwind exception.
2302 EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
2303 }
2304
Chris Lattner7369c142011-07-20 06:29:00 +00002305 // Ensure the argument is the correct type.
2306 if (V->getType() != ArgI.getCoerceToType())
2307 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
2308
John McCalla738c252011-03-09 04:27:21 +00002309 if (isPromoted)
2310 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00002311
Nick Lewycky5fa40c32013-10-01 21:51:38 +00002312 if (const CXXMethodDecl *MD =
2313 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00002314 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00002315 V = CGM.getCXXABI().
2316 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00002317 }
2318
Rafael Espindola8778c282012-11-29 16:09:03 +00002319 // Because of merging of function types from multiple decls it is
2320 // possible for the type of an argument to not match the corresponding
2321 // type in the function type. Since we are codegening the callee
2322 // in here, add a cast to the argument type.
2323 llvm::Type *LTy = ConvertType(Arg->getType());
2324 if (V->getType() != LTy)
2325 V = Builder.CreateBitCast(V, LTy);
2326
John McCall7f416cc2015-09-08 08:05:57 +00002327 ArgVals.push_back(ParamValue::forDirect(V));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002328 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00002329 }
Mike Stump11289f42009-09-09 15:08:12 +00002330
John McCall7f416cc2015-09-08 08:05:57 +00002331 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
2332 Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002333
John McCall7f416cc2015-09-08 08:05:57 +00002334 // Pointer to store into.
2335 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002336
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002337 // Fast-isel and the optimizer generally like scalar values better than
2338 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002339 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002340 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
2341 STy->getNumElements() > 1) {
John McCall7f416cc2015-09-08 08:05:57 +00002342 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Micah Villmowdd31ca12012-10-08 16:25:52 +00002343 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
John McCall7f416cc2015-09-08 08:05:57 +00002344 llvm::Type *DstTy = Ptr.getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002345 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002346
John McCall7f416cc2015-09-08 08:05:57 +00002347 Address AddrToStoreInto = Address::invalid();
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002348 if (SrcSize <= DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00002349 AddrToStoreInto =
2350 Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002351 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002352 AddrToStoreInto =
2353 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
Chris Lattner15ec3612010-06-29 00:06:42 +00002354 }
John McCall7f416cc2015-09-08 08:05:57 +00002355
2356 assert(STy->getNumElements() == NumIRArgs);
2357 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2358 auto AI = FnArgs[FirstIRArg + i];
2359 AI->setName(Arg->getName() + ".coerce" + Twine(i));
2360 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
2361 Address EltPtr =
2362 Builder.CreateStructGEP(AddrToStoreInto, i, Offset);
2363 Builder.CreateStore(AI, EltPtr);
2364 }
2365
2366 if (SrcSize > DstSize) {
2367 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
2368 }
2369
Chris Lattner15ec3612010-06-29 00:06:42 +00002370 } else {
2371 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002372 assert(NumIRArgs == 1);
2373 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00002374 AI->setName(Arg->getName() + ".coerce");
John McCall7f416cc2015-09-08 08:05:57 +00002375 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00002376 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002377
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002378 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00002379 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002380 llvm::Value *V =
2381 EmitLoadOfScalar(Alloca, false, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00002382 if (isPromoted)
2383 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002384 ArgVals.push_back(ParamValue::forDirect(V));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002385 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002386 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00002387 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002388 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002389 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002390
John McCallf26e73d2016-03-11 04:30:43 +00002391 case ABIArgInfo::CoerceAndExpand: {
2392 // Reconstruct into a temporary.
2393 Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2394 ArgVals.push_back(ParamValue::forIndirect(alloca));
2395
2396 auto coercionType = ArgI.getCoerceAndExpandType();
2397 alloca = Builder.CreateElementBitCast(alloca, coercionType);
2398 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
2399
2400 unsigned argIndex = FirstIRArg;
2401 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2402 llvm::Type *eltType = coercionType->getElementType(i);
2403 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
2404 continue;
2405
2406 auto eltAddr = Builder.CreateStructGEP(alloca, i, layout);
2407 auto elt = FnArgs[argIndex++];
2408 Builder.CreateStore(elt, eltAddr);
2409 }
2410 assert(argIndex == FirstIRArg + NumIRArgs);
2411 break;
2412 }
2413
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002414 case ABIArgInfo::Expand: {
2415 // If this structure was expanded into multiple arguments then
2416 // we need to create a temporary and reconstruct it from the
2417 // arguments.
John McCall7f416cc2015-09-08 08:05:57 +00002418 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2419 LValue LV = MakeAddrLValue(Alloca, Ty);
2420 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002421
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002422 auto FnArgIter = FnArgs.begin() + FirstIRArg;
2423 ExpandTypeFromArgs(Ty, LV, FnArgIter);
2424 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
2425 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
2426 auto AI = FnArgs[FirstIRArg + i];
2427 AI->setName(Arg->getName() + "." + Twine(i));
2428 }
2429 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002430 }
2431
2432 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002433 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002434 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002435 if (!hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002436 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002437 } else {
2438 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002439 ArgVals.push_back(ParamValue::forDirect(U));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002440 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002441 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002442 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002443 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002444
Reid Kleckner739756c2013-12-04 19:23:12 +00002445 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2446 for (int I = Args.size() - 1; I >= 0; --I)
John McCall7f416cc2015-09-08 08:05:57 +00002447 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002448 } else {
2449 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall7f416cc2015-09-08 08:05:57 +00002450 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002451 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002452}
2453
John McCallffa2c1a2012-01-29 07:46:59 +00002454static void eraseUnusedBitCasts(llvm::Instruction *insn) {
2455 while (insn->use_empty()) {
2456 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
2457 if (!bitcast) return;
2458
2459 // This is "safe" because we would have used a ConstantExpr otherwise.
2460 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
2461 bitcast->eraseFromParent();
2462 }
2463}
2464
John McCall31168b02011-06-15 23:02:42 +00002465/// Try to emit a fused autorelease of a return result.
2466static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
2467 llvm::Value *result) {
2468 // We must be immediately followed the cast.
2469 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002470 if (BB->empty()) return nullptr;
2471 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002472
Chris Lattner2192fe52011-07-18 04:24:23 +00002473 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00002474
2475 // result is in a BasicBlock and is therefore an Instruction.
2476 llvm::Instruction *generator = cast<llvm::Instruction>(result);
2477
Justin Bogner882f8612016-08-18 21:46:54 +00002478 SmallVector<llvm::Instruction *, 4> InstsToKill;
John McCall31168b02011-06-15 23:02:42 +00002479
2480 // Look for:
2481 // %generator = bitcast %type1* %generator2 to %type2*
2482 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2483 // We would have emitted this as a constant if the operand weren't
2484 // an Instruction.
2485 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2486
2487 // Require the generator to be immediately followed by the cast.
2488 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00002489 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002490
Justin Bogner882f8612016-08-18 21:46:54 +00002491 InstsToKill.push_back(bitcast);
John McCall31168b02011-06-15 23:02:42 +00002492 }
2493
2494 // Look for:
2495 // %generator = call i8* @objc_retain(i8* %originalResult)
2496 // or
2497 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2498 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00002499 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002500
2501 bool doRetainAutorelease;
2502
John McCallb04ecb72015-10-21 18:06:43 +00002503 if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints().objc_retain) {
John McCall31168b02011-06-15 23:02:42 +00002504 doRetainAutorelease = true;
John McCallb04ecb72015-10-21 18:06:43 +00002505 } else if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints()
John McCall31168b02011-06-15 23:02:42 +00002506 .objc_retainAutoreleasedReturnValue) {
2507 doRetainAutorelease = false;
2508
John McCallcfa4e9b2012-09-07 23:30:50 +00002509 // If we emitted an assembly marker for this call (and the
2510 // ARCEntrypoints field should have been set if so), go looking
2511 // for that call. If we can't find it, we can't do this
2512 // optimization. But it should always be the immediately previous
2513 // instruction, unless we needed bitcasts around the call.
John McCallb04ecb72015-10-21 18:06:43 +00002514 if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
John McCallcfa4e9b2012-09-07 23:30:50 +00002515 llvm::Instruction *prev = call->getPrevNode();
2516 assert(prev);
2517 if (isa<llvm::BitCastInst>(prev)) {
2518 prev = prev->getPrevNode();
2519 assert(prev);
2520 }
2521 assert(isa<llvm::CallInst>(prev));
2522 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
John McCallb04ecb72015-10-21 18:06:43 +00002523 CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
Justin Bogner882f8612016-08-18 21:46:54 +00002524 InstsToKill.push_back(prev);
John McCallcfa4e9b2012-09-07 23:30:50 +00002525 }
John McCall31168b02011-06-15 23:02:42 +00002526 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002527 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002528 }
2529
2530 result = call->getArgOperand(0);
Justin Bogner882f8612016-08-18 21:46:54 +00002531 InstsToKill.push_back(call);
John McCall31168b02011-06-15 23:02:42 +00002532
2533 // Keep killing bitcasts, for sanity. Note that we no longer care
2534 // about precise ordering as long as there's exactly one use.
2535 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2536 if (!bitcast->hasOneUse()) break;
Justin Bogner882f8612016-08-18 21:46:54 +00002537 InstsToKill.push_back(bitcast);
John McCall31168b02011-06-15 23:02:42 +00002538 result = bitcast->getOperand(0);
2539 }
2540
2541 // Delete all the unnecessary instructions, from latest to earliest.
Justin Bogner882f8612016-08-18 21:46:54 +00002542 for (auto *I : InstsToKill)
Saleem Abdulrasoolbe25c482016-08-18 21:40:06 +00002543 I->eraseFromParent();
John McCall31168b02011-06-15 23:02:42 +00002544
2545 // Do the fused retain/autorelease if we were asked to.
2546 if (doRetainAutorelease)
2547 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2548
2549 // Cast back to the result type.
2550 return CGF.Builder.CreateBitCast(result, resultType);
2551}
2552
John McCallffa2c1a2012-01-29 07:46:59 +00002553/// If this is a +1 of the value of an immutable 'self', remove it.
2554static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2555 llvm::Value *result) {
2556 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00002557 const ObjCMethodDecl *method =
2558 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002559 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002560 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00002561 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002562
2563 // Look for a retain call.
2564 llvm::CallInst *retainCall =
2565 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2566 if (!retainCall ||
John McCallb04ecb72015-10-21 18:06:43 +00002567 retainCall->getCalledValue() != CGF.CGM.getObjCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00002568 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002569
2570 // Look for an ordinary load of 'self'.
2571 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2572 llvm::LoadInst *load =
2573 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2574 if (!load || load->isAtomic() || load->isVolatile() ||
John McCall7f416cc2015-09-08 08:05:57 +00002575 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
Craig Topper8a13c412014-05-21 05:09:00 +00002576 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002577
2578 // Okay! Burn it all down. This relies for correctness on the
2579 // assumption that the retain is emitted as part of the return and
2580 // that thereafter everything is used "linearly".
2581 llvm::Type *resultType = result->getType();
2582 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2583 assert(retainCall->use_empty());
2584 retainCall->eraseFromParent();
2585 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2586
2587 return CGF.Builder.CreateBitCast(load, resultType);
2588}
2589
John McCall31168b02011-06-15 23:02:42 +00002590/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00002591///
2592/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00002593static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2594 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00002595 // If we're returning 'self', kill the initial retain. This is a
2596 // heuristic attempt to "encourage correctness" in the really unfortunate
2597 // case where we have a return of self during a dealloc and we desperately
2598 // need to avoid the possible autorelease.
2599 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2600 return self;
2601
John McCall31168b02011-06-15 23:02:42 +00002602 // At -O0, try to emit a fused retain/autorelease.
2603 if (CGF.shouldUseFusedARCCalls())
2604 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2605 return fused;
2606
2607 return CGF.EmitARCAutoreleaseReturnValue(result);
2608}
2609
John McCall6e1c0122012-01-29 02:35:02 +00002610/// Heuristically search for a dominating store to the return-value slot.
2611static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002612 // Check if a User is a store which pointerOperand is the ReturnValue.
2613 // We are looking for stores to the ReturnValue, not for stores of the
2614 // ReturnValue to some other location.
2615 auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
2616 auto *SI = dyn_cast<llvm::StoreInst>(U);
2617 if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer())
2618 return nullptr;
2619 // These aren't actually possible for non-coerced returns, and we
2620 // only care about non-coerced returns on this code path.
2621 assert(!SI->isAtomic() && !SI->isVolatile());
2622 return SI;
2623 };
John McCall6e1c0122012-01-29 02:35:02 +00002624 // If there are multiple uses of the return-value slot, just check
2625 // for something immediately preceding the IP. Sometimes this can
2626 // happen with how we generate implicit-returns; it can also happen
2627 // with noreturn cleanups.
John McCall7f416cc2015-09-08 08:05:57 +00002628 if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
John McCall6e1c0122012-01-29 02:35:02 +00002629 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002630 if (IP->empty()) return nullptr;
David Majnemerdc012fa2015-04-22 21:38:15 +00002631 llvm::Instruction *I = &IP->back();
2632
2633 // Skip lifetime markers
2634 for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
2635 IE = IP->rend();
2636 II != IE; ++II) {
2637 if (llvm::IntrinsicInst *Intrinsic =
2638 dyn_cast<llvm::IntrinsicInst>(&*II)) {
2639 if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
2640 const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
2641 ++II;
Alexey Samsonov10544202015-06-12 21:05:32 +00002642 if (II == IE)
2643 break;
2644 if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
2645 continue;
David Majnemerdc012fa2015-04-22 21:38:15 +00002646 }
2647 }
2648 I = &*II;
2649 break;
2650 }
2651
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002652 return GetStoreIfValid(I);
John McCall6e1c0122012-01-29 02:35:02 +00002653 }
2654
2655 llvm::StoreInst *store =
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002656 GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00002657 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002658
John McCall6e1c0122012-01-29 02:35:02 +00002659 // Now do a first-and-dirty dominance check: just walk up the
2660 // single-predecessors chain from the current insertion point.
2661 llvm::BasicBlock *StoreBB = store->getParent();
2662 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2663 while (IP != StoreBB) {
2664 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00002665 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002666 }
2667
2668 // Okay, the store's basic block dominates the insertion point; we
2669 // can do our thing.
2670 return store;
2671}
2672
Adrian Prantl3be10542013-05-02 17:30:20 +00002673void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002674 bool EmitRetDbgLoc,
2675 SourceLocation EndLoc) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002676 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2677 // Naked functions don't have epilogues.
2678 Builder.CreateUnreachable();
2679 return;
2680 }
2681
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002682 // Functions with no result always return void.
John McCall7f416cc2015-09-08 08:05:57 +00002683 if (!ReturnValue.isValid()) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002684 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00002685 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002686 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00002687
Dan Gohman481e40c2010-07-20 20:13:52 +00002688 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00002689 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00002690 QualType RetTy = FI.getReturnType();
2691 const ABIArgInfo &RetAI = FI.getReturnInfo();
2692
2693 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002694 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00002695 // Aggregrates get evaluated directly into the destination. Sometimes we
2696 // need to return the sret value in a register, though.
2697 assert(hasAggregateEvaluationKind(RetTy));
2698 if (RetAI.getInAllocaSRet()) {
2699 llvm::Function::arg_iterator EI = CurFn->arg_end();
2700 --EI;
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002701 llvm::Value *ArgStruct = &*EI;
David Blaikie2e804282015-04-05 22:47:07 +00002702 llvm::Value *SRet = Builder.CreateStructGEP(
2703 nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
John McCall7f416cc2015-09-08 08:05:57 +00002704 RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret");
Reid Klecknerfab1e892014-02-25 00:59:14 +00002705 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002706 break;
2707
Daniel Dunbar03816342010-08-21 02:24:36 +00002708 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002709 auto AI = CurFn->arg_begin();
2710 if (RetAI.isSRetAfterThis())
2711 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002712 switch (getEvaluationKind(RetTy)) {
2713 case TEK_Complex: {
2714 ComplexPairTy RT =
John McCall7f416cc2015-09-08 08:05:57 +00002715 EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002716 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002717 /*isInit*/ true);
2718 break;
2719 }
2720 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002721 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002722 break;
2723 case TEK_Scalar:
2724 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002725 MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002726 /*isInit*/ true);
2727 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002728 }
2729 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002730 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002731
2732 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002733 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002734 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2735 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002736 // The internal return value temp always will have pointer-to-return-type
2737 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002738
John McCall6e1c0122012-01-29 02:35:02 +00002739 // If there is a dominating store to ReturnValue, we can elide
2740 // the load, zap the store, and usually zap the alloca.
David Majnemerdc012fa2015-04-22 21:38:15 +00002741 if (llvm::StoreInst *SI =
2742 findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002743 // Reuse the debug location from the store unless there is
2744 // cleanup code to be emitted between the store and return
2745 // instruction.
2746 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002747 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002748 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002749 RV = SI->getValueOperand();
2750 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002751
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002752 // If that was the only use of the return value, nuke it as well now.
John McCall7f416cc2015-09-08 08:05:57 +00002753 auto returnValueInst = ReturnValue.getPointer();
2754 if (returnValueInst->use_empty()) {
2755 if (auto alloca = dyn_cast<llvm::AllocaInst>(returnValueInst)) {
2756 alloca->eraseFromParent();
2757 ReturnValue = Address::invalid();
2758 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002759 }
John McCall6e1c0122012-01-29 02:35:02 +00002760
2761 // Otherwise, we have to do a simple load.
2762 } else {
2763 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002764 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002765 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002766 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00002767 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002768
John McCall7f416cc2015-09-08 08:05:57 +00002769 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002770 }
John McCall31168b02011-06-15 23:02:42 +00002771
2772 // In ARC, end functions that return a retainable type with a call
2773 // to objc_autoreleaseReturnValue.
2774 if (AutoreleaseResult) {
Akira Hatanaka9d8ac612016-02-17 21:09:50 +00002775#ifndef NDEBUG
2776 // Type::isObjCRetainabletype has to be called on a QualType that hasn't
2777 // been stripped of the typedefs, so we cannot use RetTy here. Get the
2778 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
2779 // CurCodeDecl or BlockInfo.
2780 QualType RT;
2781
2782 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
2783 RT = FD->getReturnType();
2784 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
2785 RT = MD->getReturnType();
2786 else if (isa<BlockDecl>(CurCodeDecl))
2787 RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
2788 else
2789 llvm_unreachable("Unexpected function/method type");
2790
David Blaikiebbafb8a2012-03-11 07:00:24 +00002791 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002792 !FI.isReturnsRetained() &&
Akira Hatanaka9d8ac612016-02-17 21:09:50 +00002793 RT->isObjCRetainableType());
2794#endif
John McCall31168b02011-06-15 23:02:42 +00002795 RV = emitAutoreleaseOfResult(*this, RV);
2796 }
2797
Chris Lattner726b3d02010-06-26 23:13:19 +00002798 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002799
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002800 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002801 break;
2802
John McCallf26e73d2016-03-11 04:30:43 +00002803 case ABIArgInfo::CoerceAndExpand: {
2804 auto coercionType = RetAI.getCoerceAndExpandType();
2805 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
2806
2807 // Load all of the coerced elements out into results.
2808 llvm::SmallVector<llvm::Value*, 4> results;
2809 Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType);
2810 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2811 auto coercedEltType = coercionType->getElementType(i);
2812 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
2813 continue;
2814
2815 auto eltAddr = Builder.CreateStructGEP(addr, i, layout);
2816 auto elt = Builder.CreateLoad(eltAddr);
2817 results.push_back(elt);
2818 }
2819
2820 // If we have one result, it's the single direct result type.
2821 if (results.size() == 1) {
2822 RV = results[0];
2823
2824 // Otherwise, we need to make a first-class aggregate.
2825 } else {
2826 // Construct a return type that lacks padding elements.
2827 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
2828
2829 RV = llvm::UndefValue::get(returnType);
2830 for (unsigned i = 0, e = results.size(); i != e; ++i) {
2831 RV = Builder.CreateInsertValue(RV, results[i], i);
2832 }
2833 }
2834 break;
2835 }
2836
Chris Lattner726b3d02010-06-26 23:13:19 +00002837 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002838 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002839 }
2840
Alexey Samsonovde443c52014-08-13 00:26:40 +00002841 llvm::Instruction *Ret;
2842 if (RV) {
John McCall9a2c1c92015-09-10 00:57:46 +00002843 if (CurCodeDecl && SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) {
2844 if (auto RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>()) {
Alexey Samsonov90452df2014-09-08 20:17:19 +00002845 SanitizerScope SanScope(this);
2846 llvm::Value *Cond = Builder.CreateICmpNE(
2847 RV, llvm::Constant::getNullValue(RV->getType()));
2848 llvm::Constant *StaticData[] = {
2849 EmitCheckSourceLocation(EndLoc),
2850 EmitCheckSourceLocation(RetNNAttr->getLocation()),
2851 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002852 EmitCheck(std::make_pair(Cond, SanitizerKind::ReturnsNonnullAttribute),
2853 "nonnull_return", StaticData, None);
Alexey Samsonov90452df2014-09-08 20:17:19 +00002854 }
Alexey Samsonovde443c52014-08-13 00:26:40 +00002855 }
2856 Ret = Builder.CreateRet(RV);
2857 } else {
2858 Ret = Builder.CreateRetVoid();
2859 }
2860
Duncan P. N. Exon Smith2809cc72015-03-30 20:01:41 +00002861 if (RetDbgLoc)
Benjamin Kramer03278662015-02-07 13:15:54 +00002862 Ret->setDebugLoc(std::move(RetDbgLoc));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002863}
2864
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002865static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2866 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2867 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2868}
2869
John McCall7f416cc2015-09-08 08:05:57 +00002870static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
2871 QualType Ty) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002872 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2873 // placeholders.
2874 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2875 llvm::Value *Placeholder =
John McCall7f416cc2015-09-08 08:05:57 +00002876 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2877 Placeholder = CGF.Builder.CreateDefaultAlignedLoad(Placeholder);
2878
2879 // FIXME: When we generate this IR in one pass, we shouldn't need
2880 // this win32-specific alignment hack.
2881 CharUnits Align = CharUnits::fromQuantity(4);
2882
2883 return AggValueSlot::forAddr(Address(Placeholder, Align),
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002884 Ty.getQualifiers(),
2885 AggValueSlot::IsNotDestructed,
2886 AggValueSlot::DoesNotNeedGCBarriers,
2887 AggValueSlot::IsNotAliased);
2888}
2889
John McCall32ea9692011-03-11 20:59:21 +00002890void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002891 const VarDecl *param,
2892 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002893 // StartFunction converted the ABI-lowered parameter(s) into a
2894 // local alloca. We need to turn that into an r-value suitable
2895 // for EmitCall.
John McCall7f416cc2015-09-08 08:05:57 +00002896 Address local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002897
John McCall32ea9692011-03-11 20:59:21 +00002898 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002899
Reid Klecknerab2090d2014-07-26 01:34:32 +00002900 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2901 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002902
Richard Smithd62d4982016-06-14 01:13:21 +00002903 // For the most part, we just need to load the alloca, except that
2904 // aggregate r-values are actually pointers to temporaries.
2905 if (type->isReferenceType())
2906 args.add(RValue::get(Builder.CreateLoad(local)), type);
2907 else
2908 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00002909}
2910
John McCall31168b02011-06-15 23:02:42 +00002911static bool isProvablyNull(llvm::Value *addr) {
2912 return isa<llvm::ConstantPointerNull>(addr);
2913}
2914
2915static bool isProvablyNonNull(llvm::Value *addr) {
2916 return isa<llvm::AllocaInst>(addr);
2917}
2918
2919/// Emit the actual writing-back of a writeback.
2920static void emitWriteback(CodeGenFunction &CGF,
2921 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002922 const LValue &srcLV = writeback.Source;
John McCall7f416cc2015-09-08 08:05:57 +00002923 Address srcAddr = srcLV.getAddress();
2924 assert(!isProvablyNull(srcAddr.getPointer()) &&
John McCall31168b02011-06-15 23:02:42 +00002925 "shouldn't have writeback for provably null argument");
2926
Craig Topper8a13c412014-05-21 05:09:00 +00002927 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002928
2929 // If the argument wasn't provably non-null, we need to null check
2930 // before doing the store.
John McCall7f416cc2015-09-08 08:05:57 +00002931 bool provablyNonNull = isProvablyNonNull(srcAddr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002932 if (!provablyNonNull) {
2933 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2934 contBB = CGF.createBasicBlock("icr.done");
2935
John McCall7f416cc2015-09-08 08:05:57 +00002936 llvm::Value *isNull =
2937 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00002938 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2939 CGF.EmitBlock(writebackBB);
2940 }
2941
2942 // Load the value to writeback.
2943 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2944
2945 // Cast it back, in case we're writing an id to a Foo* or something.
John McCall7f416cc2015-09-08 08:05:57 +00002946 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
2947 "icr.writeback-cast");
John McCall31168b02011-06-15 23:02:42 +00002948
2949 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00002950
2951 // If we have a "to use" value, it's something we need to emit a use
2952 // of. This has to be carefully threaded in: if it's done after the
2953 // release it's potentially undefined behavior (and the optimizer
2954 // will ignore it), and if it happens before the retain then the
2955 // optimizer could move the release there.
2956 if (writeback.ToUse) {
2957 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2958
2959 // Retain the new value. No need to block-copy here: the block's
2960 // being passed up the stack.
2961 value = CGF.EmitARCRetainNonBlock(value);
2962
2963 // Emit the intrinsic use here.
2964 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2965
2966 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00002967 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00002968
2969 // Put the new value in place (primitively).
2970 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2971
2972 // Release the old value.
2973 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2974
2975 // Otherwise, we can just do a normal lvalue store.
2976 } else {
2977 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2978 }
John McCall31168b02011-06-15 23:02:42 +00002979
2980 // Jump to the continuation block.
2981 if (!provablyNonNull)
2982 CGF.EmitBlock(contBB);
2983}
2984
2985static void emitWritebacks(CodeGenFunction &CGF,
2986 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00002987 for (const auto &I : args.writebacks())
2988 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00002989}
2990
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002991static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2992 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002993 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002994 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2995 CallArgs.getCleanupsToDeactivate();
2996 // Iterate in reverse to increase the likelihood of popping the cleanup.
Pete Cooper57d3f142015-07-30 17:22:52 +00002997 for (const auto &I : llvm::reverse(Cleanups)) {
2998 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
2999 I.IsActiveIP->eraseFromParent();
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003000 }
3001}
3002
John McCalleff18842013-03-23 02:35:54 +00003003static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
3004 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
3005 if (uop->getOpcode() == UO_AddrOf)
3006 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00003007 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00003008}
3009
John McCall31168b02011-06-15 23:02:42 +00003010/// Emit an argument that's being passed call-by-writeback. That is,
John McCall7f416cc2015-09-08 08:05:57 +00003011/// we are passing the address of an __autoreleased temporary; it
3012/// might be copy-initialized with the current value of the given
3013/// address, but it will definitely be copied out of after the call.
John McCall31168b02011-06-15 23:02:42 +00003014static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
3015 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00003016 LValue srcLV;
3017
3018 // Make an optimistic effort to emit the address as an l-value.
Eric Christopher2c4555a2015-06-19 01:52:53 +00003019 // This can fail if the argument expression is more complicated.
John McCalleff18842013-03-23 02:35:54 +00003020 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
3021 srcLV = CGF.EmitLValue(lvExpr);
3022
3023 // Otherwise, just emit it as a scalar.
3024 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003025 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
John McCalleff18842013-03-23 02:35:54 +00003026
3027 QualType srcAddrType =
3028 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003029 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
John McCalleff18842013-03-23 02:35:54 +00003030 }
John McCall7f416cc2015-09-08 08:05:57 +00003031 Address srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00003032
3033 // The dest and src types don't necessarily match in LLVM terms
3034 // because of the crazy ObjC compatibility rules.
3035
Chris Lattner2192fe52011-07-18 04:24:23 +00003036 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00003037 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
3038
3039 // If the address is a constant null, just pass the appropriate null.
John McCall7f416cc2015-09-08 08:05:57 +00003040 if (isProvablyNull(srcAddr.getPointer())) {
John McCall31168b02011-06-15 23:02:42 +00003041 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
3042 CRE->getType());
3043 return;
3044 }
3045
John McCall31168b02011-06-15 23:02:42 +00003046 // Create the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003047 Address temp = CGF.CreateTempAlloca(destType->getElementType(),
3048 CGF.getPointerAlign(),
3049 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003050 // Loading an l-value can introduce a cleanup if the l-value is __weak,
3051 // and that cleanup will be conditional if we can't prove that the l-value
3052 // isn't null, so we need to register a dominating point so that the cleanups
3053 // system will make valid IR.
3054 CodeGenFunction::ConditionalEvaluation condEval(CGF);
3055
John McCall31168b02011-06-15 23:02:42 +00003056 // Zero-initialize it if we're not doing a copy-initialization.
3057 bool shouldCopy = CRE->shouldCopy();
3058 if (!shouldCopy) {
3059 llvm::Value *null =
3060 llvm::ConstantPointerNull::get(
3061 cast<llvm::PointerType>(destType->getElementType()));
3062 CGF.Builder.CreateStore(null, temp);
3063 }
Craig Topper8a13c412014-05-21 05:09:00 +00003064
3065 llvm::BasicBlock *contBB = nullptr;
3066 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00003067
3068 // If the address is *not* known to be non-null, we need to switch.
3069 llvm::Value *finalArgument;
3070
John McCall7f416cc2015-09-08 08:05:57 +00003071 bool provablyNonNull = isProvablyNonNull(srcAddr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00003072 if (provablyNonNull) {
John McCall7f416cc2015-09-08 08:05:57 +00003073 finalArgument = temp.getPointer();
John McCall31168b02011-06-15 23:02:42 +00003074 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003075 llvm::Value *isNull =
3076 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00003077
3078 finalArgument = CGF.Builder.CreateSelect(isNull,
3079 llvm::ConstantPointerNull::get(destType),
John McCall7f416cc2015-09-08 08:05:57 +00003080 temp.getPointer(), "icr.argument");
John McCall31168b02011-06-15 23:02:42 +00003081
3082 // If we need to copy, then the load has to be conditional, which
3083 // means we need control flow.
3084 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00003085 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00003086 contBB = CGF.createBasicBlock("icr.cont");
3087 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
3088 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
3089 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003090 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00003091 }
3092 }
3093
Craig Topper8a13c412014-05-21 05:09:00 +00003094 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00003095
John McCall31168b02011-06-15 23:02:42 +00003096 // Perform a copy if necessary.
3097 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00003098 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00003099 assert(srcRV.isScalar());
3100
3101 llvm::Value *src = srcRV.getScalarVal();
3102 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
3103 "icr.cast");
3104
3105 // Use an ordinary store, not a store-to-lvalue.
3106 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00003107
3108 // If optimization is enabled, and the value was held in a
3109 // __strong variable, we need to tell the optimizer that this
3110 // value has to stay alive until we're doing the store back.
3111 // This is because the temporary is effectively unretained,
3112 // and so otherwise we can violate the high-level semantics.
3113 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3114 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
3115 valueToUse = src;
3116 }
John McCall31168b02011-06-15 23:02:42 +00003117 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003118
John McCall31168b02011-06-15 23:02:42 +00003119 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003120 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00003121 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00003122 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00003123
3124 // Make a phi for the value to intrinsically use.
3125 if (valueToUse) {
3126 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
3127 "icr.to-use");
3128 phiToUse->addIncoming(valueToUse, copyBB);
3129 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
3130 originBB);
3131 valueToUse = phiToUse;
3132 }
3133
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003134 condEval.end(CGF);
3135 }
John McCall31168b02011-06-15 23:02:42 +00003136
John McCalleff18842013-03-23 02:35:54 +00003137 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00003138 args.add(RValue::get(finalArgument), CRE->getType());
3139}
3140
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003141void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
3142 assert(!StackBase && !StackCleanup.isValid());
3143
3144 // Save the stack.
3145 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie43f9bb72015-05-18 22:14:03 +00003146 StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003147}
3148
Nico Weber8cdb3f92015-08-25 18:43:32 +00003149void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
3150 if (StackBase) {
Reid Kleckner7c2f9e82015-10-08 00:17:45 +00003151 // Restore the stack after the call.
Nico Weber8cdb3f92015-08-25 18:43:32 +00003152 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
Nico Weber8cdb3f92015-08-25 18:43:32 +00003153 CGF.Builder.CreateCall(F, StackBase);
3154 }
3155}
3156
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003157void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
3158 SourceLocation ArgLoc,
3159 const FunctionDecl *FD,
3160 unsigned ParmNum) {
3161 if (!SanOpts.has(SanitizerKind::NonnullAttribute) || !FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003162 return;
3163 auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
3164 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
3165 auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
3166 if (!NNAttr)
3167 return;
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003168 SanitizerScope SanScope(this);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003169 assert(RV.isScalar());
3170 llvm::Value *V = RV.getScalarVal();
3171 llvm::Value *Cond =
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003172 Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003173 llvm::Constant *StaticData[] = {
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003174 EmitCheckSourceLocation(ArgLoc),
3175 EmitCheckSourceLocation(NNAttr->getLocation()),
3176 llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003177 };
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003178 EmitCheck(std::make_pair(Cond, SanitizerKind::NonnullAttribute),
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003179 "nonnull_arg", StaticData, None);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003180}
3181
David Blaikief05779e2015-07-21 18:37:18 +00003182void CodeGenFunction::EmitCallArgs(
3183 CallArgList &Args, ArrayRef<QualType> ArgTypes,
3184 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
3185 const FunctionDecl *CalleeDecl, unsigned ParamsToSkip) {
3186 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003187
3188 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg) {
3189 if (CalleeDecl == nullptr || I >= CalleeDecl->getNumParams())
3190 return;
3191 auto *PS = CalleeDecl->getParamDecl(I)->getAttr<PassObjectSizeAttr>();
3192 if (PS == nullptr)
3193 return;
3194
3195 const auto &Context = getContext();
3196 auto SizeTy = Context.getSizeType();
3197 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
3198 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T);
3199 Args.add(RValue::get(V), SizeTy);
3200 };
3201
Reid Kleckner739756c2013-12-04 19:23:12 +00003202 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
3203 // because arguments are destroyed left to right in the callee.
3204 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003205 // Insert a stack save if we're going to need any inalloca args.
3206 bool HasInAllocaArgs = false;
3207 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
3208 I != E && !HasInAllocaArgs; ++I)
3209 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
3210 if (HasInAllocaArgs) {
3211 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3212 Args.allocateArgumentMemory(*this);
3213 }
3214
3215 // Evaluate each argument.
Reid Kleckner739756c2013-12-04 19:23:12 +00003216 size_t CallArgsStart = Args.size();
3217 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
David Blaikief05779e2015-07-21 18:37:18 +00003218 CallExpr::const_arg_iterator Arg = ArgRange.begin() + I;
Richard Smith5179eb72016-06-28 19:03:57 +00003219 MaybeEmitImplicitObjectSize(I, *Arg);
Reid Kleckner739756c2013-12-04 19:23:12 +00003220 EmitCallArg(Args, *Arg, ArgTypes[I]);
Benjamin Kramerf48ee442015-07-18 14:35:53 +00003221 EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], (*Arg)->getExprLoc(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003222 CalleeDecl, ParamsToSkip + I);
Reid Kleckner739756c2013-12-04 19:23:12 +00003223 }
3224
3225 // Un-reverse the arguments we just evaluated so they match up with the LLVM
3226 // IR function.
3227 std::reverse(Args.begin() + CallArgsStart, Args.end());
3228 return;
3229 }
3230
3231 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
David Blaikief05779e2015-07-21 18:37:18 +00003232 CallExpr::const_arg_iterator Arg = ArgRange.begin() + I;
3233 assert(Arg != ArgRange.end());
Reid Kleckner739756c2013-12-04 19:23:12 +00003234 EmitCallArg(Args, *Arg, ArgTypes[I]);
Benjamin Kramerf48ee442015-07-18 14:35:53 +00003235 EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], (*Arg)->getExprLoc(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003236 CalleeDecl, ParamsToSkip + I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003237 MaybeEmitImplicitObjectSize(I, *Arg);
Reid Kleckner739756c2013-12-04 19:23:12 +00003238 }
3239}
3240
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003241namespace {
3242
David Blaikie7e70d682015-08-18 22:40:54 +00003243struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +00003244 DestroyUnpassedArg(Address Addr, QualType Ty)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003245 : Addr(Addr), Ty(Ty) {}
3246
John McCall7f416cc2015-09-08 08:05:57 +00003247 Address Addr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003248 QualType Ty;
3249
Craig Topper4f12f102014-03-12 06:41:41 +00003250 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003251 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
3252 assert(!Dtor->isTrivial());
3253 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
3254 /*Delegating=*/false, Addr);
3255 }
3256};
3257
David Blaikie38b25912015-02-09 19:13:51 +00003258struct DisableDebugLocationUpdates {
3259 CodeGenFunction &CGF;
3260 bool disabledDebugInfo;
3261 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
3262 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
3263 CGF.disableDebugInfo();
3264 }
3265 ~DisableDebugLocationUpdates() {
3266 if (disabledDebugInfo)
3267 CGF.enableDebugInfo();
3268 }
3269};
3270
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00003271} // end anonymous namespace
3272
John McCall32ea9692011-03-11 20:59:21 +00003273void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
3274 QualType type) {
David Blaikie38b25912015-02-09 19:13:51 +00003275 DisableDebugLocationUpdates Dis(*this, E);
John McCall31168b02011-06-15 23:02:42 +00003276 if (const ObjCIndirectCopyRestoreExpr *CRE
3277 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00003278 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00003279 assert(getContext().hasSameType(E->getType(), type));
3280 return emitWritebackArg(*this, args, CRE);
3281 }
3282
John McCall0a76c0c2011-08-26 18:42:59 +00003283 assert(type->isReferenceType() == E->isGLValue() &&
3284 "reference binding to unmaterialized r-value!");
3285
John McCall17054bd62011-08-26 21:08:13 +00003286 if (E->isGLValue()) {
3287 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00003288 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00003289 }
Mike Stump11289f42009-09-09 15:08:12 +00003290
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003291 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
3292
3293 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
3294 // However, we still have to push an EH-only cleanup in case we unwind before
3295 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00003296 if (HasAggregateEvalKind &&
3297 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
3298 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00003299 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00003300 AggValueSlot Slot;
3301 if (args.isUsingInAlloca())
3302 Slot = createPlaceholderSlot(*this, type);
3303 else
3304 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00003305
3306 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
3307 bool DestroyedInCallee =
3308 RD && RD->hasNonTrivialDestructor() &&
3309 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
3310 if (DestroyedInCallee)
3311 Slot.setExternallyDestructed();
3312
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003313 EmitAggExpr(E, Slot);
3314 RValue RV = Slot.asRValue();
3315 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003316
Reid Klecknere39ee212014-05-03 00:33:28 +00003317 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003318 // Create a no-op GEP between the placeholder and the cleanup so we can
3319 // RAUW it successfully. It also serves as a marker of the first
3320 // instruction where the cleanup is active.
John McCall7f416cc2015-09-08 08:05:57 +00003321 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
3322 type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003323 // This unreachable is a temporary marker which will be removed later.
3324 llvm::Instruction *IsActive = Builder.CreateUnreachable();
3325 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003326 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003327 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003328 }
3329
3330 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00003331 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
3332 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
3333 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00003334 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
3335 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
3336 } else {
3337 // We can't represent a misaligned lvalue in the CallArgList, so copy
3338 // to an aligned temporary now.
John McCall7f416cc2015-09-08 08:05:57 +00003339 Address tmp = CreateMemTemp(type);
3340 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile());
Eli Friedman61f615a2013-06-11 01:08:22 +00003341 args.add(RValue::getAggregate(tmp), type);
3342 }
Eli Friedmandf968192011-05-26 00:10:27 +00003343 return;
3344 }
3345
John McCall32ea9692011-03-11 20:59:21 +00003346 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00003347}
3348
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003349QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
3350 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
3351 // implicitly widens null pointer constants that are arguments to varargs
3352 // functions to pointer-sized ints.
3353 if (!getTarget().getTriple().isOSWindows())
3354 return Arg->getType();
3355
3356 if (Arg->getType()->isIntegerType() &&
3357 getContext().getTypeSize(Arg->getType()) <
3358 getContext().getTargetInfo().getPointerWidth(0) &&
3359 Arg->isNullPointerConstant(getContext(),
3360 Expr::NPC_ValueDependentIsNotNull)) {
3361 return getContext().getIntPtrType();
3362 }
3363
3364 return Arg->getType();
3365}
3366
Dan Gohman515a60d2012-02-16 00:57:37 +00003367// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3368// optimizer it can aggressively ignore unwind edges.
3369void
3370CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
3371 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3372 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
3373 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
3374 CGM.getNoObjCARCExceptionsMetadata());
3375}
3376
John McCall882987f2013-02-28 19:01:20 +00003377/// Emits a call to the given no-arguments nounwind runtime function.
3378llvm::CallInst *
3379CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3380 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003381 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003382}
3383
3384/// Emits a call to the given nounwind runtime function.
3385llvm::CallInst *
3386CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3387 ArrayRef<llvm::Value*> args,
3388 const llvm::Twine &name) {
3389 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
3390 call->setDoesNotThrow();
3391 return call;
3392}
3393
3394/// Emits a simple call (never an invoke) to the given no-arguments
3395/// runtime function.
3396llvm::CallInst *
3397CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3398 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003399 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003400}
3401
David Majnemer0b17d442015-12-15 21:27:59 +00003402// Calls which may throw must have operand bundles indicating which funclet
3403// they are nested within.
3404static void
Sanjay Patel846b63b2016-01-18 22:15:33 +00003405getBundlesForFunclet(llvm::Value *Callee, llvm::Instruction *CurrentFuncletPad,
David Majnemer0b17d442015-12-15 21:27:59 +00003406 SmallVectorImpl<llvm::OperandBundleDef> &BundleList) {
Sanjay Patel846b63b2016-01-18 22:15:33 +00003407 // There is no need for a funclet operand bundle if we aren't inside a
3408 // funclet.
David Majnemer0b17d442015-12-15 21:27:59 +00003409 if (!CurrentFuncletPad)
3410 return;
3411
3412 // Skip intrinsics which cannot throw.
3413 auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts());
3414 if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow())
3415 return;
3416
3417 BundleList.emplace_back("funclet", CurrentFuncletPad);
3418}
3419
David Majnemer971d31b2016-02-24 17:02:45 +00003420/// Emits a simple call (never an invoke) to the given runtime function.
3421llvm::CallInst *
3422CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3423 ArrayRef<llvm::Value*> args,
3424 const llvm::Twine &name) {
3425 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3426 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList);
3427
3428 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList, name);
3429 call->setCallingConv(getRuntimeCC());
3430 return call;
3431}
3432
John McCall882987f2013-02-28 19:01:20 +00003433/// Emits a call or invoke to the given noreturn runtime function.
3434void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
3435 ArrayRef<llvm::Value*> args) {
David Majnemer0b17d442015-12-15 21:27:59 +00003436 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3437 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList);
3438
John McCall882987f2013-02-28 19:01:20 +00003439 if (getInvokeDest()) {
3440 llvm::InvokeInst *invoke =
3441 Builder.CreateInvoke(callee,
3442 getUnreachableBlock(),
3443 getInvokeDest(),
David Majnemer0b17d442015-12-15 21:27:59 +00003444 args,
3445 BundleList);
John McCall882987f2013-02-28 19:01:20 +00003446 invoke->setDoesNotReturn();
3447 invoke->setCallingConv(getRuntimeCC());
3448 } else {
David Majnemer0b17d442015-12-15 21:27:59 +00003449 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
John McCall882987f2013-02-28 19:01:20 +00003450 call->setDoesNotReturn();
3451 call->setCallingConv(getRuntimeCC());
3452 Builder.CreateUnreachable();
3453 }
3454}
3455
Sanjay Patel846b63b2016-01-18 22:15:33 +00003456/// Emits a call or invoke instruction to the given nullary runtime function.
John McCall882987f2013-02-28 19:01:20 +00003457llvm::CallSite
3458CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3459 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003460 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003461}
3462
3463/// Emits a call or invoke instruction to the given runtime function.
3464llvm::CallSite
3465CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3466 ArrayRef<llvm::Value*> args,
3467 const Twine &name) {
3468 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
3469 callSite.setCallingConv(getRuntimeCC());
3470 return callSite;
3471}
3472
John McCallbd309292010-07-06 01:34:17 +00003473/// Emits a call or invoke instruction to the given function, depending
3474/// on the current state of the EH stack.
3475llvm::CallSite
3476CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00003477 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003478 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00003479 llvm::BasicBlock *InvokeDest = getInvokeDest();
David Majnemer3df77bc2016-01-26 23:14:47 +00003480 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3481 getBundlesForFunclet(Callee, CurrentFuncletPad, BundleList);
John McCallbd309292010-07-06 01:34:17 +00003482
Dan Gohman515a60d2012-02-16 00:57:37 +00003483 llvm::Instruction *Inst;
3484 if (!InvokeDest)
David Majnemer3df77bc2016-01-26 23:14:47 +00003485 Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
Dan Gohman515a60d2012-02-16 00:57:37 +00003486 else {
3487 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
David Majnemer3df77bc2016-01-26 23:14:47 +00003488 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
3489 Name);
Dan Gohman515a60d2012-02-16 00:57:37 +00003490 EmitBlock(ContBB);
3491 }
3492
3493 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3494 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003495 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003496 AddObjCARCExceptionMetadata(Inst);
3497
Benjamin Kramerc19cde12015-04-10 14:49:31 +00003498 return llvm::CallSite(Inst);
John McCallbd309292010-07-06 01:34:17 +00003499}
3500
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003501/// \brief Store a non-aggregate value to an address to initialize it. For
3502/// initialization, a non-atomic store will be used.
3503static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
3504 LValue Dst) {
3505 if (Src.isScalar())
3506 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
3507 else
3508 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
3509}
3510
3511void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
3512 llvm::Value *New) {
3513 DeferredReplacements.push_back(std::make_pair(Old, New));
3514}
Chris Lattnerd59d8672011-07-12 06:29:11 +00003515
Daniel Dunbard931a872009-02-02 22:03:45 +00003516RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00003517 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00003518 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003519 const CallArgList &CallArgs,
Samuel Antao798f11c2015-11-23 22:04:44 +00003520 CGCalleeInfo CalleeInfo,
David Chisnallff5f88c2010-05-02 13:41:58 +00003521 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00003522 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00003523
3524 // Handle struct-return functions by passing a pointer to the
3525 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00003526 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003527 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003528
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003529 llvm::FunctionType *IRFuncTy =
3530 cast<llvm::FunctionType>(
3531 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00003532
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003533 // If we're using inalloca, insert the allocation after the stack save.
3534 // FIXME: Do this earlier rather than hacking it in here!
John McCall7f416cc2015-09-08 08:05:57 +00003535 Address ArgMemory = Address::invalid();
3536 const llvm::StructLayout *ArgMemoryLayout = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003537 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
John McCall7f416cc2015-09-08 08:05:57 +00003538 ArgMemoryLayout = CGM.getDataLayout().getStructLayout(ArgStruct);
Reid Kleckner9df1d972014-04-10 01:40:15 +00003539 llvm::Instruction *IP = CallArgs.getStackBase();
3540 llvm::AllocaInst *AI;
3541 if (IP) {
3542 IP = IP->getNextNode();
3543 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
3544 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00003545 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00003546 }
John McCall7f416cc2015-09-08 08:05:57 +00003547 auto Align = CallInfo.getArgStructAlignment();
3548 AI->setAlignment(Align.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003549 AI->setUsedWithInAlloca(true);
3550 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
John McCall7f416cc2015-09-08 08:05:57 +00003551 ArgMemory = Address(AI, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003552 }
3553
John McCall7f416cc2015-09-08 08:05:57 +00003554 // Helper function to drill into the inalloca allocation.
3555 auto createInAllocaStructGEP = [&](unsigned FieldIndex) -> Address {
3556 auto FieldOffset =
3557 CharUnits::fromQuantity(ArgMemoryLayout->getElementOffset(FieldIndex));
3558 return Builder.CreateStructGEP(ArgMemory, FieldIndex, FieldOffset);
3559 };
3560
Alexey Samsonov153004f2014-09-29 22:08:00 +00003561 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003562 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
3563
Chris Lattner4ca97c32009-06-13 00:26:38 +00003564 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00003565 // alloca to hold the result, unless one is given to us.
John McCall7f416cc2015-09-08 08:05:57 +00003566 Address SRetPtr = Address::invalid();
Leny Kholodov6aab1112015-06-08 10:23:49 +00003567 size_t UnusedReturnSize = 0;
John McCallf26e73d2016-03-11 04:30:43 +00003568 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
John McCall7f416cc2015-09-08 08:05:57 +00003569 if (!ReturnValue.isNull()) {
3570 SRetPtr = ReturnValue.getValue();
3571 } else {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003572 SRetPtr = CreateMemTemp(RetTy);
Leny Kholodov6aab1112015-06-08 10:23:49 +00003573 if (HaveInsertPoint() && ReturnValue.isUnused()) {
3574 uint64_t size =
3575 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
John McCall7f416cc2015-09-08 08:05:57 +00003576 if (EmitLifetimeStart(size, SRetPtr.getPointer()))
Leny Kholodov6aab1112015-06-08 10:23:49 +00003577 UnusedReturnSize = size;
3578 }
3579 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003580 if (IRFunctionArgs.hasSRetArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00003581 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
John McCallf26e73d2016-03-11 04:30:43 +00003582 } else if (RetAI.isInAlloca()) {
John McCall7f416cc2015-09-08 08:05:57 +00003583 Address Addr = createInAllocaStructGEP(RetAI.getInAllocaFieldIndex());
3584 Builder.CreateStore(SRetPtr.getPointer(), Addr);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003585 }
Anders Carlsson17490832009-12-24 20:40:36 +00003586 }
Mike Stump11289f42009-09-09 15:08:12 +00003587
John McCall12f23522016-04-04 18:33:08 +00003588 Address swiftErrorTemp = Address::invalid();
3589 Address swiftErrorArg = Address::invalid();
3590
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00003591 assert(CallInfo.arg_size() == CallArgs.size() &&
3592 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003593 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003594 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00003595 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003596 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003597 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003598 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003599
Rafael Espindolafad28de2012-10-24 01:59:00 +00003600 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003601 if (IRFunctionArgs.hasPaddingArg(ArgNo))
3602 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
3603 llvm::UndefValue::get(ArgInfo.getPaddingType());
3604
3605 unsigned FirstIRArg, NumIRArgs;
3606 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003607
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003608 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003609 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003610 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003611 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3612 if (RV.isAggregate()) {
3613 // Replace the placeholder with the appropriate argument slot GEP.
3614 llvm::Instruction *Placeholder =
John McCall7f416cc2015-09-08 08:05:57 +00003615 cast<llvm::Instruction>(RV.getAggregatePointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003616 CGBuilderTy::InsertPoint IP = Builder.saveIP();
3617 Builder.SetInsertPoint(Placeholder);
John McCall7f416cc2015-09-08 08:05:57 +00003618 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003619 Builder.restoreIP(IP);
John McCall7f416cc2015-09-08 08:05:57 +00003620 deferPlaceholderReplacement(Placeholder, Addr.getPointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003621 } else {
3622 // Store the RValue into the argument struct.
John McCall7f416cc2015-09-08 08:05:57 +00003623 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
3624 unsigned AS = Addr.getType()->getPointerAddressSpace();
David Majnemer32b57b02014-03-31 16:12:47 +00003625 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3626 // There are some cases where a trivial bitcast is not avoidable. The
3627 // definition of a type later in a translation unit may change it's type
3628 // from {}* to (%struct.foo*)*.
John McCall7f416cc2015-09-08 08:05:57 +00003629 if (Addr.getType() != MemType)
David Majnemer32b57b02014-03-31 16:12:47 +00003630 Addr = Builder.CreateBitCast(Addr, MemType);
John McCall7f416cc2015-09-08 08:05:57 +00003631 LValue argLV = MakeAddrLValue(Addr, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003632 EmitInitStoreOfNonAggregate(*this, RV, argLV);
3633 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003634 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003635 }
3636
Daniel Dunbar03816342010-08-21 02:24:36 +00003637 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003638 assert(NumIRArgs == 1);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003639 if (RV.isScalar() || RV.isComplex()) {
3640 // Make a temporary alloca to pass the argument.
John McCall7f416cc2015-09-08 08:05:57 +00003641 Address Addr = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3642 IRCallArgs[FirstIRArg] = Addr.getPointer();
John McCall47fb9502013-03-07 21:37:08 +00003643
John McCall7f416cc2015-09-08 08:05:57 +00003644 LValue argLV = MakeAddrLValue(Addr, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003645 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003646 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003647 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00003648 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003649 // 1. If the argument is not byval, and we are required to copy the
3650 // source. (This case doesn't occur on any common architecture.)
3651 // 2. If the argument is byval, RV is not sufficiently aligned, and
3652 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00003653 // 3. If the argument is byval, but RV is located in an address space
3654 // different than that of the argument (0).
John McCall7f416cc2015-09-08 08:05:57 +00003655 Address Addr = RV.getAggregateAddress();
3656 CharUnits Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003657 const llvm::DataLayout *TD = &CGM.getDataLayout();
John McCall7f416cc2015-09-08 08:05:57 +00003658 const unsigned RVAddrSpace = Addr.getType()->getAddressSpace();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003659 const unsigned ArgAddrSpace =
3660 (FirstIRArg < IRFuncTy->getNumParams()
3661 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
3662 : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00003663 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall7f416cc2015-09-08 08:05:57 +00003664 (ArgInfo.getIndirectByVal() && Addr.getAlignment() < Align &&
3665 llvm::getOrEnforceKnownAlignment(Addr.getPointer(),
3666 Align.getQuantity(), *TD)
3667 < Align.getQuantity()) ||
Mehdi Aminib3d52092015-03-10 02:36:43 +00003668 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003669 // Create an aligned temporary, and copy to it.
John McCall7f416cc2015-09-08 08:05:57 +00003670 Address AI = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3671 IRCallArgs[FirstIRArg] = AI.getPointer();
Chad Rosier615ed1a2012-03-29 17:37:10 +00003672 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003673 } else {
3674 // Skip the extra memcpy call.
John McCall7f416cc2015-09-08 08:05:57 +00003675 IRCallArgs[FirstIRArg] = Addr.getPointer();
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003676 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003677 }
3678 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00003679 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003680
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003681 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003682 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003683 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003684
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003685 case ABIArgInfo::Extend:
3686 case ABIArgInfo::Direct: {
3687 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003688 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3689 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003690 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003691 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003692 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003693 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003694 else
John McCall7f416cc2015-09-08 08:05:57 +00003695 V = Builder.CreateLoad(RV.getAggregateAddress());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003696
John McCall12f23522016-04-04 18:33:08 +00003697 // Implement swifterror by copying into a new swifterror argument.
3698 // We'll write back in the normal path out of the call.
3699 if (CallInfo.getExtParameterInfo(ArgNo).getABI()
3700 == ParameterABI::SwiftErrorResult) {
3701 assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
3702
3703 QualType pointeeTy = I->Ty->getPointeeType();
3704 swiftErrorArg =
3705 Address(V, getContext().getTypeAlignInChars(pointeeTy));
3706
3707 swiftErrorTemp =
3708 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
3709 V = swiftErrorTemp.getPointer();
3710 cast<llvm::AllocaInst>(V)->setSwiftError(true);
3711
3712 llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
3713 Builder.CreateStore(errorValue, swiftErrorTemp);
3714 }
3715
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003716 // We might have to widen integers, but we should never truncate.
3717 if (ArgInfo.getCoerceToType() != V->getType() &&
3718 V->getType()->isIntegerTy())
3719 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
3720
Chris Lattner3ce86682011-07-12 04:53:39 +00003721 // If the argument doesn't match, perform a bitcast to coerce it. This
3722 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003723 if (FirstIRArg < IRFuncTy->getNumParams() &&
3724 V->getType() != IRFuncTy->getParamType(FirstIRArg))
3725 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
John McCall12f23522016-04-04 18:33:08 +00003726
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003727 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003728 break;
3729 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003730
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003731 // FIXME: Avoid the conversion through memory if possible.
John McCall7f416cc2015-09-08 08:05:57 +00003732 Address Src = Address::invalid();
John McCall47fb9502013-03-07 21:37:08 +00003733 if (RV.isScalar() || RV.isComplex()) {
John McCall7f416cc2015-09-08 08:05:57 +00003734 Src = CreateMemTemp(I->Ty, "coerce");
3735 LValue SrcLV = MakeAddrLValue(Src, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003736 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00003737 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003738 Src = RV.getAggregateAddress();
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00003739 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003740
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003741 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00003742 Src = emitAddressAtOffset(*this, Src, ArgInfo);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003743
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003744 // Fast-isel and the optimizer generally like scalar values better than
3745 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00003746 llvm::StructType *STy =
3747 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003748 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
John McCall7f416cc2015-09-08 08:05:57 +00003749 llvm::Type *SrcTy = Src.getType()->getElementType();
Chandler Carrutha6399a52012-10-10 11:29:08 +00003750 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
3751 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
3752
3753 // If the source type is smaller than the destination type of the
3754 // coerce-to logic, copy the source value into a temp alloca the size
3755 // of the destination type to allow loading all of it. The bits past
3756 // the source value are left undef.
3757 if (SrcSize < DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00003758 Address TempAlloca
3759 = CreateTempAlloca(STy, Src.getAlignment(),
3760 Src.getName() + ".coerce");
3761 Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
3762 Src = TempAlloca;
Chandler Carrutha6399a52012-10-10 11:29:08 +00003763 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003764 Src = Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(STy));
Chandler Carrutha6399a52012-10-10 11:29:08 +00003765 }
3766
John McCall7f416cc2015-09-08 08:05:57 +00003767 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003768 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00003769 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00003770 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
3771 Address EltPtr = Builder.CreateStructGEP(Src, i, Offset);
3772 llvm::Value *LI = Builder.CreateLoad(EltPtr);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003773 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00003774 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00003775 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00003776 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003777 assert(NumIRArgs == 1);
3778 IRCallArgs[FirstIRArg] =
John McCall7f416cc2015-09-08 08:05:57 +00003779 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00003780 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003781
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003782 break;
3783 }
3784
John McCallf26e73d2016-03-11 04:30:43 +00003785 case ABIArgInfo::CoerceAndExpand: {
John McCallf26e73d2016-03-11 04:30:43 +00003786 auto coercionType = ArgInfo.getCoerceAndExpandType();
3787 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
3788
John McCall12f23522016-04-04 18:33:08 +00003789 llvm::Value *tempSize = nullptr;
3790 Address addr = Address::invalid();
3791 if (RV.isAggregate()) {
3792 addr = RV.getAggregateAddress();
3793 } else {
3794 assert(RV.isScalar()); // complex should always just be direct
3795
3796 llvm::Type *scalarType = RV.getScalarVal()->getType();
3797 auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
3798 auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType);
3799
3800 tempSize = llvm::ConstantInt::get(CGM.Int64Ty, scalarSize);
3801
3802 // Materialize to a temporary.
3803 addr = CreateTempAlloca(RV.getScalarVal()->getType(),
3804 CharUnits::fromQuantity(std::max(layout->getAlignment(),
3805 scalarAlign)));
3806 EmitLifetimeStart(scalarSize, addr.getPointer());
3807
3808 Builder.CreateStore(RV.getScalarVal(), addr);
3809 }
3810
John McCallf26e73d2016-03-11 04:30:43 +00003811 addr = Builder.CreateElementBitCast(addr, coercionType);
3812
3813 unsigned IRArgPos = FirstIRArg;
3814 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3815 llvm::Type *eltType = coercionType->getElementType(i);
3816 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
3817 Address eltAddr = Builder.CreateStructGEP(addr, i, layout);
3818 llvm::Value *elt = Builder.CreateLoad(eltAddr);
3819 IRCallArgs[IRArgPos++] = elt;
3820 }
3821 assert(IRArgPos == FirstIRArg + NumIRArgs);
3822
John McCall12f23522016-04-04 18:33:08 +00003823 if (tempSize) {
3824 EmitLifetimeEnd(tempSize, addr.getPointer());
3825 }
3826
John McCallf26e73d2016-03-11 04:30:43 +00003827 break;
3828 }
3829
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003830 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003831 unsigned IRArgPos = FirstIRArg;
3832 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
3833 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003834 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003835 }
3836 }
Mike Stump11289f42009-09-09 15:08:12 +00003837
John McCall7f416cc2015-09-08 08:05:57 +00003838 if (ArgMemory.isValid()) {
3839 llvm::Value *Arg = ArgMemory.getPointer();
Reid Klecknerafba553e2014-07-08 02:24:27 +00003840 if (CallInfo.isVariadic()) {
3841 // When passing non-POD arguments by value to variadic functions, we will
3842 // end up with a variadic prototype and an inalloca call site. In such
3843 // cases, we can't do any parameter mismatch checks. Give up and bitcast
3844 // the callee.
3845 unsigned CalleeAS =
3846 cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
3847 Callee = Builder.CreateBitCast(
3848 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
3849 } else {
3850 llvm::Type *LastParamTy =
3851 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
3852 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003853#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00003854 // Assert that these structs have equivalent element types.
3855 llvm::StructType *FullTy = CallInfo.getArgStruct();
3856 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3857 cast<llvm::PointerType>(LastParamTy)->getElementType());
3858 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3859 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3860 DE = DeclaredTy->element_end(),
3861 FI = FullTy->element_begin();
3862 DI != DE; ++DI, ++FI)
3863 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003864#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00003865 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3866 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003867 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003868 assert(IRFunctionArgs.hasInallocaArg());
3869 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003870 }
3871
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003872 if (!CallArgs.getCleanupsToDeactivate().empty())
3873 deactivateArgCleanupsBeforeCall(*this, CallArgs);
3874
Chris Lattner4ca97c32009-06-13 00:26:38 +00003875 // If the callee is a bitcast of a function to a varargs pointer to function
3876 // type, check to see if we can remove the bitcast. This handles some cases
3877 // with unprototyped functions.
3878 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
3879 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003880 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
3881 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00003882 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00003883 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00003884
Chris Lattner4ca97c32009-06-13 00:26:38 +00003885 if (CE->getOpcode() == llvm::Instruction::BitCast &&
3886 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00003887 ActualFT->getNumParams() == CurFT->getNumParams() &&
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003888 ActualFT->getNumParams() == IRCallArgs.size() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00003889 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00003890 bool ArgsMatch = true;
3891 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
3892 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
3893 ArgsMatch = false;
3894 break;
3895 }
Mike Stump11289f42009-09-09 15:08:12 +00003896
Chris Lattner4ca97c32009-06-13 00:26:38 +00003897 // Strip the cast if we can get away with it. This is a nice cleanup,
3898 // but also allows us to inline the function at -O0 if it is marked
3899 // always_inline.
3900 if (ArgsMatch)
3901 Callee = CalleeF;
3902 }
3903 }
Mike Stump11289f42009-09-09 15:08:12 +00003904
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003905 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
3906 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
3907 // Inalloca argument can have different type.
3908 if (IRFunctionArgs.hasInallocaArg() &&
3909 i == IRFunctionArgs.getInallocaArgNo())
3910 continue;
3911 if (i < IRFuncTy->getNumParams())
3912 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
3913 }
3914
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003915 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00003916 CodeGen::AttributeListType AttributeList;
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00003917 CGM.ConstructAttributeList(Callee->getName(), CallInfo, CalleeInfo,
3918 AttributeList, CallingConv,
3919 /*AttrOnCallSite=*/true);
Bill Wendling3087d022012-12-07 23:17:26 +00003920 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003921 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00003922
David Majnemer4e52d6f2015-12-12 05:39:21 +00003923 bool CannotThrow;
3924 if (currentFunctionUsesSEHTry()) {
3925 // SEH cares about asynchronous exceptions, everything can "throw."
3926 CannotThrow = false;
3927 } else if (isCleanupPadScope() &&
3928 EHPersonality::get(*this).isMSVCXXPersonality()) {
3929 // The MSVC++ personality will implicitly terminate the program if an
3930 // exception is thrown. An unwind edge cannot be reached.
3931 CannotThrow = true;
3932 } else {
3933 // Otherwise, nowunind callsites will never throw.
3934 CannotThrow = Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
3935 llvm::Attribute::NoUnwind);
3936 }
3937 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00003938
David Majnemer0b17d442015-12-15 21:27:59 +00003939 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3940 getBundlesForFunclet(Callee, CurrentFuncletPad, BundleList);
3941
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003942 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00003943 if (!InvokeDest) {
David Majnemer0b17d442015-12-15 21:27:59 +00003944 CS = Builder.CreateCall(Callee, IRCallArgs, BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00003945 } else {
3946 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
David Majnemer0b17d442015-12-15 21:27:59 +00003947 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs,
3948 BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00003949 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003950 }
Chris Lattnere70a0072010-06-29 16:40:28 +00003951 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00003952 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003953
Peter Collingbourne41af7c22014-05-20 17:12:51 +00003954 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
3955 !CS.hasFnAttr(llvm::Attribute::NoInline))
3956 Attrs =
3957 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3958 llvm::Attribute::AlwaysInline);
3959
David Majnemer4e52d6f2015-12-12 05:39:21 +00003960 // Disable inlining inside SEH __try blocks.
3961 if (isSEHTryScope())
Reid Klecknera5930002015-02-11 21:40:48 +00003962 Attrs =
3963 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3964 llvm::Attribute::NoInline);
3965
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003966 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003967 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003968
Adam Nemet1e217bc2016-03-28 22:18:53 +00003969 // Insert instrumentation or attach profile metadata at indirect call sites.
3970 // For more details, see the comment before the definition of
3971 // IPVK_IndirectCallTarget in InstrProfData.inc.
Betul Buyukkurt518276a2016-01-23 22:50:44 +00003972 if (!CS.getCalledFunction())
3973 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
3974 CS.getInstruction(), Callee);
3975
Dan Gohman515a60d2012-02-16 00:57:37 +00003976 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3977 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003978 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003979 AddObjCARCExceptionMetadata(CS.getInstruction());
3980
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003981 // If the call doesn't return, finish the basic block and clear the
3982 // insertion point; this allows the rest of IRgen to discard
3983 // unreachable code.
3984 if (CS.doesNotReturn()) {
Leny Kholodov6aab1112015-06-08 10:23:49 +00003985 if (UnusedReturnSize)
3986 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
John McCall7f416cc2015-09-08 08:05:57 +00003987 SRetPtr.getPointer());
Leny Kholodov6aab1112015-06-08 10:23:49 +00003988
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003989 Builder.CreateUnreachable();
3990 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003991
Mike Stump18bb9282009-05-16 07:57:57 +00003992 // FIXME: For now, emit a dummy basic block because expr emitters in
3993 // generally are not ready to handle emitting expressions at unreachable
3994 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003995 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003996
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003997 // Return a reasonable RValue.
3998 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00003999 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004000
4001 llvm::Instruction *CI = CS.getInstruction();
Mehdi Amini557c20a2016-03-13 21:05:23 +00004002 if (!CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00004003 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00004004
John McCall12f23522016-04-04 18:33:08 +00004005 // Perform the swifterror writeback.
4006 if (swiftErrorTemp.isValid()) {
4007 llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
4008 Builder.CreateStore(errorResult, swiftErrorArg);
4009 }
4010
John McCall31168b02011-06-15 23:02:42 +00004011 // Emit any writebacks immediately. Arguably this should happen
4012 // after any return-value munging.
4013 if (CallArgs.hasWritebacks())
4014 emitWritebacks(*this, CallArgs);
4015
Nico Weber8cdb3f92015-08-25 18:43:32 +00004016 // The stack cleanup for inalloca arguments has to run out of the normal
4017 // lexical order, so deactivate it and run it manually here.
4018 CallArgs.freeArgumentMemory(*this);
4019
Samuel Antao798f11c2015-11-23 22:04:44 +00004020 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
4021 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
Akira Hatanakac8667622015-11-06 23:56:15 +00004022 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
4023 Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
Samuel Antao798f11c2015-11-23 22:04:44 +00004024 }
Akira Hatanakac8667622015-11-06 23:56:15 +00004025
Hal Finkelee90a222014-09-26 05:04:30 +00004026 RValue Ret = [&] {
4027 switch (RetAI.getKind()) {
John McCallf26e73d2016-03-11 04:30:43 +00004028 case ABIArgInfo::CoerceAndExpand: {
4029 auto coercionType = RetAI.getCoerceAndExpandType();
4030 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
4031
4032 Address addr = SRetPtr;
4033 addr = Builder.CreateElementBitCast(addr, coercionType);
4034
John McCall12f23522016-04-04 18:33:08 +00004035 assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
4036 bool requiresExtract = isa<llvm::StructType>(CI->getType());
4037
John McCallf26e73d2016-03-11 04:30:43 +00004038 unsigned unpaddedIndex = 0;
4039 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
4040 llvm::Type *eltType = coercionType->getElementType(i);
4041 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
4042 Address eltAddr = Builder.CreateStructGEP(addr, i, layout);
John McCall12f23522016-04-04 18:33:08 +00004043 llvm::Value *elt = CI;
4044 if (requiresExtract)
4045 elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
4046 else
4047 assert(unpaddedIndex == 0);
John McCallf26e73d2016-03-11 04:30:43 +00004048 Builder.CreateStore(elt, eltAddr);
4049 }
John McCall12f23522016-04-04 18:33:08 +00004050 // FALLTHROUGH
4051 }
4052
4053 case ABIArgInfo::InAlloca:
4054 case ABIArgInfo::Indirect: {
4055 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
4056 if (UnusedReturnSize)
4057 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
4058 SRetPtr.getPointer());
4059 return ret;
John McCallf26e73d2016-03-11 04:30:43 +00004060 }
4061
Hal Finkelee90a222014-09-26 05:04:30 +00004062 case ABIArgInfo::Ignore:
4063 // If we are ignoring an argument that had a result, make sure to
4064 // construct the appropriate return value for our caller.
4065 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004066
Hal Finkelee90a222014-09-26 05:04:30 +00004067 case ABIArgInfo::Extend:
4068 case ABIArgInfo::Direct: {
4069 llvm::Type *RetIRTy = ConvertType(RetTy);
4070 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
4071 switch (getEvaluationKind(RetTy)) {
4072 case TEK_Complex: {
4073 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
4074 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
4075 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004076 }
Hal Finkelee90a222014-09-26 05:04:30 +00004077 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +00004078 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00004079 bool DestIsVolatile = ReturnValue.isVolatile();
4080
John McCall7f416cc2015-09-08 08:05:57 +00004081 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00004082 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
4083 DestIsVolatile = false;
4084 }
John McCall7f416cc2015-09-08 08:05:57 +00004085 BuildAggStore(*this, CI, DestPtr, DestIsVolatile);
Hal Finkelee90a222014-09-26 05:04:30 +00004086 return RValue::getAggregate(DestPtr);
4087 }
4088 case TEK_Scalar: {
4089 // If the argument doesn't match, perform a bitcast to coerce it. This
4090 // can happen due to trivial type mismatches.
4091 llvm::Value *V = CI;
4092 if (V->getType() != RetIRTy)
4093 V = Builder.CreateBitCast(V, RetIRTy);
4094 return RValue::get(V);
4095 }
4096 }
4097 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004098 }
Hal Finkelee90a222014-09-26 05:04:30 +00004099
John McCall7f416cc2015-09-08 08:05:57 +00004100 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00004101 bool DestIsVolatile = ReturnValue.isVolatile();
4102
John McCall7f416cc2015-09-08 08:05:57 +00004103 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00004104 DestPtr = CreateMemTemp(RetTy, "coerce");
4105 DestIsVolatile = false;
John McCall47fb9502013-03-07 21:37:08 +00004106 }
Hal Finkelee90a222014-09-26 05:04:30 +00004107
4108 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00004109 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
4110 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Hal Finkelee90a222014-09-26 05:04:30 +00004111
4112 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004113 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004114
Hal Finkelee90a222014-09-26 05:04:30 +00004115 case ABIArgInfo::Expand:
4116 llvm_unreachable("Invalid ABI kind for return argument");
Anders Carlsson17490832009-12-24 20:40:36 +00004117 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004118
Hal Finkelee90a222014-09-26 05:04:30 +00004119 llvm_unreachable("Unhandled ABIArgInfo::Kind");
4120 } ();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004121
Samuel Antao798f11c2015-11-23 22:04:44 +00004122 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
4123
Hal Finkelee90a222014-09-26 05:04:30 +00004124 if (Ret.isScalar() && TargetDecl) {
4125 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
4126 llvm::Value *OffsetValue = nullptr;
4127 if (const auto *Offset = AA->getOffset())
4128 OffsetValue = EmitScalarExpr(Offset);
4129
4130 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
4131 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
4132 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
4133 OffsetValue);
4134 }
Daniel Dunbar573884e2008-09-10 07:04:09 +00004135 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00004136
Hal Finkelee90a222014-09-26 05:04:30 +00004137 return Ret;
Daniel Dunbar613855c2008-09-09 23:27:19 +00004138}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00004139
4140/* VarArg handling */
4141
Charles Davisc7d5c942015-09-17 20:55:33 +00004142Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
4143 VAListAddr = VE->isMicrosoftABI()
4144 ? EmitMSVAListRef(VE->getSubExpr())
4145 : EmitVAListRef(VE->getSubExpr());
4146 QualType Ty = VE->getType();
4147 if (VE->isMicrosoftABI())
4148 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004149 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00004150}