blob: 428098da263c697835eacc3da4c22e78a4eadffd [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"
Nick Lewyckyd9bce502016-09-20 15:49:58 +000032#include "llvm/Analysis/ValueTracking.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000033#include "llvm/IR/Attributes.h"
Nikolay Haustov8c6538b2016-06-30 09:06:33 +000034#include "llvm/IR/CallingConv.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000035#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000036#include "llvm/IR/DataLayout.h"
37#include "llvm/IR/InlineAsm.h"
Saleem Abdulrasool94cfc602016-04-07 17:49:44 +000038#include "llvm/IR/Intrinsics.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000039#include "llvm/IR/IntrinsicInst.h"
Eli Friedmanf7456192011-06-15 22:09:18 +000040#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000041using namespace clang;
42using namespace CodeGen;
43
44/***/
45
Nikolay Haustov8c6538b2016-06-30 09:06:33 +000046unsigned CodeGenTypes::ClangCallConvToLLVMCallConv(CallingConv CC) {
John McCallab26cfa2010-02-05 21:31:56 +000047 switch (CC) {
48 default: return llvm::CallingConv::C;
49 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
50 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
Erich Keane757d3172016-11-02 18:29:35 +000051 case CC_X86RegCall: return llvm::CallingConv::X86_RegCall;
Douglas Gregora941dca2010-05-18 16:57:00 +000052 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Charles Davisb5a214e2013-08-30 04:39:01 +000053 case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64;
54 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
Anton Korobeynikov231e8752011-04-14 20:06:49 +000055 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
56 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Guy Benyeif0a014b2012-12-25 08:53:55 +000057 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Reid Klecknerd7857f02014-10-24 17:42:17 +000058 // TODO: Add support for __pascal to LLVM.
59 case CC_X86Pascal: return llvm::CallingConv::C;
60 // TODO: Add support for __vectorcall to LLVM.
Reid Kleckner80944df2014-10-31 22:00:51 +000061 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
Alexander Kornienko21de0ae2015-01-20 11:20:41 +000062 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +000063 case CC_OpenCLKernel: return CGM.getTargetCodeGenInfo().getOpenCLKernelCallingConv();
Roman Levenstein35aa5ce2016-03-16 18:00:46 +000064 case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
65 case CC_PreserveAll: return llvm::CallingConv::PreserveAll;
John McCall12f23522016-04-04 18:33:08 +000066 case CC_Swift: return llvm::CallingConv::Swift;
John McCallab26cfa2010-02-05 21:31:56 +000067 }
68}
69
John McCall8ee376f2010-02-24 07:14:12 +000070/// Derives the 'this' type for codegen purposes, i.e. ignoring method
71/// qualification.
72/// FIXME: address space qualification?
John McCall2da83a32010-02-26 00:48:12 +000073static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
74 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
75 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000076}
77
John McCall8ee376f2010-02-24 07:14:12 +000078/// Returns the canonical formal type of the given C++ method.
John McCall2da83a32010-02-26 00:48:12 +000079static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
80 return MD->getType()->getCanonicalTypeUnqualified()
81 .getAs<FunctionProtoType>();
John McCall8ee376f2010-02-24 07:14:12 +000082}
83
84/// Returns the "extra-canonicalized" return type, which discards
85/// qualifiers on the return type. Codegen doesn't care about them,
86/// and it makes ABI code a little easier to be able to assume that
87/// all parameter and return types are top-level unqualified.
John McCall2da83a32010-02-26 00:48:12 +000088static CanQualType GetReturnType(QualType RetTy) {
89 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall8ee376f2010-02-24 07:14:12 +000090}
91
John McCall8dda7b22012-07-07 06:41:13 +000092/// Arrange the argument and result information for a value of the given
93/// unprototyped freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +000094const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +000095CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCalla729c622012-02-17 03:33:10 +000096 // When translating an unprototyped function type, always use a
97 // variadic type.
Alp Toker314cc812014-01-25 16:55:45 +000098 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
Peter Collingbournef7706832014-12-12 23:41:25 +000099 /*instanceMethod=*/false,
100 /*chainCall=*/false, None,
John McCallc56a8b32016-03-11 04:30:31 +0000101 FTNP->getExtInfo(), {}, RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +0000102}
103
Simon Pilgrim27cc0542017-02-15 15:12:06 +0000104/// Adds the formal parameters in FPT to the given prefix. If any parameter in
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000105/// FPT has pass_object_size attrs, then we'll add parameters for those, too.
106static void appendParameterTypes(const CodeGenTypes &CGT,
107 SmallVectorImpl<CanQualType> &prefix,
John McCallc56a8b32016-03-11 04:30:31 +0000108 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
109 CanQual<FunctionProtoType> FPT,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000110 const FunctionDecl *FD) {
John McCallc56a8b32016-03-11 04:30:31 +0000111 // Fill out paramInfos.
112 if (FPT->hasExtParameterInfos() || !paramInfos.empty()) {
113 assert(paramInfos.size() <= prefix.size());
114 auto protoParamInfos = FPT->getExtParameterInfos();
115 paramInfos.reserve(prefix.size() + protoParamInfos.size());
116 paramInfos.resize(prefix.size());
John McCall12f23522016-04-04 18:33:08 +0000117 paramInfos.append(protoParamInfos.begin(), protoParamInfos.end());
John McCallc56a8b32016-03-11 04:30:31 +0000118 }
119
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000120 // Fast path: unknown target.
121 if (FD == nullptr) {
122 prefix.append(FPT->param_type_begin(), FPT->param_type_end());
123 return;
124 }
125
126 // In the vast majority cases, we'll have precisely FPT->getNumParams()
127 // parameters; the only thing that can change this is the presence of
128 // pass_object_size. So, we preallocate for the common case.
129 prefix.reserve(prefix.size() + FPT->getNumParams());
130
131 assert(FD->getNumParams() == FPT->getNumParams());
132 for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
133 prefix.push_back(FPT->getParamType(I));
134 if (FD->getParamDecl(I)->hasAttr<PassObjectSizeAttr>())
135 prefix.push_back(CGT.getContext().getSizeType());
136 }
137}
138
John McCall8dda7b22012-07-07 06:41:13 +0000139/// Arrange the LLVM function layout for a value of the given function
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000140/// type, on top of any implicit parameters already stored.
141static const CGFunctionInfo &
Peter Collingbournef7706832014-12-12 23:41:25 +0000142arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000143 SmallVectorImpl<CanQualType> &prefix,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000144 CanQual<FunctionProtoType> FTP,
145 const FunctionDecl *FD) {
John McCallc56a8b32016-03-11 04:30:31 +0000146 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
George Burgess IV419996c2016-06-16 23:06:04 +0000147 RequiredArgs Required =
148 RequiredArgs::forPrototypePlus(FTP, prefix.size(), FD);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000149 // FIXME: Kill copy.
John McCallc56a8b32016-03-11 04:30:31 +0000150 appendParameterTypes(CGT, prefix, paramInfos, FTP, FD);
Alp Toker314cc812014-01-25 16:55:45 +0000151 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
John McCallc56a8b32016-03-11 04:30:31 +0000152
Peter Collingbournef7706832014-12-12 23:41:25 +0000153 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
154 /*chainCall=*/false, prefix,
John McCallc56a8b32016-03-11 04:30:31 +0000155 FTP->getExtInfo(), paramInfos,
George Burgess IV419996c2016-06-16 23:06:04 +0000156 Required);
John McCall8ee376f2010-02-24 07:14:12 +0000157}
158
John McCalla729c622012-02-17 03:33:10 +0000159/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000160/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000161const CGFunctionInfo &
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000162CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP,
163 const FunctionDecl *FD) {
John McCalla729c622012-02-17 03:33:10 +0000164 SmallVector<CanQualType, 16> argTypes;
Peter Collingbournef7706832014-12-12 23:41:25 +0000165 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000166 FTP, FD);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000167}
168
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000169static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000170 // Set the appropriate calling convention for the Function.
171 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000172 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000173
174 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000175 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000176
Erich Keane757d3172016-11-02 18:29:35 +0000177 if (D->hasAttr<RegCallAttr>())
178 return CC_X86RegCall;
179
Douglas Gregora941dca2010-05-18 16:57:00 +0000180 if (D->hasAttr<ThisCallAttr>())
181 return CC_X86ThisCall;
182
Reid Klecknerd7857f02014-10-24 17:42:17 +0000183 if (D->hasAttr<VectorCallAttr>())
184 return CC_X86VectorCall;
185
Dawn Perchik335e16b2010-09-03 01:29:35 +0000186 if (D->hasAttr<PascalAttr>())
187 return CC_X86Pascal;
188
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000189 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
190 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
191
Guy Benyeif0a014b2012-12-25 08:53:55 +0000192 if (D->hasAttr<IntelOclBiccAttr>())
193 return CC_IntelOclBicc;
194
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000195 if (D->hasAttr<MSABIAttr>())
196 return IsWindows ? CC_C : CC_X86_64Win64;
197
198 if (D->hasAttr<SysVABIAttr>())
199 return IsWindows ? CC_X86_64SysV : CC_C;
200
Roman Levenstein35aa5ce2016-03-16 18:00:46 +0000201 if (D->hasAttr<PreserveMostAttr>())
202 return CC_PreserveMost;
203
204 if (D->hasAttr<PreserveAllAttr>())
205 return CC_PreserveAll;
206
John McCallab26cfa2010-02-05 21:31:56 +0000207 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000208}
209
John McCalla729c622012-02-17 03:33:10 +0000210/// Arrange the argument and result information for a call to an
211/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000212/// (Zero value of RD means we don't have any meaningful "this" argument type,
213/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000214/// The member function must be an ordinary function, i.e. not a
215/// constructor or destructor.
216const CGFunctionInfo &
217CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000218 const FunctionProtoType *FTP,
219 const CXXMethodDecl *MD) {
John McCalla729c622012-02-17 03:33:10 +0000220 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000221
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000222 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000223 if (RD)
224 argTypes.push_back(GetThisType(Context, RD));
225 else
226 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000227
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000228 return ::arrangeLLVMFunctionInfo(
229 *this, true, argTypes,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000230 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>(), MD);
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000231}
232
John McCalla729c622012-02-17 03:33:10 +0000233/// Arrange the argument and result information for a declaration or
234/// definition of the given C++ non-static member function. The
235/// member function must be an ordinary function, i.e. not a
236/// constructor or destructor.
237const CGFunctionInfo &
238CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000239 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000240 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
241
John McCalla729c622012-02-17 03:33:10 +0000242 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000243
John McCalla729c622012-02-17 03:33:10 +0000244 if (MD->isInstance()) {
245 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000246 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000247 return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
John McCalla729c622012-02-17 03:33:10 +0000248 }
249
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000250 return arrangeFreeFunctionType(prototype, MD);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000251}
252
Richard Smith5179eb72016-06-28 19:03:57 +0000253bool CodeGenTypes::inheritingCtorHasParams(
254 const InheritedConstructor &Inherited, CXXCtorType Type) {
255 // Parameters are unnecessary if we're constructing a base class subobject
256 // and the inherited constructor lives in a virtual base.
257 return Type == Ctor_Complete ||
258 !Inherited.getShadowDecl()->constructsVirtualBase() ||
259 !Target.getCXXABI().hasConstructorVariants();
260 }
261
John McCalla729c622012-02-17 03:33:10 +0000262const CGFunctionInfo &
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000263CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
264 StructorType Type) {
265
John McCalla729c622012-02-17 03:33:10 +0000266 SmallVector<CanQualType, 16> argTypes;
John McCallc56a8b32016-03-11 04:30:31 +0000267 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000268 argTypes.push_back(GetThisType(Context, MD->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000269
Richard Smith5179eb72016-06-28 19:03:57 +0000270 bool PassParams = true;
271
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000272 GlobalDecl GD;
273 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
274 GD = GlobalDecl(CD, toCXXCtorType(Type));
Richard Smith5179eb72016-06-28 19:03:57 +0000275
276 // A base class inheriting constructor doesn't get forwarded arguments
277 // needed to construct a virtual base (or base class thereof).
278 if (auto Inherited = CD->getInheritedConstructor())
279 PassParams = inheritingCtorHasParams(Inherited, toCXXCtorType(Type));
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000280 } else {
281 auto *DD = dyn_cast<CXXDestructorDecl>(MD);
282 GD = GlobalDecl(DD, toCXXDtorType(Type));
283 }
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000284
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000285 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
John McCall5d865c322010-08-31 07:33:07 +0000286
287 // Add the formal parameters.
Richard Smith5179eb72016-06-28 19:03:57 +0000288 if (PassParams)
289 appendParameterTypes(*this, argTypes, paramInfos, FTP, MD);
John McCall5d865c322010-08-31 07:33:07 +0000290
George Burgess IV75b34a92017-02-22 22:38:25 +0000291 CGCXXABI::AddedStructorArgs AddedArgs =
292 TheCXXABI.buildStructorSignature(MD, Type, argTypes);
293 if (!paramInfos.empty()) {
294 // Note: prefix implies after the first param.
295 if (AddedArgs.Prefix)
296 paramInfos.insert(paramInfos.begin() + 1, AddedArgs.Prefix,
297 FunctionProtoType::ExtParameterInfo{});
298 if (AddedArgs.Suffix)
299 paramInfos.append(AddedArgs.Suffix,
300 FunctionProtoType::ExtParameterInfo{});
301 }
Reid Kleckner89077a12013-12-17 19:46:40 +0000302
303 RequiredArgs required =
Richard Smith5179eb72016-06-28 19:03:57 +0000304 (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size())
305 : RequiredArgs::All);
Reid Kleckner89077a12013-12-17 19:46:40 +0000306
John McCall8dda7b22012-07-07 06:41:13 +0000307 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000308 CanQualType resultType = TheCXXABI.HasThisReturn(GD)
309 ? argTypes.front()
310 : TheCXXABI.hasMostDerivedReturn(GD)
311 ? CGM.getContext().VoidPtrTy
312 : Context.VoidTy;
Peter Collingbournef7706832014-12-12 23:41:25 +0000313 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
314 /*chainCall=*/false, argTypes, extInfo,
John McCallc56a8b32016-03-11 04:30:31 +0000315 paramInfos, required);
316}
317
318static SmallVector<CanQualType, 16>
319getArgTypesForCall(ASTContext &ctx, const CallArgList &args) {
320 SmallVector<CanQualType, 16> argTypes;
321 for (auto &arg : args)
322 argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
323 return argTypes;
324}
325
326static SmallVector<CanQualType, 16>
327getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) {
328 SmallVector<CanQualType, 16> argTypes;
329 for (auto &arg : args)
330 argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
331 return argTypes;
332}
333
334static void addExtParameterInfosForCall(
335 llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
336 const FunctionProtoType *proto,
337 unsigned prefixArgs,
338 unsigned totalArgs) {
339 assert(proto->hasExtParameterInfos());
340 assert(paramInfos.size() <= prefixArgs);
341 assert(proto->getNumParams() + prefixArgs <= totalArgs);
342
343 // Add default infos for any prefix args that don't already have infos.
344 paramInfos.resize(prefixArgs);
345
346 // Add infos for the prototype.
347 auto protoInfos = proto->getExtParameterInfos();
348 paramInfos.append(protoInfos.begin(), protoInfos.end());
349
350 // Add default infos for the variadic arguments.
351 paramInfos.resize(totalArgs);
352}
353
354static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16>
355getExtParameterInfosForCall(const FunctionProtoType *proto,
356 unsigned prefixArgs, unsigned totalArgs) {
357 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result;
358 if (proto->hasExtParameterInfos()) {
359 addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
360 }
361 return result;
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000362}
363
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000364/// Arrange a call to a C++ method, passing the given arguments.
George Burgess IVd0a9e802017-02-23 22:07:35 +0000365///
366/// ExtraPrefixArgs is the number of ABI-specific args passed after the `this`
367/// parameter.
368/// ExtraSuffixArgs is the number of ABI-specific args passed at the end of
369/// args.
370/// PassProtoArgs indicates whether `args` has args for the parameters in the
371/// given CXXConstructorDecl.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000372const CGFunctionInfo &
373CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
374 const CXXConstructorDecl *D,
375 CXXCtorType CtorKind,
George Burgess IVd0a9e802017-02-23 22:07:35 +0000376 unsigned ExtraPrefixArgs,
377 unsigned ExtraSuffixArgs,
378 bool PassProtoArgs) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000379 // FIXME: Kill copy.
380 SmallVector<CanQualType, 16> ArgTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000381 for (const auto &Arg : args)
382 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000383
George Burgess IVd0a9e802017-02-23 22:07:35 +0000384 // +1 for implicit this, which should always be args[0].
385 unsigned TotalPrefixArgs = 1 + ExtraPrefixArgs;
386
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000387 CanQual<FunctionProtoType> FPT = GetFormalType(D);
George Burgess IVd0a9e802017-02-23 22:07:35 +0000388 RequiredArgs Required =
389 RequiredArgs::forPrototypePlus(FPT, TotalPrefixArgs + ExtraSuffixArgs, D);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000390 GlobalDecl GD(D, CtorKind);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000391 CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
392 ? ArgTypes.front()
393 : TheCXXABI.hasMostDerivedReturn(GD)
394 ? CGM.getContext().VoidPtrTy
395 : Context.VoidTy;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000396
397 FunctionType::ExtInfo Info = FPT->getExtInfo();
George Burgess IVd0a9e802017-02-23 22:07:35 +0000398 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> ParamInfos;
399 // If the prototype args are elided, we should only have ABI-specific args,
400 // which never have param info.
401 if (PassProtoArgs && FPT->hasExtParameterInfos()) {
402 // ABI-specific suffix arguments are treated the same as variadic arguments.
403 addExtParameterInfosForCall(ParamInfos, FPT.getTypePtr(), TotalPrefixArgs,
404 ArgTypes.size());
405 }
Peter Collingbournef7706832014-12-12 23:41:25 +0000406 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
407 /*chainCall=*/false, ArgTypes, Info,
John McCallc56a8b32016-03-11 04:30:31 +0000408 ParamInfos, Required);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000409}
410
John McCalla729c622012-02-17 03:33:10 +0000411/// Arrange the argument and result information for the declaration or
412/// definition of the given function.
413const CGFunctionInfo &
414CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000415 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000416 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000417 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000418
John McCall2da83a32010-02-26 00:48:12 +0000419 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000420
John McCall2da83a32010-02-26 00:48:12 +0000421 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000422
423 // When declaring a function without a prototype, always use a
424 // non-variadic type.
George Burgess IV35cfca22017-01-06 19:10:48 +0000425 if (CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>()) {
Peter Collingbournef7706832014-12-12 23:41:25 +0000426 return arrangeLLVMFunctionInfo(
427 noProto->getReturnType(), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000428 /*chainCall=*/false, None, noProto->getExtInfo(), {},RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000429 }
430
George Burgess IV35cfca22017-01-06 19:10:48 +0000431 return arrangeFreeFunctionType(FTy.castAs<FunctionProtoType>(), FD);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000432}
433
John McCalla729c622012-02-17 03:33:10 +0000434/// Arrange the argument and result information for the declaration or
435/// definition of an Objective-C method.
436const CGFunctionInfo &
437CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
438 // It happens that this is the same as a call with no optional
439 // arguments, except also using the formal 'self' type.
440 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
441}
442
443/// Arrange the argument and result information for the function type
444/// through which to perform a send to the given Objective-C method,
445/// using the given receiver type. The receiver type is not always
446/// the 'self' type of the method or even an Objective-C pointer type.
447/// This is *not* the right method for actually performing such a
448/// message send, due to the possibility of optional arguments.
449const CGFunctionInfo &
450CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
451 QualType receiverType) {
452 SmallVector<CanQualType, 16> argTys;
453 argTys.push_back(Context.getCanonicalParamType(receiverType));
454 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000455 // FIXME: Kill copy?
David Majnemer59f77922016-06-24 04:05:48 +0000456 for (const auto *I : MD->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000457 argTys.push_back(Context.getCanonicalParamType(I->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000458 }
John McCall31168b02011-06-15 23:02:42 +0000459
460 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000461 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
462 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000463
David Blaikiebbafb8a2012-03-11 07:00:24 +0000464 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000465 MD->hasAttr<NSReturnsRetainedAttr>())
466 einfo = einfo.withProducesResult(true);
467
John McCalla729c622012-02-17 03:33:10 +0000468 RequiredArgs required =
469 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
470
Peter Collingbournef7706832014-12-12 23:41:25 +0000471 return arrangeLLVMFunctionInfo(
472 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000473 /*chainCall=*/false, argTys, einfo, {}, required);
474}
475
476const CGFunctionInfo &
477CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType,
478 const CallArgList &args) {
479 auto argTypes = getArgTypesForCall(Context, args);
480 FunctionType::ExtInfo einfo;
481
482 return arrangeLLVMFunctionInfo(
483 GetReturnType(returnType), /*instanceMethod=*/false,
484 /*chainCall=*/false, argTypes, einfo, {}, RequiredArgs::All);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000485}
486
John McCalla729c622012-02-17 03:33:10 +0000487const CGFunctionInfo &
488CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000489 // FIXME: Do we need to handle ObjCMethodDecl?
490 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000491
Anders Carlsson6710c532010-02-06 02:44:09 +0000492 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000493 return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
Anders Carlsson6710c532010-02-06 02:44:09 +0000494
495 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000496 return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000497
John McCalla729c622012-02-17 03:33:10 +0000498 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000499}
500
Reid Klecknerc3473512014-08-29 21:43:29 +0000501/// Arrange a thunk that takes 'this' as the first parameter followed by
502/// varargs. Return a void pointer, regardless of the actual return type.
503/// The body of the thunk will end in a musttail call to a function of the
504/// correct type, and the caller will bitcast the function to the correct
505/// prototype.
506const CGFunctionInfo &
507CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) {
508 assert(MD->isVirtual() && "only virtual memptrs have thunks");
509 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
510 CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
Peter Collingbournef7706832014-12-12 23:41:25 +0000511 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
512 /*chainCall=*/false, ArgTys,
John McCallc56a8b32016-03-11 04:30:31 +0000513 FTP->getExtInfo(), {}, RequiredArgs(1));
Reid Klecknerc3473512014-08-29 21:43:29 +0000514}
515
David Majnemerdfa6d202015-03-11 18:36:39 +0000516const CGFunctionInfo &
David Majnemer37fd66e2015-03-13 22:36:55 +0000517CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
518 CXXCtorType CT) {
519 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
520
David Majnemerdfa6d202015-03-11 18:36:39 +0000521 CanQual<FunctionProtoType> FTP = GetFormalType(CD);
522 SmallVector<CanQualType, 2> ArgTys;
523 const CXXRecordDecl *RD = CD->getParent();
524 ArgTys.push_back(GetThisType(Context, RD));
David Majnemer37fd66e2015-03-13 22:36:55 +0000525 if (CT == Ctor_CopyingClosure)
526 ArgTys.push_back(*FTP->param_type_begin());
David Majnemerdfa6d202015-03-11 18:36:39 +0000527 if (RD->getNumVBases() > 0)
528 ArgTys.push_back(Context.IntTy);
529 CallingConv CC = Context.getDefaultCallingConvention(
530 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
531 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
532 /*chainCall=*/false, ArgTys,
John McCallc56a8b32016-03-11 04:30:31 +0000533 FunctionType::ExtInfo(CC), {},
534 RequiredArgs::All);
David Majnemerdfa6d202015-03-11 18:36:39 +0000535}
536
John McCallc818bbb2012-12-07 07:03:17 +0000537/// Arrange a call as unto a free function, except possibly with an
538/// additional number of formal parameters considered required.
539static const CGFunctionInfo &
540arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000541 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000542 const CallArgList &args,
543 const FunctionType *fnType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000544 unsigned numExtraRequiredArgs,
545 bool chainCall) {
John McCallc818bbb2012-12-07 07:03:17 +0000546 assert(args.size() >= numExtraRequiredArgs);
547
John McCallc56a8b32016-03-11 04:30:31 +0000548 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
549
John McCallc818bbb2012-12-07 07:03:17 +0000550 // In most cases, there are no optional arguments.
551 RequiredArgs required = RequiredArgs::All;
552
553 // If we have a variadic prototype, the required arguments are the
554 // extra prefix plus the arguments in the prototype.
555 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
556 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000557 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000558
John McCallc56a8b32016-03-11 04:30:31 +0000559 if (proto->hasExtParameterInfos())
560 addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
561 args.size());
562
John McCallc818bbb2012-12-07 07:03:17 +0000563 // If we don't have a prototype at all, but we're supposed to
564 // explicitly use the variadic convention for unprototyped calls,
565 // treat all of the arguments as required but preserve the nominal
566 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000567 } else if (CGM.getTargetCodeGenInfo()
568 .isNoProtoCallVariadic(args,
569 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000570 required = RequiredArgs(args.size());
571 }
572
Peter Collingbournef7706832014-12-12 23:41:25 +0000573 // FIXME: Kill copy.
574 SmallVector<CanQualType, 16> argTypes;
575 for (const auto &arg : args)
576 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
577 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
578 /*instanceMethod=*/false, chainCall,
John McCallc56a8b32016-03-11 04:30:31 +0000579 argTypes, fnType->getExtInfo(), paramInfos,
580 required);
John McCallc818bbb2012-12-07 07:03:17 +0000581}
582
John McCalla729c622012-02-17 03:33:10 +0000583/// Figure out the rules for calling a function with the given formal
584/// type using the given arguments. The arguments are necessary
585/// because the function might be unprototyped, in which case it's
586/// target-dependent in crazy ways.
587const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000588CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
Peter Collingbournef7706832014-12-12 23:41:25 +0000589 const FunctionType *fnType,
590 bool chainCall) {
591 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
592 chainCall ? 1 : 0, chainCall);
John McCallc818bbb2012-12-07 07:03:17 +0000593}
John McCalla729c622012-02-17 03:33:10 +0000594
John McCallc56a8b32016-03-11 04:30:31 +0000595/// A block function is essentially a free function with an
John McCallc818bbb2012-12-07 07:03:17 +0000596/// extra implicit argument.
597const CGFunctionInfo &
598CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
599 const FunctionType *fnType) {
Peter Collingbournef7706832014-12-12 23:41:25 +0000600 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
601 /*chainCall=*/false);
John McCalla729c622012-02-17 03:33:10 +0000602}
603
604const CGFunctionInfo &
John McCallc56a8b32016-03-11 04:30:31 +0000605CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto,
606 const FunctionArgList &params) {
607 auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
608 auto argTypes = getArgTypesForDeclaration(Context, params);
609
George Burgess IV419996c2016-06-16 23:06:04 +0000610 return arrangeLLVMFunctionInfo(
611 GetReturnType(proto->getReturnType()),
612 /*instanceMethod*/ false, /*chainCall*/ false, argTypes,
613 proto->getExtInfo(), paramInfos,
614 RequiredArgs::forPrototypePlus(proto, 1, nullptr));
John McCallc56a8b32016-03-11 04:30:31 +0000615}
616
617const CGFunctionInfo &
618CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType,
619 const CallArgList &args) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000620 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000621 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000622 for (const auto &Arg : args)
623 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Peter Collingbournef7706832014-12-12 23:41:25 +0000624 return arrangeLLVMFunctionInfo(
625 GetReturnType(resultType), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000626 /*chainCall=*/false, argTypes, FunctionType::ExtInfo(),
627 /*paramInfos=*/ {}, RequiredArgs::All);
John McCall8dda7b22012-07-07 06:41:13 +0000628}
629
John McCallc56a8b32016-03-11 04:30:31 +0000630const CGFunctionInfo &
631CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType,
632 const FunctionArgList &args) {
633 auto argTypes = getArgTypesForDeclaration(Context, args);
634
635 return arrangeLLVMFunctionInfo(
636 GetReturnType(resultType), /*instanceMethod=*/false, /*chainCall=*/false,
637 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
638}
639
640const CGFunctionInfo &
641CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType,
642 ArrayRef<CanQualType> argTypes) {
643 return arrangeLLVMFunctionInfo(
644 resultType, /*instanceMethod=*/false, /*chainCall=*/false,
645 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
646}
647
John McCall8dda7b22012-07-07 06:41:13 +0000648/// Arrange a call to a C++ method, passing the given arguments.
George Burgess IVd0a9e802017-02-23 22:07:35 +0000649///
650/// numPrefixArgs is the number of ABI-specific prefix arguments we have. It
651/// does not count `this`.
John McCall8dda7b22012-07-07 06:41:13 +0000652const CGFunctionInfo &
653CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
John McCallc56a8b32016-03-11 04:30:31 +0000654 const FunctionProtoType *proto,
George Burgess IVd0a9e802017-02-23 22:07:35 +0000655 RequiredArgs required,
656 unsigned numPrefixArgs) {
657 assert(numPrefixArgs + 1 <= args.size() &&
658 "Emitting a call with less args than the required prefix?");
659 // Add one to account for `this`. It's a bit awkward here, but we don't count
660 // `this` in similar places elsewhere.
John McCallc56a8b32016-03-11 04:30:31 +0000661 auto paramInfos =
George Burgess IVd0a9e802017-02-23 22:07:35 +0000662 getExtParameterInfosForCall(proto, numPrefixArgs + 1, args.size());
John McCallc56a8b32016-03-11 04:30:31 +0000663
John McCall8dda7b22012-07-07 06:41:13 +0000664 // FIXME: Kill copy.
John McCallc56a8b32016-03-11 04:30:31 +0000665 auto argTypes = getArgTypesForCall(Context, args);
John McCall8dda7b22012-07-07 06:41:13 +0000666
John McCallc56a8b32016-03-11 04:30:31 +0000667 FunctionType::ExtInfo info = proto->getExtInfo();
Peter Collingbournef7706832014-12-12 23:41:25 +0000668 return arrangeLLVMFunctionInfo(
John McCallc56a8b32016-03-11 04:30:31 +0000669 GetReturnType(proto->getReturnType()), /*instanceMethod=*/true,
670 /*chainCall=*/false, argTypes, info, paramInfos, required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000671}
672
John McCalla729c622012-02-17 03:33:10 +0000673const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Peter Collingbournef7706832014-12-12 23:41:25 +0000674 return arrangeLLVMFunctionInfo(
675 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000676 None, FunctionType::ExtInfo(), {}, RequiredArgs::All);
677}
678
679const CGFunctionInfo &
680CodeGenTypes::arrangeCall(const CGFunctionInfo &signature,
681 const CallArgList &args) {
682 assert(signature.arg_size() <= args.size());
683 if (signature.arg_size() == args.size())
684 return signature;
685
686 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
687 auto sigParamInfos = signature.getExtParameterInfos();
688 if (!sigParamInfos.empty()) {
689 paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
690 paramInfos.resize(args.size());
691 }
692
693 auto argTypes = getArgTypesForCall(Context, args);
694
695 assert(signature.getRequiredArgs().allowsOptionalArgs());
696 return arrangeLLVMFunctionInfo(signature.getReturnType(),
697 signature.isInstanceMethod(),
698 signature.isChainCall(),
699 argTypes,
700 signature.getExtInfo(),
701 paramInfos,
702 signature.getRequiredArgs());
John McCalla738c252011-03-09 04:27:21 +0000703}
704
John McCalla729c622012-02-17 03:33:10 +0000705/// Arrange the argument and result information for an abstract value
706/// of a given function type. This is the method which all of the
707/// above functions ultimately defer to.
708const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000709CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000710 bool instanceMethod,
711 bool chainCall,
John McCall8dda7b22012-07-07 06:41:13 +0000712 ArrayRef<CanQualType> argTypes,
713 FunctionType::ExtInfo info,
John McCallc56a8b32016-03-11 04:30:31 +0000714 ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
John McCall8dda7b22012-07-07 06:41:13 +0000715 RequiredArgs required) {
Saleem Abdulrasool32d1a962014-11-25 03:49:50 +0000716 assert(std::all_of(argTypes.begin(), argTypes.end(),
717 std::mem_fun_ref(&CanQualType::isCanonicalAsParam)));
John McCall2da83a32010-02-26 00:48:12 +0000718
Daniel Dunbare0be8292009-02-03 00:07:12 +0000719 // Lookup or create unique function info.
720 llvm::FoldingSetNodeID ID;
John McCallc56a8b32016-03-11 04:30:31 +0000721 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos,
722 required, resultType, argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000723
Craig Topper8a13c412014-05-21 05:09:00 +0000724 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000725 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000726 if (FI)
727 return *FI;
728
John McCallc56a8b32016-03-11 04:30:31 +0000729 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
730
John McCalla729c622012-02-17 03:33:10 +0000731 // Construct the function info. We co-allocate the ArgInfos.
Peter Collingbournef7706832014-12-12 23:41:25 +0000732 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
John McCallc56a8b32016-03-11 04:30:31 +0000733 paramInfos, resultType, argTypes, required);
John McCalla729c622012-02-17 03:33:10 +0000734 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000735
David Blaikie82e95a32014-11-19 07:49:47 +0000736 bool inserted = FunctionsBeingProcessed.insert(FI).second;
737 (void)inserted;
John McCalla729c622012-02-17 03:33:10 +0000738 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000739
Daniel Dunbar313321e2009-02-03 05:31:23 +0000740 // Compute ABI information.
John McCall12f23522016-04-04 18:33:08 +0000741 if (info.getCC() != CC_Swift) {
742 getABIInfo().computeInfo(*FI);
743 } else {
744 swiftcall::computeABIInfo(CGM, *FI);
745 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000746
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000747 // Loop over all of the computed argument and return value info. If any of
748 // them are direct or extend without a specified coerce type, specify the
749 // default now.
John McCalla729c622012-02-17 03:33:10 +0000750 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000751 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000752 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000753
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000754 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000755 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000756 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000757
John McCalla729c622012-02-17 03:33:10 +0000758 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
759 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000760
Daniel Dunbare0be8292009-02-03 00:07:12 +0000761 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000762}
763
John McCalla729c622012-02-17 03:33:10 +0000764CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Peter Collingbournef7706832014-12-12 23:41:25 +0000765 bool instanceMethod,
766 bool chainCall,
John McCalla729c622012-02-17 03:33:10 +0000767 const FunctionType::ExtInfo &info,
John McCallc56a8b32016-03-11 04:30:31 +0000768 ArrayRef<ExtParameterInfo> paramInfos,
John McCalla729c622012-02-17 03:33:10 +0000769 CanQualType resultType,
770 ArrayRef<CanQualType> argTypes,
771 RequiredArgs required) {
John McCallc56a8b32016-03-11 04:30:31 +0000772 assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
773
774 void *buffer =
775 operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
776 argTypes.size() + 1, paramInfos.size()));
777
John McCalla729c622012-02-17 03:33:10 +0000778 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
779 FI->CallingConvention = llvmCC;
780 FI->EffectiveCallingConvention = llvmCC;
781 FI->ASTCallingConvention = info.getCC();
Peter Collingbournef7706832014-12-12 23:41:25 +0000782 FI->InstanceMethod = instanceMethod;
783 FI->ChainCall = chainCall;
John McCalla729c622012-02-17 03:33:10 +0000784 FI->NoReturn = info.getNoReturn();
785 FI->ReturnsRetained = info.getProducesResult();
786 FI->Required = required;
787 FI->HasRegParm = info.getHasRegParm();
788 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000789 FI->ArgStruct = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +0000790 FI->ArgStructAlign = 0;
John McCalla729c622012-02-17 03:33:10 +0000791 FI->NumArgs = argTypes.size();
John McCallc56a8b32016-03-11 04:30:31 +0000792 FI->HasExtParameterInfos = !paramInfos.empty();
John McCalla729c622012-02-17 03:33:10 +0000793 FI->getArgsBuffer()[0].type = resultType;
794 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
795 FI->getArgsBuffer()[i + 1].type = argTypes[i];
John McCallc56a8b32016-03-11 04:30:31 +0000796 for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
797 FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
John McCalla729c622012-02-17 03:33:10 +0000798 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000799}
800
801/***/
802
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000803namespace {
804// ABIArgInfo::Expand implementation.
805
806// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
807struct TypeExpansion {
808 enum TypeExpansionKind {
809 // Elements of constant arrays are expanded recursively.
810 TEK_ConstantArray,
811 // Record fields are expanded recursively (but if record is a union, only
812 // the field with the largest size is expanded).
813 TEK_Record,
814 // For complex types, real and imaginary parts are expanded recursively.
815 TEK_Complex,
816 // All other types are not expandable.
817 TEK_None
818 };
819
820 const TypeExpansionKind Kind;
821
822 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000823 virtual ~TypeExpansion() {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000824};
825
826struct ConstantArrayExpansion : TypeExpansion {
827 QualType EltTy;
828 uint64_t NumElts;
829
830 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
831 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
832 static bool classof(const TypeExpansion *TE) {
833 return TE->Kind == TEK_ConstantArray;
834 }
835};
836
837struct RecordExpansion : TypeExpansion {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000838 SmallVector<const CXXBaseSpecifier *, 1> Bases;
839
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000840 SmallVector<const FieldDecl *, 1> Fields;
841
Reid Klecknere9f6a712014-10-31 17:10:41 +0000842 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
843 SmallVector<const FieldDecl *, 1> &&Fields)
Benjamin Kramer0bb97742016-02-13 16:00:13 +0000844 : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
845 Fields(std::move(Fields)) {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000846 static bool classof(const TypeExpansion *TE) {
847 return TE->Kind == TEK_Record;
848 }
849};
850
851struct ComplexExpansion : TypeExpansion {
852 QualType EltTy;
853
854 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
855 static bool classof(const TypeExpansion *TE) {
856 return TE->Kind == TEK_Complex;
857 }
858};
859
860struct NoExpansion : TypeExpansion {
861 NoExpansion() : TypeExpansion(TEK_None) {}
862 static bool classof(const TypeExpansion *TE) {
863 return TE->Kind == TEK_None;
864 }
865};
866} // namespace
867
868static std::unique_ptr<TypeExpansion>
869getTypeExpansion(QualType Ty, const ASTContext &Context) {
870 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
871 return llvm::make_unique<ConstantArrayExpansion>(
872 AT->getElementType(), AT->getSize().getZExtValue());
873 }
874 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000875 SmallVector<const CXXBaseSpecifier *, 1> Bases;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000876 SmallVector<const FieldDecl *, 1> Fields;
Bob Wilsone826a2a2011-08-03 05:58:22 +0000877 const RecordDecl *RD = RT->getDecl();
878 assert(!RD->hasFlexibleArrayMember() &&
879 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000880 if (RD->isUnion()) {
881 // Unions can be here only in degenerative cases - all the fields are same
882 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000883 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000884 CharUnits UnionSize = CharUnits::Zero();
885
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000886 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000887 // Skip zero length bitfields.
888 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
889 continue;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000890 assert(!FD->isBitField() &&
891 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000892 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000893 if (UnionSize < FieldSize) {
894 UnionSize = FieldSize;
895 LargestFD = FD;
896 }
897 }
898 if (LargestFD)
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000899 Fields.push_back(LargestFD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000900 } else {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000901 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
902 assert(!CXXRD->isDynamicClass() &&
903 "cannot expand vtable pointers in dynamic classes");
904 for (const CXXBaseSpecifier &BS : CXXRD->bases())
905 Bases.push_back(&BS);
906 }
907
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000908 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000909 // Skip zero length bitfields.
910 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
911 continue;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000912 assert(!FD->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000913 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000914 Fields.push_back(FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000915 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000916 }
Reid Klecknere9f6a712014-10-31 17:10:41 +0000917 return llvm::make_unique<RecordExpansion>(std::move(Bases),
918 std::move(Fields));
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000919 }
920 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
921 return llvm::make_unique<ComplexExpansion>(CT->getElementType());
922 }
923 return llvm::make_unique<NoExpansion>();
924}
925
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000926static int getExpansionSize(QualType Ty, const ASTContext &Context) {
927 auto Exp = getTypeExpansion(Ty, Context);
928 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
929 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
930 }
931 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
932 int Res = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +0000933 for (auto BS : RExp->Bases)
934 Res += getExpansionSize(BS->getType(), Context);
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000935 for (auto FD : RExp->Fields)
936 Res += getExpansionSize(FD->getType(), Context);
937 return Res;
938 }
939 if (isa<ComplexExpansion>(Exp.get()))
940 return 2;
941 assert(isa<NoExpansion>(Exp.get()));
942 return 1;
943}
944
Alexey Samsonov153004f2014-09-29 22:08:00 +0000945void
946CodeGenTypes::getExpandedTypes(QualType Ty,
947 SmallVectorImpl<llvm::Type *>::iterator &TI) {
948 auto Exp = getTypeExpansion(Ty, Context);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000949 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
950 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
Alexey Samsonov153004f2014-09-29 22:08:00 +0000951 getExpandedTypes(CAExp->EltTy, TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000952 }
953 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000954 for (auto BS : RExp->Bases)
955 getExpandedTypes(BS->getType(), TI);
956 for (auto FD : RExp->Fields)
Alexey Samsonov153004f2014-09-29 22:08:00 +0000957 getExpandedTypes(FD->getType(), TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000958 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
959 llvm::Type *EltTy = ConvertType(CExp->EltTy);
Alexey Samsonov153004f2014-09-29 22:08:00 +0000960 *TI++ = EltTy;
961 *TI++ = EltTy;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000962 } else {
963 assert(isa<NoExpansion>(Exp.get()));
Alexey Samsonov153004f2014-09-29 22:08:00 +0000964 *TI++ = ConvertType(Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000965 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000966}
967
John McCall7f416cc2015-09-08 08:05:57 +0000968static void forConstantArrayExpansion(CodeGenFunction &CGF,
969 ConstantArrayExpansion *CAE,
970 Address BaseAddr,
971 llvm::function_ref<void(Address)> Fn) {
972 CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
973 CharUnits EltAlign =
974 BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
975
976 for (int i = 0, n = CAE->NumElts; i < n; i++) {
977 llvm::Value *EltAddr =
978 CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i);
979 Fn(Address(EltAddr, EltAlign));
980 }
981}
982
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000983void CodeGenFunction::ExpandTypeFromArgs(
John McCall12f23522016-04-04 18:33:08 +0000984 QualType Ty, LValue LV, SmallVectorImpl<llvm::Value *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000985 assert(LV.isSimple() &&
986 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000987
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000988 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, LV.getAddress(),
991 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000992 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
993 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
John McCall7f416cc2015-09-08 08:05:57 +0000994 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000995 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000996 Address This = LV.getAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +0000997 for (const CXXBaseSpecifier *BS : RExp->Bases) {
998 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +0000999 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +00001000 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1001 /*NullCheckValue=*/false, SourceLocation());
1002 LValue SubLV = MakeAddrLValue(Base, BS->getType());
1003
1004 // Recurse onto bases.
1005 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
1006 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001007 for (auto FD : RExp->Fields) {
1008 // FIXME: What are the right qualifiers here?
Reid Kleckner9d031092016-05-02 22:42:34 +00001009 LValue SubLV = EmitLValueForFieldInitialization(LV, FD);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001010 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
Bob Wilsone826a2a2011-08-03 05:58:22 +00001011 }
John McCall7f416cc2015-09-08 08:05:57 +00001012 } else if (isa<ComplexExpansion>(Exp.get())) {
1013 auto realValue = *AI++;
1014 auto imagValue = *AI++;
1015 EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001016 } else {
1017 assert(isa<NoExpansion>(Exp.get()));
1018 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001019 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001020}
1021
1022void CodeGenFunction::ExpandTypeToArgs(
1023 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
1024 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
1025 auto Exp = getTypeExpansion(Ty, getContext());
1026 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +00001027 forConstantArrayExpansion(*this, CAExp, RV.getAggregateAddress(),
1028 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001029 RValue EltRV =
1030 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
1031 ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
John McCall7f416cc2015-09-08 08:05:57 +00001032 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001033 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +00001034 Address This = RV.getAggregateAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +00001035 for (const CXXBaseSpecifier *BS : RExp->Bases) {
1036 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +00001037 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +00001038 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1039 /*NullCheckValue=*/false, SourceLocation());
1040 RValue BaseRV = RValue::getAggregate(Base);
1041
1042 // Recurse onto bases.
1043 ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
1044 IRCallArgPos);
1045 }
1046
1047 LValue LV = MakeAddrLValue(This, Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001048 for (auto FD : RExp->Fields) {
1049 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
1050 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
1051 IRCallArgPos);
1052 }
1053 } else if (isa<ComplexExpansion>(Exp.get())) {
1054 ComplexPairTy CV = RV.getComplexVal();
1055 IRCallArgs[IRCallArgPos++] = CV.first;
1056 IRCallArgs[IRCallArgPos++] = CV.second;
1057 } else {
1058 assert(isa<NoExpansion>(Exp.get()));
1059 assert(RV.isScalar() &&
1060 "Unexpected non-scalar rvalue during struct expansion.");
1061
1062 // Insert a bitcast as needed.
1063 llvm::Value *V = RV.getScalarVal();
1064 if (IRCallArgPos < IRFuncTy->getNumParams() &&
1065 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
1066 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
1067
1068 IRCallArgs[IRCallArgPos++] = V;
1069 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001070}
1071
John McCall7f416cc2015-09-08 08:05:57 +00001072/// Create a temporary allocation for the purposes of coercion.
1073static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
1074 CharUnits MinAlign) {
1075 // Don't use an alignment that's worse than what LLVM would prefer.
1076 auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty);
1077 CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
1078
1079 return CGF.CreateTempAlloca(Ty, Align);
1080}
1081
Chris Lattner895c52b2010-06-27 06:04:18 +00001082/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +00001083/// accessing some number of bytes out of it, try to gep into the struct to get
1084/// at its inner goodness. Dive as deep as possible without entering an element
1085/// with an in-memory size smaller than DstSize.
John McCall7f416cc2015-09-08 08:05:57 +00001086static Address
1087EnterStructPointerForCoercedAccess(Address SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +00001088 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +00001089 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +00001090 // We can't dive into a zero-element struct.
1091 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001092
Chris Lattner2192fe52011-07-18 04:24:23 +00001093 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001094
Chris Lattner1cd66982010-06-27 05:56:15 +00001095 // 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 +00001096 // first element is the same size as the whole struct, we can enter it. The
1097 // comparison must be made on the store size and not the alloca size. Using
1098 // the alloca size may overstate the size of the load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001099 uint64_t FirstEltSize =
James Molloy90d61012014-08-29 10:17:52 +00001100 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001101 if (FirstEltSize < DstSize &&
James Molloy90d61012014-08-29 10:17:52 +00001102 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +00001103 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001104
Chris Lattner1cd66982010-06-27 05:56:15 +00001105 // GEP into the first element.
John McCall7f416cc2015-09-08 08:05:57 +00001106 SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, CharUnits(), "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001107
Chris Lattner1cd66982010-06-27 05:56:15 +00001108 // If the first element is a struct, recurse.
John McCall7f416cc2015-09-08 08:05:57 +00001109 llvm::Type *SrcTy = SrcPtr.getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001110 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +00001111 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +00001112
1113 return SrcPtr;
1114}
1115
Chris Lattner055097f2010-06-27 06:26:04 +00001116/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
1117/// are either integers or pointers. This does a truncation of the value if it
1118/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001119///
1120/// This behaves as if the value were coerced through memory, so on big-endian
1121/// targets the high bits are preserved in a truncation, while little-endian
1122/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +00001123static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +00001124 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +00001125 CodeGenFunction &CGF) {
1126 if (Val->getType() == Ty)
1127 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001128
Chris Lattner055097f2010-06-27 06:26:04 +00001129 if (isa<llvm::PointerType>(Val->getType())) {
1130 // If this is Pointer->Pointer avoid conversion to and from int.
1131 if (isa<llvm::PointerType>(Ty))
1132 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001133
Chris Lattner055097f2010-06-27 06:26:04 +00001134 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +00001135 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +00001136 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001137
Chris Lattner2192fe52011-07-18 04:24:23 +00001138 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +00001139 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +00001140 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001141
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001142 if (Val->getType() != DestIntTy) {
1143 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
1144 if (DL.isBigEndian()) {
1145 // Preserve the high bits on big-endian targets.
1146 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +00001147 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
1148 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
1149
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001150 if (SrcSize > DstSize) {
1151 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
1152 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
1153 } else {
1154 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
1155 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
1156 }
1157 } else {
1158 // Little-endian targets preserve the low bits. No shifts required.
1159 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
1160 }
1161 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001162
Chris Lattner055097f2010-06-27 06:26:04 +00001163 if (isa<llvm::PointerType>(Ty))
1164 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
1165 return Val;
1166}
1167
Chris Lattner1cd66982010-06-27 05:56:15 +00001168
1169
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001170/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001171/// a pointer to an object of type \arg Ty, known to be aligned to
1172/// \arg SrcAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001173///
1174/// This safely handles the case when the src type is smaller than the
1175/// destination type; in this situation the values of bits which not
1176/// present in the src are undefined.
John McCall7f416cc2015-09-08 08:05:57 +00001177static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001178 CodeGenFunction &CGF) {
John McCall7f416cc2015-09-08 08:05:57 +00001179 llvm::Type *SrcTy = Src.getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001180
Chris Lattnerd200eda2010-06-28 22:51:39 +00001181 // If SrcTy and Ty are the same, just do a load.
1182 if (SrcTy == Ty)
John McCall7f416cc2015-09-08 08:05:57 +00001183 return CGF.Builder.CreateLoad(Src);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001184
Micah Villmowdd31ca12012-10-08 16:25:52 +00001185 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001186
Chris Lattner2192fe52011-07-18 04:24:23 +00001187 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001188 Src = EnterStructPointerForCoercedAccess(Src, SrcSTy, DstSize, CGF);
1189 SrcTy = Src.getType()->getElementType();
Chris Lattner1cd66982010-06-27 05:56:15 +00001190 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001191
Micah Villmowdd31ca12012-10-08 16:25:52 +00001192 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001193
Chris Lattner055097f2010-06-27 06:26:04 +00001194 // If the source and destination are integer or pointer types, just do an
1195 // extension or truncation to the desired type.
1196 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
1197 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
John McCall7f416cc2015-09-08 08:05:57 +00001198 llvm::Value *Load = CGF.Builder.CreateLoad(Src);
Chris Lattner055097f2010-06-27 06:26:04 +00001199 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
1200 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001201
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001202 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +00001203 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +00001204 // Generally SrcSize is never greater than DstSize, since this means we are
1205 // losing bits. However, this can happen in cases where the structure has
1206 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +00001207 //
Mike Stump18bb9282009-05-16 07:57:57 +00001208 // FIXME: Assert that we aren't truncating non-padding bits when have access
1209 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001210 Src = CGF.Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(Ty));
1211 return CGF.Builder.CreateLoad(Src);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001212 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001213
John McCall7f416cc2015-09-08 08:05:57 +00001214 // Otherwise do coercion through memory. This is stupid, but simple.
1215 Address Tmp = CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment());
1216 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1217 Address SrcCasted = CGF.Builder.CreateBitCast(Src, CGF.Int8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001218 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
1219 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
John McCall7f416cc2015-09-08 08:05:57 +00001220 false);
1221 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001222}
1223
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001224// Function to store a first-class aggregate into memory. We prefer to
1225// store the elements rather than the aggregate to be more friendly to
1226// fast-isel.
1227// FIXME: Do we need to recurse here?
1228static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
John McCall7f416cc2015-09-08 08:05:57 +00001229 Address Dest, bool DestIsVolatile) {
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001230 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +00001231 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001232 dyn_cast<llvm::StructType>(Val->getType())) {
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001233 const llvm::StructLayout *Layout =
1234 CGF.CGM.getDataLayout().getStructLayout(STy);
1235
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001236 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00001237 auto EltOffset = CharUnits::fromQuantity(Layout->getElementOffset(i));
1238 Address EltPtr = CGF.Builder.CreateStructGEP(Dest, i, EltOffset);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001239 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
John McCall7f416cc2015-09-08 08:05:57 +00001240 CGF.Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001241 }
1242 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001243 CGF.Builder.CreateStore(Val, Dest, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001244 }
1245}
1246
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001247/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001248/// where the source and destination may have different types. The
1249/// destination is known to be aligned to \arg DstAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001250///
1251/// This safely handles the case when the src type is larger than the
1252/// destination type; the upper bits of the src will be lost.
1253static void CreateCoercedStore(llvm::Value *Src,
John McCall7f416cc2015-09-08 08:05:57 +00001254 Address Dst,
Anders Carlsson17490832009-12-24 20:40:36 +00001255 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001256 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001257 llvm::Type *SrcTy = Src->getType();
John McCall7f416cc2015-09-08 08:05:57 +00001258 llvm::Type *DstTy = Dst.getType()->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +00001259 if (SrcTy == DstTy) {
John McCall7f416cc2015-09-08 08:05:57 +00001260 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattnerd200eda2010-06-28 22:51:39 +00001261 return;
1262 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001263
Micah Villmowdd31ca12012-10-08 16:25:52 +00001264 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001265
Chris Lattner2192fe52011-07-18 04:24:23 +00001266 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001267 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy, SrcSize, CGF);
1268 DstTy = Dst.getType()->getElementType();
Chris Lattner895c52b2010-06-27 06:04:18 +00001269 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001270
Chris Lattner055097f2010-06-27 06:26:04 +00001271 // If the source and destination are integer or pointer types, just do an
1272 // extension or truncation to the desired type.
1273 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1274 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1275 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
John McCall7f416cc2015-09-08 08:05:57 +00001276 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattner055097f2010-06-27 06:26:04 +00001277 return;
1278 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001279
Micah Villmowdd31ca12012-10-08 16:25:52 +00001280 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001281
Daniel Dunbar313321e2009-02-03 05:31:23 +00001282 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001283 if (SrcSize <= DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00001284 Dst = CGF.Builder.CreateBitCast(Dst, llvm::PointerType::getUnqual(SrcTy));
1285 BuildAggStore(CGF, Src, Dst, DstIsVolatile);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001286 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001287 // Otherwise do coercion through memory. This is stupid, but
1288 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001289
1290 // Generally SrcSize is never greater than DstSize, since this means we are
1291 // losing bits. However, this can happen in cases where the structure has
1292 // additional padding, for example due to a user specified alignment.
1293 //
1294 // FIXME: Assert that we aren't truncating non-padding bits when have access
1295 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001296 Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
1297 CGF.Builder.CreateStore(Src, Tmp);
1298 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1299 Address DstCasted = CGF.Builder.CreateBitCast(Dst, CGF.Int8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001300 CGF.Builder.CreateMemCpy(DstCasted, Casted,
1301 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
John McCall7f416cc2015-09-08 08:05:57 +00001302 false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001303 }
1304}
1305
John McCall7f416cc2015-09-08 08:05:57 +00001306static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
1307 const ABIArgInfo &info) {
1308 if (unsigned offset = info.getDirectOffset()) {
1309 addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
1310 addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
1311 CharUnits::fromQuantity(offset));
1312 addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
1313 }
1314 return addr;
1315}
1316
Alexey Samsonov153004f2014-09-29 22:08:00 +00001317namespace {
1318
1319/// Encapsulates information about the way function arguments from
1320/// CGFunctionInfo should be passed to actual LLVM IR function.
1321class ClangToLLVMArgMapping {
1322 static const unsigned InvalidIndex = ~0U;
1323 unsigned InallocaArgNo;
1324 unsigned SRetArgNo;
1325 unsigned TotalIRArgs;
1326
1327 /// Arguments of LLVM IR function corresponding to single Clang argument.
1328 struct IRArgs {
1329 unsigned PaddingArgIndex;
1330 // Argument is expanded to IR arguments at positions
1331 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1332 unsigned FirstArgIndex;
1333 unsigned NumberOfArgs;
1334
1335 IRArgs()
1336 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1337 NumberOfArgs(0) {}
1338 };
1339
1340 SmallVector<IRArgs, 8> ArgInfo;
1341
1342public:
1343 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1344 bool OnlyRequiredArgs = false)
1345 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1346 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1347 construct(Context, FI, OnlyRequiredArgs);
1348 }
1349
1350 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1351 unsigned getInallocaArgNo() const {
1352 assert(hasInallocaArg());
1353 return InallocaArgNo;
1354 }
1355
1356 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1357 unsigned getSRetArgNo() const {
1358 assert(hasSRetArg());
1359 return SRetArgNo;
1360 }
1361
1362 unsigned totalIRArgs() const { return TotalIRArgs; }
1363
1364 bool hasPaddingArg(unsigned ArgNo) const {
1365 assert(ArgNo < ArgInfo.size());
1366 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1367 }
1368 unsigned getPaddingArgNo(unsigned ArgNo) const {
1369 assert(hasPaddingArg(ArgNo));
1370 return ArgInfo[ArgNo].PaddingArgIndex;
1371 }
1372
1373 /// Returns index of first IR argument corresponding to ArgNo, and their
1374 /// quantity.
1375 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1376 assert(ArgNo < ArgInfo.size());
1377 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1378 ArgInfo[ArgNo].NumberOfArgs);
1379 }
1380
1381private:
1382 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1383 bool OnlyRequiredArgs);
1384};
1385
1386void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1387 const CGFunctionInfo &FI,
1388 bool OnlyRequiredArgs) {
1389 unsigned IRArgNo = 0;
1390 bool SwapThisWithSRet = false;
1391 const ABIArgInfo &RetAI = FI.getReturnInfo();
1392
1393 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1394 SwapThisWithSRet = RetAI.isSRetAfterThis();
1395 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1396 }
1397
1398 unsigned ArgNo = 0;
1399 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1400 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1401 ++I, ++ArgNo) {
1402 assert(I != FI.arg_end());
1403 QualType ArgType = I->type;
1404 const ABIArgInfo &AI = I->info;
1405 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1406 auto &IRArgs = ArgInfo[ArgNo];
1407
1408 if (AI.getPaddingType())
1409 IRArgs.PaddingArgIndex = IRArgNo++;
1410
1411 switch (AI.getKind()) {
1412 case ABIArgInfo::Extend:
1413 case ABIArgInfo::Direct: {
1414 // FIXME: handle sseregparm someday...
1415 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1416 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1417 IRArgs.NumberOfArgs = STy->getNumElements();
1418 } else {
1419 IRArgs.NumberOfArgs = 1;
1420 }
1421 break;
1422 }
1423 case ABIArgInfo::Indirect:
1424 IRArgs.NumberOfArgs = 1;
1425 break;
1426 case ABIArgInfo::Ignore:
1427 case ABIArgInfo::InAlloca:
1428 // ignore and inalloca doesn't have matching LLVM parameters.
1429 IRArgs.NumberOfArgs = 0;
1430 break;
John McCallf26e73d2016-03-11 04:30:43 +00001431 case ABIArgInfo::CoerceAndExpand:
1432 IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
1433 break;
1434 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001435 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1436 break;
1437 }
Alexey Samsonov153004f2014-09-29 22:08:00 +00001438
1439 if (IRArgs.NumberOfArgs > 0) {
1440 IRArgs.FirstArgIndex = IRArgNo;
1441 IRArgNo += IRArgs.NumberOfArgs;
1442 }
1443
1444 // Skip over the sret parameter when it comes second. We already handled it
1445 // above.
1446 if (IRArgNo == 1 && SwapThisWithSRet)
1447 IRArgNo++;
1448 }
1449 assert(ArgNo == ArgInfo.size());
1450
1451 if (FI.usesInAlloca())
1452 InallocaArgNo = IRArgNo++;
1453
1454 TotalIRArgs = IRArgNo;
1455}
1456} // namespace
1457
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001458/***/
1459
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001460bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001461 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00001462}
1463
Tim Northovere77cc392014-03-29 13:28:05 +00001464bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1465 return ReturnTypeUsesSRet(FI) &&
1466 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1467}
1468
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001469bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1470 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1471 switch (BT->getKind()) {
1472 default:
1473 return false;
1474 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +00001475 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001476 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +00001477 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001478 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +00001479 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001480 }
1481 }
1482
1483 return false;
1484}
1485
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001486bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1487 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1488 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1489 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +00001490 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001491 }
1492 }
1493
1494 return false;
1495}
1496
Chris Lattnera5f58b02011-07-09 17:41:47 +00001497llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +00001498 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1499 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +00001500}
1501
Chris Lattnera5f58b02011-07-09 17:41:47 +00001502llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +00001503CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001504
David Blaikie82e95a32014-11-19 07:49:47 +00001505 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1506 (void)Inserted;
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001507 assert(Inserted && "Recursively being processed?");
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001508
Alexey Samsonov153004f2014-09-29 22:08:00 +00001509 llvm::Type *resultType = nullptr;
John McCall85dd2c52011-05-15 02:19:42 +00001510 const ABIArgInfo &retAI = FI.getReturnInfo();
1511 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +00001512 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +00001513 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +00001514
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001515 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001516 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +00001517 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +00001518 break;
1519
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001520 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001521 if (retAI.getInAllocaSRet()) {
1522 // sret things on win32 aren't void, they return the sret pointer.
1523 QualType ret = FI.getReturnType();
1524 llvm::Type *ty = ConvertType(ret);
1525 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1526 resultType = llvm::PointerType::get(ty, addressSpace);
1527 } else {
1528 resultType = llvm::Type::getVoidTy(getLLVMContext());
1529 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001530 break;
1531
John McCall7f416cc2015-09-08 08:05:57 +00001532 case ABIArgInfo::Indirect:
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001533 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +00001534 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001535 break;
John McCallf26e73d2016-03-11 04:30:43 +00001536
1537 case ABIArgInfo::CoerceAndExpand:
1538 resultType = retAI.getUnpaddedCoerceAndExpandType();
1539 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001540 }
Mike Stump11289f42009-09-09 15:08:12 +00001541
Alexey Samsonov153004f2014-09-29 22:08:00 +00001542 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1543 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1544
1545 // Add type for sret argument.
1546 if (IRFunctionArgs.hasSRetArg()) {
1547 QualType Ret = FI.getReturnType();
1548 llvm::Type *Ty = ConvertType(Ret);
1549 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1550 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1551 llvm::PointerType::get(Ty, AddressSpace);
1552 }
1553
1554 // Add type for inalloca argument.
1555 if (IRFunctionArgs.hasInallocaArg()) {
1556 auto ArgStruct = FI.getArgStruct();
1557 assert(ArgStruct);
1558 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1559 }
1560
John McCallc818bbb2012-12-07 07:03:17 +00001561 // Add in all of the required arguments.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001562 unsigned ArgNo = 0;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00001563 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1564 ie = it + FI.getNumRequiredArgs();
Alexey Samsonov153004f2014-09-29 22:08:00 +00001565 for (; it != ie; ++it, ++ArgNo) {
1566 const ABIArgInfo &ArgInfo = it->info;
Mike Stump11289f42009-09-09 15:08:12 +00001567
Rafael Espindolafad28de2012-10-24 01:59:00 +00001568 // Insert a padding type to ensure proper alignment.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001569 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1570 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1571 ArgInfo.getPaddingType();
Rafael Espindolafad28de2012-10-24 01:59:00 +00001572
Alexey Samsonov153004f2014-09-29 22:08:00 +00001573 unsigned FirstIRArg, NumIRArgs;
1574 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1575
1576 switch (ArgInfo.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001577 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001578 case ABIArgInfo::InAlloca:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001579 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001580 break;
1581
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001582 case ABIArgInfo::Indirect: {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001583 assert(NumIRArgs == 1);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001584 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +00001585 llvm::Type *LTy = ConvertTypeForMem(it->type);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001586 ArgTypes[FirstIRArg] = LTy->getPointerTo();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001587 break;
1588 }
1589
1590 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +00001591 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001592 // Fast-isel and the optimizer generally like scalar values better than
1593 // FCAs, so we flatten them if this is safe to do for this argument.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001594 llvm::Type *argType = ArgInfo.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +00001595 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001596 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1597 assert(NumIRArgs == st->getNumElements());
John McCall85dd2c52011-05-15 02:19:42 +00001598 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
Alexey Samsonov153004f2014-09-29 22:08:00 +00001599 ArgTypes[FirstIRArg + i] = st->getElementType(i);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001600 } else {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001601 assert(NumIRArgs == 1);
1602 ArgTypes[FirstIRArg] = argType;
Chris Lattner3dd716c2010-06-28 23:44:11 +00001603 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001604 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001605 }
Mike Stump11289f42009-09-09 15:08:12 +00001606
John McCallf26e73d2016-03-11 04:30:43 +00001607 case ABIArgInfo::CoerceAndExpand: {
1608 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1609 for (auto EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
1610 *ArgTypesIter++ = EltTy;
1611 }
1612 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1613 break;
1614 }
1615
Daniel Dunbard3674e62008-09-11 01:48:57 +00001616 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001617 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1618 getExpandedTypes(it->type, ArgTypesIter);
1619 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001620 break;
1621 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001622 }
1623
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001624 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1625 assert(Erased && "Not in set?");
Alexey Samsonov153004f2014-09-29 22:08:00 +00001626
1627 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001628}
1629
Chris Lattner2192fe52011-07-18 04:24:23 +00001630llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001631 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001632 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001633
Chris Lattner8806e322011-07-10 00:18:59 +00001634 if (!isFuncTypeConvertible(FPT))
1635 return llvm::StructType::get(getLLVMContext());
1636
1637 const CGFunctionInfo *Info;
1638 if (isa<CXXDestructorDecl>(MD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001639 Info =
1640 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
Chris Lattner8806e322011-07-10 00:18:59 +00001641 else
John McCalla729c622012-02-17 03:33:10 +00001642 Info = &arrangeCXXMethodDeclaration(MD);
1643 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001644}
1645
Samuel Antao798f11c2015-11-23 22:04:44 +00001646static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
1647 llvm::AttrBuilder &FuncAttrs,
1648 const FunctionProtoType *FPT) {
1649 if (!FPT)
1650 return;
1651
1652 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
1653 FPT->isNothrow(Ctx))
1654 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1655}
1656
Justin Lebarb080b632017-01-25 21:29:48 +00001657void CodeGenModule::ConstructDefaultFnAttrList(StringRef Name, bool HasOptnone,
1658 bool AttrOnCallSite,
1659 llvm::AttrBuilder &FuncAttrs) {
1660 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1661 if (!HasOptnone) {
1662 if (CodeGenOpts.OptimizeSize)
1663 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1664 if (CodeGenOpts.OptimizeSize == 2)
1665 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1666 }
1667
1668 if (CodeGenOpts.DisableRedZone)
1669 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
1670 if (CodeGenOpts.NoImplicitFloat)
1671 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
1672
1673 if (AttrOnCallSite) {
1674 // Attributes that should go on the call site only.
1675 if (!CodeGenOpts.SimplifyLibCalls ||
1676 CodeGenOpts.isNoBuiltinFunc(Name.data()))
1677 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
1678 if (!CodeGenOpts.TrapFuncName.empty())
1679 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
1680 } else {
1681 // Attributes that should go on the function, but not the call site.
1682 if (!CodeGenOpts.DisableFPElim) {
1683 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
1684 } else if (CodeGenOpts.OmitLeafFramePointer) {
1685 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
1686 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
1687 } else {
1688 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
1689 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
1690 }
1691
1692 FuncAttrs.addAttribute("less-precise-fpmad",
1693 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
1694
1695 if (!CodeGenOpts.FPDenormalMode.empty())
1696 FuncAttrs.addAttribute("denormal-fp-math", CodeGenOpts.FPDenormalMode);
1697
1698 FuncAttrs.addAttribute("no-trapping-math",
1699 llvm::toStringRef(CodeGenOpts.NoTrappingMath));
1700
1701 // TODO: Are these all needed?
1702 // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags.
1703 FuncAttrs.addAttribute("no-infs-fp-math",
1704 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
1705 FuncAttrs.addAttribute("no-nans-fp-math",
1706 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
1707 FuncAttrs.addAttribute("unsafe-fp-math",
1708 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
1709 FuncAttrs.addAttribute("use-soft-float",
1710 llvm::toStringRef(CodeGenOpts.SoftFloat));
1711 FuncAttrs.addAttribute("stack-protector-buffer-size",
1712 llvm::utostr(CodeGenOpts.SSPBufferSize));
1713 FuncAttrs.addAttribute("no-signed-zeros-fp-math",
1714 llvm::toStringRef(CodeGenOpts.NoSignedZeros));
1715 FuncAttrs.addAttribute(
1716 "correctly-rounded-divide-sqrt-fp-math",
1717 llvm::toStringRef(CodeGenOpts.CorrectlyRoundedDivSqrt));
1718
1719 // TODO: Reciprocal estimate codegen options should apply to instructions?
1720 std::vector<std::string> &Recips = getTarget().getTargetOpts().Reciprocals;
1721 if (!Recips.empty())
1722 FuncAttrs.addAttribute("reciprocal-estimates",
1723 llvm::join(Recips.begin(), Recips.end(), ","));
1724
1725 if (CodeGenOpts.StackRealignment)
1726 FuncAttrs.addAttribute("stackrealign");
1727 if (CodeGenOpts.Backchain)
1728 FuncAttrs.addAttribute("backchain");
1729 }
1730
1731 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
1732 // Conservatively, mark all functions and calls in CUDA as convergent
1733 // (meaning, they may call an intrinsically convergent op, such as
1734 // __syncthreads(), and so can't have certain optimizations applied around
1735 // them). LLVM will remove this attribute where it safely can.
1736 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
1737
1738 // Exceptions aren't supported in CUDA device code.
1739 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1740
1741 // Respect -fcuda-flush-denormals-to-zero.
1742 if (getLangOpts().CUDADeviceFlushDenormalsToZero)
1743 FuncAttrs.addAttribute("nvptx-f32ftz", "true");
1744 }
1745}
1746
1747void CodeGenModule::AddDefaultFnAttrs(llvm::Function &F) {
1748 llvm::AttrBuilder FuncAttrs;
1749 ConstructDefaultFnAttrList(F.getName(),
1750 F.hasFnAttribute(llvm::Attribute::OptimizeNone),
1751 /* AttrOnCallsite = */ false, FuncAttrs);
1752 llvm::AttributeSet AS = llvm::AttributeSet::get(
1753 getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
1754 F.addAttributes(llvm::AttributeSet::FunctionIndex, AS);
1755}
1756
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00001757void CodeGenModule::ConstructAttributeList(
1758 StringRef Name, const CGFunctionInfo &FI, CGCalleeInfo CalleeInfo,
1759 AttributeListType &PAL, unsigned &CallingConv, bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001760 llvm::AttrBuilder FuncAttrs;
1761 llvm::AttrBuilder RetAttrs;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001762
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001763 CallingConv = FI.getEffectiveCallingConvention();
John McCallab26cfa2010-02-05 21:31:56 +00001764 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001765 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001766
Samuel Antao798f11c2015-11-23 22:04:44 +00001767 // If we have information about the function prototype, we can learn
1768 // attributes form there.
1769 AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
1770 CalleeInfo.getCalleeFunctionProtoType());
1771
1772 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
1773
Justin Lebarb080b632017-01-25 21:29:48 +00001774 bool HasOptnone = false;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001775 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001776 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001777 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001778 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001779 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001780 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001781 if (TargetDecl->hasAttr<NoReturnAttr>())
1782 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001783 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1784 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Yaxun Liu7d07ae72016-11-01 18:45:32 +00001785 if (TargetDecl->hasAttr<ConvergentAttr>())
1786 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
Richard Smithdebc59d2013-01-30 05:45:05 +00001787
1788 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
Samuel Antao798f11c2015-11-23 22:04:44 +00001789 AddAttributesFromFunctionProtoType(
1790 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
Richard Smith49af6292013-03-05 08:30:04 +00001791 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1792 // These attributes are not inherited by overloads.
1793 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1794 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001795 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001796 }
1797
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001798 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
Eric Christopherbf005ec2011-08-15 22:38:22 +00001799 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001800 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1801 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001802 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001803 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1804 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001805 } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
1806 FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
1807 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001808 }
David Majnemer631a90b2015-02-04 07:23:21 +00001809 if (TargetDecl->hasAttr<RestrictAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001810 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001811 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1812 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Paul Robinson08556952014-12-11 20:14:04 +00001813
1814 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
George Burgess IVe3763372016-12-22 02:50:20 +00001815 if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) {
1816 Optional<unsigned> NumElemsParam;
1817 // alloc_size args are base-1, 0 means not present.
1818 if (unsigned N = AllocSize->getNumElemsParam())
1819 NumElemsParam = N - 1;
1820 FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam() - 1,
1821 NumElemsParam);
1822 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001823 }
1824
Justin Lebarb080b632017-01-25 21:29:48 +00001825 ConstructDefaultFnAttrList(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
Paul Robinson08556952014-12-11 20:14:04 +00001826
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001827 if (CodeGenOpts.EnableSegmentedStacks &&
1828 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001829 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001830
Justin Lebarb080b632017-01-25 21:29:48 +00001831 if (!AttrOnCallSite) {
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001832 bool DisableTailCalls =
Justin Lebarb080b632017-01-25 21:29:48 +00001833 CodeGenOpts.DisableTailCalls ||
1834 (TargetDecl && (TargetDecl->hasAttr<DisableTailCallsAttr>() ||
1835 TargetDecl->hasAttr<AnyX86InterruptAttr>()));
1836 FuncAttrs.addAttribute("disable-tail-calls",
1837 llvm::toStringRef(DisableTailCalls));
Eric Christopher70c16652015-03-25 23:14:47 +00001838
Eric Christopher11acf732015-06-12 01:35:52 +00001839 // Add target-cpu and target-features attributes to functions. If
1840 // we have a decl for the function and it has a target attribute then
1841 // parse that and add it to the feature set.
1842 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
Eric Christopher11acf732015-06-12 01:35:52 +00001843 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
Eric Christopherb57804a2015-09-01 22:03:56 +00001844 if (FD && FD->hasAttr<TargetAttr>()) {
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001845 llvm::StringMap<bool> FeatureMap;
Eric Christopher2b90a642015-11-11 23:05:08 +00001846 getFunctionFeatureMap(FeatureMap, FD);
Eric Christopher11acf732015-06-12 01:35:52 +00001847
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001848 // Produce the canonical string for this set of features.
1849 std::vector<std::string> Features;
1850 for (llvm::StringMap<bool>::const_iterator it = FeatureMap.begin(),
1851 ie = FeatureMap.end();
1852 it != ie; ++it)
1853 Features.push_back((it->second ? "+" : "-") + it->first().str());
Eric Christopher2249b812015-07-01 00:08:29 +00001854
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001855 // Now add the target-cpu and target-features to the function.
Eric Christopher2b90a642015-11-11 23:05:08 +00001856 // While we populated the feature map above, we still need to
1857 // get and parse the target attribute so we can get the cpu for
1858 // the function.
1859 const auto *TD = FD->getAttr<TargetAttr>();
1860 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
1861 if (ParsedAttr.second != "")
1862 TargetCPU = ParsedAttr.second;
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001863 if (TargetCPU != "")
1864 FuncAttrs.addAttribute("target-cpu", TargetCPU);
1865 if (!Features.empty()) {
1866 std::sort(Features.begin(), Features.end());
1867 FuncAttrs.addAttribute(
1868 "target-features",
1869 llvm::join(Features.begin(), Features.end(), ","));
1870 }
1871 } else {
1872 // Otherwise just add the existing target cpu and target features to the
1873 // function.
1874 std::vector<std::string> &Features = getTarget().getTargetOpts().Features;
1875 if (TargetCPU != "")
1876 FuncAttrs.addAttribute("target-cpu", TargetCPU);
1877 if (!Features.empty()) {
1878 std::sort(Features.begin(), Features.end());
1879 FuncAttrs.addAttribute(
1880 "target-features",
1881 llvm::join(Features.begin(), Features.end(), ","));
1882 }
Eric Christopher70c16652015-03-25 23:14:47 +00001883 }
Bill Wendling985d1c52013-02-15 21:30:01 +00001884 }
1885
Alexey Samsonov153004f2014-09-29 22:08:00 +00001886 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001887
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001888 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001889 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001890 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001891 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001892 if (RetTy->hasSignedIntegerRepresentation())
1893 RetAttrs.addAttribute(llvm::Attribute::SExt);
1894 else if (RetTy->hasUnsignedIntegerRepresentation())
1895 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001896 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001897 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001898 if (RetAI.getInReg())
1899 RetAttrs.addAttribute(llvm::Attribute::InReg);
1900 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001901 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001902 break;
1903
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001904 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001905 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001906 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001907 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1908 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001909 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001910 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001911
John McCallf26e73d2016-03-11 04:30:43 +00001912 case ABIArgInfo::CoerceAndExpand:
1913 break;
1914
Daniel Dunbard3674e62008-09-11 01:48:57 +00001915 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001916 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001917 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001918
Hal Finkela2347ba2014-07-18 15:52:10 +00001919 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1920 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00001921 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00001922 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1923 .getQuantity());
1924 else if (getContext().getTargetAddressSpace(PTy) == 0)
1925 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1926 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001927
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001928 // Attach return attributes.
1929 if (RetAttrs.hasAttributes()) {
1930 PAL.push_back(llvm::AttributeSet::get(
1931 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1932 }
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001933
John McCall12f23522016-04-04 18:33:08 +00001934 bool hasUsedSRet = false;
1935
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001936 // Attach attributes to sret.
1937 if (IRFunctionArgs.hasSRetArg()) {
1938 llvm::AttrBuilder SRETAttrs;
1939 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
John McCall12f23522016-04-04 18:33:08 +00001940 hasUsedSRet = true;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001941 if (RetAI.getInReg())
1942 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1943 PAL.push_back(llvm::AttributeSet::get(
1944 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1945 }
1946
1947 // Attach attributes to inalloca argument.
1948 if (IRFunctionArgs.hasInallocaArg()) {
1949 llvm::AttrBuilder Attrs;
1950 Attrs.addAttribute(llvm::Attribute::InAlloca);
1951 PAL.push_back(llvm::AttributeSet::get(
1952 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1953 }
1954
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001955 unsigned ArgNo = 0;
1956 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1957 E = FI.arg_end();
1958 I != E; ++I, ++ArgNo) {
1959 QualType ParamType = I->type;
1960 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001961 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001962
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001963 // Add attribute for padding argument, if necessary.
1964 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendling290d9522013-01-27 02:46:53 +00001965 if (AI.getPaddingInReg())
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001966 PAL.push_back(llvm::AttributeSet::get(
1967 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1968 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001969 }
1970
John McCall39ec71f2010-03-27 00:47:27 +00001971 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1972 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001973 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001974 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001975 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001976 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001977 Attrs.addAttribute(llvm::Attribute::SExt);
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00001978 else if (ParamType->isUnsignedIntegerOrEnumerationType()) {
1979 if (getTypes().getABIInfo().shouldSignExtUnsignedType(ParamType))
1980 Attrs.addAttribute(llvm::Attribute::SExt);
1981 else
1982 Attrs.addAttribute(llvm::Attribute::ZExt);
1983 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001984 // FALL THROUGH
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001985 case ABIArgInfo::Direct:
Peter Collingbournef7706832014-12-12 23:41:25 +00001986 if (ArgNo == 0 && FI.isChainCall())
1987 Attrs.addAttribute(llvm::Attribute::Nest);
1988 else if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001989 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001990 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001991
James Y Knight71608572015-08-21 18:19:06 +00001992 case ABIArgInfo::Indirect: {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001993 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001994 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001995
Anders Carlsson20759ad2009-09-16 15:53:40 +00001996 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001997 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001998
John McCall7f416cc2015-09-08 08:05:57 +00001999 CharUnits Align = AI.getIndirectAlign();
James Y Knight71608572015-08-21 18:19:06 +00002000
2001 // In a byval argument, it is important that the required
2002 // alignment of the type is honored, as LLVM might be creating a
2003 // *new* stack object, and needs to know what alignment to give
2004 // it. (Sometimes it can deduce a sensible alignment on its own,
2005 // but not if clang decides it must emit a packed struct, or the
2006 // user specifies increased alignment requirements.)
2007 //
2008 // This is different from indirect *not* byval, where the object
2009 // exists already, and the align attribute is purely
2010 // informative.
John McCall7f416cc2015-09-08 08:05:57 +00002011 assert(!Align.isZero());
James Y Knight71608572015-08-21 18:19:06 +00002012
John McCall7f416cc2015-09-08 08:05:57 +00002013 // For now, only add this when we have a byval argument.
2014 // TODO: be less lazy about updating test cases.
2015 if (AI.getIndirectByVal())
2016 Attrs.addAlignmentAttr(Align.getQuantity());
Bill Wendlinga7912f82012-10-10 07:36:56 +00002017
Daniel Dunbarc2304432009-03-18 19:51:01 +00002018 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00002019 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
2020 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00002021 break;
James Y Knight71608572015-08-21 18:19:06 +00002022 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002023 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002024 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00002025 case ABIArgInfo::CoerceAndExpand:
2026 break;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002027
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002028 case ABIArgInfo::InAlloca:
2029 // inalloca disables readnone and readonly.
2030 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
2031 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002032 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00002033 }
Mike Stump11289f42009-09-09 15:08:12 +00002034
Hal Finkela2347ba2014-07-18 15:52:10 +00002035 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
2036 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00002037 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00002038 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
2039 .getQuantity());
2040 else if (getContext().getTargetAddressSpace(PTy) == 0)
2041 Attrs.addAttribute(llvm::Attribute::NonNull);
2042 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00002043
John McCall12f23522016-04-04 18:33:08 +00002044 switch (FI.getExtParameterInfo(ArgNo).getABI()) {
2045 case ParameterABI::Ordinary:
2046 break;
2047
2048 case ParameterABI::SwiftIndirectResult: {
2049 // Add 'sret' if we haven't already used it for something, but
2050 // only if the result is void.
2051 if (!hasUsedSRet && RetTy->isVoidType()) {
2052 Attrs.addAttribute(llvm::Attribute::StructRet);
2053 hasUsedSRet = true;
2054 }
2055
2056 // Add 'noalias' in either case.
2057 Attrs.addAttribute(llvm::Attribute::NoAlias);
2058
2059 // Add 'dereferenceable' and 'alignment'.
2060 auto PTy = ParamType->getPointeeType();
2061 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2062 auto info = getContext().getTypeInfoInChars(PTy);
2063 Attrs.addDereferenceableAttr(info.first.getQuantity());
2064 Attrs.addAttribute(llvm::Attribute::getWithAlignment(getLLVMContext(),
2065 info.second.getQuantity()));
2066 }
2067 break;
2068 }
2069
2070 case ParameterABI::SwiftErrorResult:
2071 Attrs.addAttribute(llvm::Attribute::SwiftError);
2072 break;
2073
2074 case ParameterABI::SwiftContext:
2075 Attrs.addAttribute(llvm::Attribute::SwiftSelf);
2076 break;
2077 }
2078
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002079 if (Attrs.hasAttributes()) {
2080 unsigned FirstIRArg, NumIRArgs;
2081 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2082 for (unsigned i = 0; i < NumIRArgs; i++)
2083 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
2084 FirstIRArg + i + 1, Attrs));
2085 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00002086 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002087 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002088
Bill Wendlinga7912f82012-10-10 07:36:56 +00002089 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00002090 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00002091 AttributeSet::get(getLLVMContext(),
2092 llvm::AttributeSet::FunctionIndex,
2093 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00002094}
2095
John McCalla738c252011-03-09 04:27:21 +00002096/// An argument came in as a promoted argument; demote it back to its
2097/// declared type.
2098static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
2099 const VarDecl *var,
2100 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002101 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00002102
2103 // This can happen with promotions that actually don't change the
2104 // underlying type, like the enum promotions.
2105 if (value->getType() == varType) return value;
2106
2107 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
2108 && "unexpected promotion type");
2109
2110 if (isa<llvm::IntegerType>(varType))
2111 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
2112
2113 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
2114}
2115
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002116/// Returns the attribute (either parameter attribute, or function
2117/// attribute), which declares argument ArgNo to be non-null.
2118static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
2119 QualType ArgType, unsigned ArgNo) {
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002120 // FIXME: __attribute__((nonnull)) can also be applied to:
2121 // - references to pointers, where the pointee is known to be
2122 // nonnull (apparently a Clang extension)
2123 // - transparent unions containing pointers
2124 // In the former case, LLVM IR cannot represent the constraint. In
2125 // the latter case, we have no guarantee that the transparent union
2126 // is in fact passed as a pointer.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002127 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
2128 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002129 // First, check attribute on parameter itself.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002130 if (PVD) {
2131 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
2132 return ParmNNAttr;
2133 }
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002134 // Check function attributes.
2135 if (!FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002136 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002137 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002138 if (NNAttr->isNonNull(ArgNo))
2139 return NNAttr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002140 }
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002141 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002142}
2143
John McCall12f23522016-04-04 18:33:08 +00002144namespace {
2145 struct CopyBackSwiftError final : EHScopeStack::Cleanup {
2146 Address Temp;
2147 Address Arg;
2148 CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
2149 void Emit(CodeGenFunction &CGF, Flags flags) override {
2150 llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
2151 CGF.Builder.CreateStore(errorValue, Arg);
2152 }
2153 };
2154}
2155
Daniel Dunbard931a872009-02-02 22:03:45 +00002156void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
2157 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00002158 const FunctionArgList &Args) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002159 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
2160 // Naked functions don't have prologues.
2161 return;
2162
John McCallcaa19452009-07-28 01:00:58 +00002163 // If this is an implicit-return-zero function, go ahead and
2164 // initialize the return value. TODO: it might be nice to have
2165 // a more general mechanism for this that didn't require synthesized
2166 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00002167 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00002168 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00002169 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00002170 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00002171 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00002172 Builder.CreateStore(Zero, ReturnValue);
2173 }
2174 }
2175
Mike Stump18bb9282009-05-16 07:57:57 +00002176 // FIXME: We no longer need the types from FunctionArgList; lift up and
2177 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00002178
Alexey Samsonov153004f2014-09-29 22:08:00 +00002179 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002180 // Flattened function arguments.
John McCall12f23522016-04-04 18:33:08 +00002181 SmallVector<llvm::Value *, 16> FnArgs;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002182 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
2183 for (auto &Arg : Fn->args()) {
2184 FnArgs.push_back(&Arg);
2185 }
2186 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00002187
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002188 // If we're using inalloca, all the memory arguments are GEPs off of the last
2189 // parameter, which is a pointer to the complete memory area.
John McCall7f416cc2015-09-08 08:05:57 +00002190 Address ArgStruct = Address::invalid();
2191 const llvm::StructLayout *ArgStructLayout = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002192 if (IRFunctionArgs.hasInallocaArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00002193 ArgStructLayout = CGM.getDataLayout().getStructLayout(FI.getArgStruct());
2194 ArgStruct = Address(FnArgs[IRFunctionArgs.getInallocaArgNo()],
2195 FI.getArgStructAlignment());
2196
2197 assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002198 }
2199
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002200 // Name the struct return parameter.
2201 if (IRFunctionArgs.hasSRetArg()) {
John McCall12f23522016-04-04 18:33:08 +00002202 auto AI = cast<llvm::Argument>(FnArgs[IRFunctionArgs.getSRetArgNo()]);
Daniel Dunbar613855c2008-09-09 23:27:19 +00002203 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00002204 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00002205 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002206 }
Mike Stump11289f42009-09-09 15:08:12 +00002207
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002208 // Track if we received the parameter as a pointer (indirect, byval, or
2209 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
2210 // into a local alloca for us.
John McCall7f416cc2015-09-08 08:05:57 +00002211 SmallVector<ParamValue, 16> ArgVals;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002212 ArgVals.reserve(Args.size());
2213
Reid Kleckner739756c2013-12-04 19:23:12 +00002214 // Create a pointer value for every parameter declaration. This usually
2215 // entails copying one or more LLVM IR arguments into an alloca. Don't push
2216 // any cleanups or do anything that might unwind. We do that separately, so
2217 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002218 assert(FI.arg_size() == Args.size() &&
2219 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002220 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002221 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002222 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00002223 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00002224 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002225 QualType Ty = info_it->type;
2226 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002227
John McCalla738c252011-03-09 04:27:21 +00002228 bool isPromoted =
2229 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
2230
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002231 unsigned FirstIRArg, NumIRArgs;
2232 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002233
Daniel Dunbard3674e62008-09-11 01:48:57 +00002234 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002235 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002236 assert(NumIRArgs == 0);
John McCall7f416cc2015-09-08 08:05:57 +00002237 auto FieldIndex = ArgI.getInAllocaFieldIndex();
2238 CharUnits FieldOffset =
2239 CharUnits::fromQuantity(ArgStructLayout->getElementOffset(FieldIndex));
2240 Address V = Builder.CreateStructGEP(ArgStruct, FieldIndex, FieldOffset,
2241 Arg->getName());
2242 ArgVals.push_back(ParamValue::forIndirect(V));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002243 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002244 }
2245
Daniel Dunbar747865a2009-02-05 09:16:39 +00002246 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002247 assert(NumIRArgs == 1);
John McCall7f416cc2015-09-08 08:05:57 +00002248 Address ParamAddr = Address(FnArgs[FirstIRArg], ArgI.getIndirectAlign());
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002249
John McCall47fb9502013-03-07 21:37:08 +00002250 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002251 // Aggregates and complex variables are accessed by reference. All we
John McCall7f416cc2015-09-08 08:05:57 +00002252 // need to do is realign the value, if requested.
2253 Address V = ParamAddr;
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002254 if (ArgI.getIndirectRealign()) {
John McCall7f416cc2015-09-08 08:05:57 +00002255 Address AlignedTemp = CreateMemTemp(Ty, "coerce");
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002256
2257 // Copy from the incoming argument pointer to the temporary with the
2258 // appropriate alignment.
2259 //
2260 // FIXME: We should have a common utility for generating an aggregate
2261 // copy.
Ken Dyck705ba072011-01-19 01:58:38 +00002262 CharUnits Size = getContext().getTypeSizeInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002263 auto SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity());
2264 Address Dst = Builder.CreateBitCast(AlignedTemp, Int8PtrTy);
2265 Address Src = Builder.CreateBitCast(ParamAddr, Int8PtrTy);
2266 Builder.CreateMemCpy(Dst, Src, SizeVal, false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002267 V = AlignedTemp;
2268 }
John McCall7f416cc2015-09-08 08:05:57 +00002269 ArgVals.push_back(ParamValue::forIndirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00002270 } else {
2271 // Load scalar value from indirect argument.
John McCall7f416cc2015-09-08 08:05:57 +00002272 llvm::Value *V =
2273 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00002274
2275 if (isPromoted)
2276 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002277 ArgVals.push_back(ParamValue::forDirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00002278 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002279 break;
2280 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002281
2282 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00002283 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00002284
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002285 // If we have the trivial case, handle it with no muss and fuss.
2286 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002287 ArgI.getCoerceToType() == ConvertType(Ty) &&
2288 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002289 assert(NumIRArgs == 1);
John McCall12f23522016-04-04 18:33:08 +00002290 llvm::Value *V = FnArgs[FirstIRArg];
2291 auto AI = cast<llvm::Argument>(V);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002292
Hal Finkel48d53e22014-07-19 01:41:07 +00002293 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002294 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
2295 PVD->getFunctionScopeIndex()))
Hal Finkel82504f02014-07-11 17:35:21 +00002296 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2297 AI->getArgNo() + 1,
2298 llvm::Attribute::NonNull));
2299
Hal Finkel48d53e22014-07-19 01:41:07 +00002300 QualType OTy = PVD->getOriginalType();
2301 if (const auto *ArrTy =
2302 getContext().getAsConstantArrayType(OTy)) {
2303 // A C99 array parameter declaration with the static keyword also
2304 // indicates dereferenceability, and if the size is constant we can
2305 // use the dereferenceable attribute (which requires the size in
2306 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00002307 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00002308 QualType ETy = ArrTy->getElementType();
2309 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
2310 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
2311 ArrSize) {
2312 llvm::AttrBuilder Attrs;
2313 Attrs.addDereferenceableAttr(
2314 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
2315 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2316 AI->getArgNo() + 1, Attrs));
2317 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
2318 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2319 AI->getArgNo() + 1,
2320 llvm::Attribute::NonNull));
2321 }
2322 }
2323 } else if (const auto *ArrTy =
2324 getContext().getAsVariableArrayType(OTy)) {
2325 // For C99 VLAs with the static keyword, we don't know the size so
2326 // we can't use the dereferenceable attribute, but in addrspace(0)
2327 // we know that it must be nonnull.
2328 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
2329 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
2330 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2331 AI->getArgNo() + 1,
2332 llvm::Attribute::NonNull));
2333 }
Hal Finkel1b0d24e2014-10-02 21:21:25 +00002334
2335 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
2336 if (!AVAttr)
2337 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
2338 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
2339 if (AVAttr) {
2340 llvm::Value *AlignmentValue =
2341 EmitScalarExpr(AVAttr->getAlignment());
2342 llvm::ConstantInt *AlignmentCI =
2343 cast<llvm::ConstantInt>(AlignmentValue);
2344 unsigned Alignment =
2345 std::min((unsigned) AlignmentCI->getZExtValue(),
2346 +llvm::Value::MaximumAlignment);
2347
2348 llvm::AttrBuilder Attrs;
2349 Attrs.addAlignmentAttr(Alignment);
2350 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2351 AI->getArgNo() + 1, Attrs));
2352 }
Hal Finkel48d53e22014-07-19 01:41:07 +00002353 }
2354
Bill Wendling507c3512012-10-16 05:23:44 +00002355 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00002356 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2357 AI->getArgNo() + 1,
2358 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00002359
John McCall12f23522016-04-04 18:33:08 +00002360 // LLVM expects swifterror parameters to be used in very restricted
2361 // ways. Copy the value into a less-restricted temporary.
2362 if (FI.getExtParameterInfo(ArgNo).getABI()
2363 == ParameterABI::SwiftErrorResult) {
2364 QualType pointeeTy = Ty->getPointeeType();
2365 assert(pointeeTy->isPointerType());
2366 Address temp =
2367 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
2368 Address arg = Address(V, getContext().getTypeAlignInChars(pointeeTy));
2369 llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
2370 Builder.CreateStore(incomingErrorValue, temp);
2371 V = temp.getPointer();
2372
2373 // Push a cleanup to copy the value back at the end of the function.
2374 // The convention does not guarantee that the value will be written
2375 // back if the function exits with an unwind exception.
2376 EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
2377 }
2378
Chris Lattner7369c142011-07-20 06:29:00 +00002379 // Ensure the argument is the correct type.
2380 if (V->getType() != ArgI.getCoerceToType())
2381 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
2382
John McCalla738c252011-03-09 04:27:21 +00002383 if (isPromoted)
2384 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00002385
2386 // Because of merging of function types from multiple decls it is
2387 // possible for the type of an argument to not match the corresponding
2388 // type in the function type. Since we are codegening the callee
2389 // in here, add a cast to the argument type.
2390 llvm::Type *LTy = ConvertType(Arg->getType());
2391 if (V->getType() != LTy)
2392 V = Builder.CreateBitCast(V, LTy);
2393
John McCall7f416cc2015-09-08 08:05:57 +00002394 ArgVals.push_back(ParamValue::forDirect(V));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002395 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00002396 }
Mike Stump11289f42009-09-09 15:08:12 +00002397
John McCall7f416cc2015-09-08 08:05:57 +00002398 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
2399 Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002400
John McCall7f416cc2015-09-08 08:05:57 +00002401 // Pointer to store into.
2402 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002403
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002404 // Fast-isel and the optimizer generally like scalar values better than
2405 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002406 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002407 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
2408 STy->getNumElements() > 1) {
John McCall7f416cc2015-09-08 08:05:57 +00002409 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Micah Villmowdd31ca12012-10-08 16:25:52 +00002410 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
John McCall7f416cc2015-09-08 08:05:57 +00002411 llvm::Type *DstTy = Ptr.getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002412 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002413
John McCall7f416cc2015-09-08 08:05:57 +00002414 Address AddrToStoreInto = Address::invalid();
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002415 if (SrcSize <= DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00002416 AddrToStoreInto =
2417 Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002418 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002419 AddrToStoreInto =
2420 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
Chris Lattner15ec3612010-06-29 00:06:42 +00002421 }
John McCall7f416cc2015-09-08 08:05:57 +00002422
2423 assert(STy->getNumElements() == NumIRArgs);
2424 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2425 auto AI = FnArgs[FirstIRArg + i];
2426 AI->setName(Arg->getName() + ".coerce" + Twine(i));
2427 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
2428 Address EltPtr =
2429 Builder.CreateStructGEP(AddrToStoreInto, i, Offset);
2430 Builder.CreateStore(AI, EltPtr);
2431 }
2432
2433 if (SrcSize > DstSize) {
2434 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
2435 }
2436
Chris Lattner15ec3612010-06-29 00:06:42 +00002437 } else {
2438 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002439 assert(NumIRArgs == 1);
2440 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00002441 AI->setName(Arg->getName() + ".coerce");
John McCall7f416cc2015-09-08 08:05:57 +00002442 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00002443 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002444
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002445 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00002446 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002447 llvm::Value *V =
2448 EmitLoadOfScalar(Alloca, false, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00002449 if (isPromoted)
2450 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002451 ArgVals.push_back(ParamValue::forDirect(V));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002452 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002453 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00002454 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002455 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002456 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002457
John McCallf26e73d2016-03-11 04:30:43 +00002458 case ABIArgInfo::CoerceAndExpand: {
2459 // Reconstruct into a temporary.
2460 Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2461 ArgVals.push_back(ParamValue::forIndirect(alloca));
2462
2463 auto coercionType = ArgI.getCoerceAndExpandType();
2464 alloca = Builder.CreateElementBitCast(alloca, coercionType);
2465 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
2466
2467 unsigned argIndex = FirstIRArg;
2468 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2469 llvm::Type *eltType = coercionType->getElementType(i);
2470 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
2471 continue;
2472
2473 auto eltAddr = Builder.CreateStructGEP(alloca, i, layout);
2474 auto elt = FnArgs[argIndex++];
2475 Builder.CreateStore(elt, eltAddr);
2476 }
2477 assert(argIndex == FirstIRArg + NumIRArgs);
2478 break;
2479 }
2480
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002481 case ABIArgInfo::Expand: {
2482 // If this structure was expanded into multiple arguments then
2483 // we need to create a temporary and reconstruct it from the
2484 // arguments.
John McCall7f416cc2015-09-08 08:05:57 +00002485 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2486 LValue LV = MakeAddrLValue(Alloca, Ty);
2487 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002488
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002489 auto FnArgIter = FnArgs.begin() + FirstIRArg;
2490 ExpandTypeFromArgs(Ty, LV, FnArgIter);
2491 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
2492 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
2493 auto AI = FnArgs[FirstIRArg + i];
2494 AI->setName(Arg->getName() + "." + Twine(i));
2495 }
2496 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002497 }
2498
2499 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002500 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002501 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002502 if (!hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002503 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002504 } else {
2505 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002506 ArgVals.push_back(ParamValue::forDirect(U));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002507 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002508 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002509 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002510 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002511
Reid Kleckner739756c2013-12-04 19:23:12 +00002512 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2513 for (int I = Args.size() - 1; I >= 0; --I)
John McCall7f416cc2015-09-08 08:05:57 +00002514 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002515 } else {
2516 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall7f416cc2015-09-08 08:05:57 +00002517 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002518 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002519}
2520
John McCallffa2c1a2012-01-29 07:46:59 +00002521static void eraseUnusedBitCasts(llvm::Instruction *insn) {
2522 while (insn->use_empty()) {
2523 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
2524 if (!bitcast) return;
2525
2526 // This is "safe" because we would have used a ConstantExpr otherwise.
2527 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
2528 bitcast->eraseFromParent();
2529 }
2530}
2531
John McCall31168b02011-06-15 23:02:42 +00002532/// Try to emit a fused autorelease of a return result.
2533static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
2534 llvm::Value *result) {
2535 // We must be immediately followed the cast.
2536 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002537 if (BB->empty()) return nullptr;
2538 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002539
Chris Lattner2192fe52011-07-18 04:24:23 +00002540 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00002541
2542 // result is in a BasicBlock and is therefore an Instruction.
2543 llvm::Instruction *generator = cast<llvm::Instruction>(result);
2544
Justin Bogner882f8612016-08-18 21:46:54 +00002545 SmallVector<llvm::Instruction *, 4> InstsToKill;
John McCall31168b02011-06-15 23:02:42 +00002546
2547 // Look for:
2548 // %generator = bitcast %type1* %generator2 to %type2*
2549 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2550 // We would have emitted this as a constant if the operand weren't
2551 // an Instruction.
2552 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2553
2554 // Require the generator to be immediately followed by the cast.
2555 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00002556 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002557
Justin Bogner882f8612016-08-18 21:46:54 +00002558 InstsToKill.push_back(bitcast);
John McCall31168b02011-06-15 23:02:42 +00002559 }
2560
2561 // Look for:
2562 // %generator = call i8* @objc_retain(i8* %originalResult)
2563 // or
2564 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2565 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00002566 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002567
2568 bool doRetainAutorelease;
2569
John McCallb04ecb72015-10-21 18:06:43 +00002570 if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints().objc_retain) {
John McCall31168b02011-06-15 23:02:42 +00002571 doRetainAutorelease = true;
John McCallb04ecb72015-10-21 18:06:43 +00002572 } else if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints()
John McCall31168b02011-06-15 23:02:42 +00002573 .objc_retainAutoreleasedReturnValue) {
2574 doRetainAutorelease = false;
2575
John McCallcfa4e9b2012-09-07 23:30:50 +00002576 // If we emitted an assembly marker for this call (and the
2577 // ARCEntrypoints field should have been set if so), go looking
2578 // for that call. If we can't find it, we can't do this
2579 // optimization. But it should always be the immediately previous
2580 // instruction, unless we needed bitcasts around the call.
John McCallb04ecb72015-10-21 18:06:43 +00002581 if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
John McCallcfa4e9b2012-09-07 23:30:50 +00002582 llvm::Instruction *prev = call->getPrevNode();
2583 assert(prev);
2584 if (isa<llvm::BitCastInst>(prev)) {
2585 prev = prev->getPrevNode();
2586 assert(prev);
2587 }
2588 assert(isa<llvm::CallInst>(prev));
2589 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
John McCallb04ecb72015-10-21 18:06:43 +00002590 CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
Justin Bogner882f8612016-08-18 21:46:54 +00002591 InstsToKill.push_back(prev);
John McCallcfa4e9b2012-09-07 23:30:50 +00002592 }
John McCall31168b02011-06-15 23:02:42 +00002593 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002594 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002595 }
2596
2597 result = call->getArgOperand(0);
Justin Bogner882f8612016-08-18 21:46:54 +00002598 InstsToKill.push_back(call);
John McCall31168b02011-06-15 23:02:42 +00002599
2600 // Keep killing bitcasts, for sanity. Note that we no longer care
2601 // about precise ordering as long as there's exactly one use.
2602 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2603 if (!bitcast->hasOneUse()) break;
Justin Bogner882f8612016-08-18 21:46:54 +00002604 InstsToKill.push_back(bitcast);
John McCall31168b02011-06-15 23:02:42 +00002605 result = bitcast->getOperand(0);
2606 }
2607
2608 // Delete all the unnecessary instructions, from latest to earliest.
Justin Bogner882f8612016-08-18 21:46:54 +00002609 for (auto *I : InstsToKill)
Saleem Abdulrasoolbe25c482016-08-18 21:40:06 +00002610 I->eraseFromParent();
John McCall31168b02011-06-15 23:02:42 +00002611
2612 // Do the fused retain/autorelease if we were asked to.
2613 if (doRetainAutorelease)
2614 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2615
2616 // Cast back to the result type.
2617 return CGF.Builder.CreateBitCast(result, resultType);
2618}
2619
John McCallffa2c1a2012-01-29 07:46:59 +00002620/// If this is a +1 of the value of an immutable 'self', remove it.
2621static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2622 llvm::Value *result) {
2623 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00002624 const ObjCMethodDecl *method =
2625 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002626 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002627 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00002628 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002629
2630 // Look for a retain call.
2631 llvm::CallInst *retainCall =
2632 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2633 if (!retainCall ||
John McCallb04ecb72015-10-21 18:06:43 +00002634 retainCall->getCalledValue() != CGF.CGM.getObjCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00002635 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002636
2637 // Look for an ordinary load of 'self'.
2638 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2639 llvm::LoadInst *load =
2640 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2641 if (!load || load->isAtomic() || load->isVolatile() ||
John McCall7f416cc2015-09-08 08:05:57 +00002642 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
Craig Topper8a13c412014-05-21 05:09:00 +00002643 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002644
2645 // Okay! Burn it all down. This relies for correctness on the
2646 // assumption that the retain is emitted as part of the return and
2647 // that thereafter everything is used "linearly".
2648 llvm::Type *resultType = result->getType();
2649 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2650 assert(retainCall->use_empty());
2651 retainCall->eraseFromParent();
2652 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2653
2654 return CGF.Builder.CreateBitCast(load, resultType);
2655}
2656
John McCall31168b02011-06-15 23:02:42 +00002657/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00002658///
2659/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00002660static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2661 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00002662 // If we're returning 'self', kill the initial retain. This is a
2663 // heuristic attempt to "encourage correctness" in the really unfortunate
2664 // case where we have a return of self during a dealloc and we desperately
2665 // need to avoid the possible autorelease.
2666 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2667 return self;
2668
John McCall31168b02011-06-15 23:02:42 +00002669 // At -O0, try to emit a fused retain/autorelease.
2670 if (CGF.shouldUseFusedARCCalls())
2671 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2672 return fused;
2673
2674 return CGF.EmitARCAutoreleaseReturnValue(result);
2675}
2676
John McCall6e1c0122012-01-29 02:35:02 +00002677/// Heuristically search for a dominating store to the return-value slot.
2678static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002679 // Check if a User is a store which pointerOperand is the ReturnValue.
2680 // We are looking for stores to the ReturnValue, not for stores of the
2681 // ReturnValue to some other location.
2682 auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
2683 auto *SI = dyn_cast<llvm::StoreInst>(U);
2684 if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer())
2685 return nullptr;
2686 // These aren't actually possible for non-coerced returns, and we
2687 // only care about non-coerced returns on this code path.
2688 assert(!SI->isAtomic() && !SI->isVolatile());
2689 return SI;
2690 };
John McCall6e1c0122012-01-29 02:35:02 +00002691 // If there are multiple uses of the return-value slot, just check
2692 // for something immediately preceding the IP. Sometimes this can
2693 // happen with how we generate implicit-returns; it can also happen
2694 // with noreturn cleanups.
John McCall7f416cc2015-09-08 08:05:57 +00002695 if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
John McCall6e1c0122012-01-29 02:35:02 +00002696 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002697 if (IP->empty()) return nullptr;
David Majnemerdc012fa2015-04-22 21:38:15 +00002698 llvm::Instruction *I = &IP->back();
2699
2700 // Skip lifetime markers
2701 for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
2702 IE = IP->rend();
2703 II != IE; ++II) {
2704 if (llvm::IntrinsicInst *Intrinsic =
2705 dyn_cast<llvm::IntrinsicInst>(&*II)) {
2706 if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
2707 const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
2708 ++II;
Alexey Samsonov10544202015-06-12 21:05:32 +00002709 if (II == IE)
2710 break;
2711 if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
2712 continue;
David Majnemerdc012fa2015-04-22 21:38:15 +00002713 }
2714 }
2715 I = &*II;
2716 break;
2717 }
2718
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002719 return GetStoreIfValid(I);
John McCall6e1c0122012-01-29 02:35:02 +00002720 }
2721
2722 llvm::StoreInst *store =
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002723 GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00002724 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002725
John McCall6e1c0122012-01-29 02:35:02 +00002726 // Now do a first-and-dirty dominance check: just walk up the
2727 // single-predecessors chain from the current insertion point.
2728 llvm::BasicBlock *StoreBB = store->getParent();
2729 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2730 while (IP != StoreBB) {
2731 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00002732 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002733 }
2734
2735 // Okay, the store's basic block dominates the insertion point; we
2736 // can do our thing.
2737 return store;
2738}
2739
Adrian Prantl3be10542013-05-02 17:30:20 +00002740void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002741 bool EmitRetDbgLoc,
2742 SourceLocation EndLoc) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002743 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2744 // Naked functions don't have epilogues.
2745 Builder.CreateUnreachable();
2746 return;
2747 }
2748
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002749 // Functions with no result always return void.
John McCall7f416cc2015-09-08 08:05:57 +00002750 if (!ReturnValue.isValid()) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002751 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00002752 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002753 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00002754
Dan Gohman481e40c2010-07-20 20:13:52 +00002755 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00002756 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00002757 QualType RetTy = FI.getReturnType();
2758 const ABIArgInfo &RetAI = FI.getReturnInfo();
2759
2760 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002761 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00002762 // Aggregrates get evaluated directly into the destination. Sometimes we
2763 // need to return the sret value in a register, though.
2764 assert(hasAggregateEvaluationKind(RetTy));
2765 if (RetAI.getInAllocaSRet()) {
2766 llvm::Function::arg_iterator EI = CurFn->arg_end();
2767 --EI;
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002768 llvm::Value *ArgStruct = &*EI;
David Blaikie2e804282015-04-05 22:47:07 +00002769 llvm::Value *SRet = Builder.CreateStructGEP(
2770 nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
John McCall7f416cc2015-09-08 08:05:57 +00002771 RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret");
Reid Klecknerfab1e892014-02-25 00:59:14 +00002772 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002773 break;
2774
Daniel Dunbar03816342010-08-21 02:24:36 +00002775 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002776 auto AI = CurFn->arg_begin();
2777 if (RetAI.isSRetAfterThis())
2778 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002779 switch (getEvaluationKind(RetTy)) {
2780 case TEK_Complex: {
2781 ComplexPairTy RT =
John McCall7f416cc2015-09-08 08:05:57 +00002782 EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002783 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002784 /*isInit*/ true);
2785 break;
2786 }
2787 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002788 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002789 break;
2790 case TEK_Scalar:
2791 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002792 MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002793 /*isInit*/ true);
2794 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002795 }
2796 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002797 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002798
2799 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002800 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002801 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2802 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002803 // The internal return value temp always will have pointer-to-return-type
2804 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002805
John McCall6e1c0122012-01-29 02:35:02 +00002806 // If there is a dominating store to ReturnValue, we can elide
2807 // the load, zap the store, and usually zap the alloca.
David Majnemerdc012fa2015-04-22 21:38:15 +00002808 if (llvm::StoreInst *SI =
2809 findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002810 // Reuse the debug location from the store unless there is
2811 // cleanup code to be emitted between the store and return
2812 // instruction.
2813 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002814 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002815 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002816 RV = SI->getValueOperand();
2817 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002818
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002819 // If that was the only use of the return value, nuke it as well now.
John McCall7f416cc2015-09-08 08:05:57 +00002820 auto returnValueInst = ReturnValue.getPointer();
2821 if (returnValueInst->use_empty()) {
2822 if (auto alloca = dyn_cast<llvm::AllocaInst>(returnValueInst)) {
2823 alloca->eraseFromParent();
2824 ReturnValue = Address::invalid();
2825 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002826 }
John McCall6e1c0122012-01-29 02:35:02 +00002827
2828 // Otherwise, we have to do a simple load.
2829 } else {
2830 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002831 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002832 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002833 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00002834 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002835
John McCall7f416cc2015-09-08 08:05:57 +00002836 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002837 }
John McCall31168b02011-06-15 23:02:42 +00002838
2839 // In ARC, end functions that return a retainable type with a call
2840 // to objc_autoreleaseReturnValue.
2841 if (AutoreleaseResult) {
Akira Hatanaka9d8ac612016-02-17 21:09:50 +00002842#ifndef NDEBUG
2843 // Type::isObjCRetainabletype has to be called on a QualType that hasn't
2844 // been stripped of the typedefs, so we cannot use RetTy here. Get the
2845 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
2846 // CurCodeDecl or BlockInfo.
2847 QualType RT;
2848
2849 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
2850 RT = FD->getReturnType();
2851 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
2852 RT = MD->getReturnType();
2853 else if (isa<BlockDecl>(CurCodeDecl))
2854 RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
2855 else
2856 llvm_unreachable("Unexpected function/method type");
2857
David Blaikiebbafb8a2012-03-11 07:00:24 +00002858 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002859 !FI.isReturnsRetained() &&
Akira Hatanaka9d8ac612016-02-17 21:09:50 +00002860 RT->isObjCRetainableType());
2861#endif
John McCall31168b02011-06-15 23:02:42 +00002862 RV = emitAutoreleaseOfResult(*this, RV);
2863 }
2864
Chris Lattner726b3d02010-06-26 23:13:19 +00002865 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002866
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002867 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002868 break;
2869
John McCallf26e73d2016-03-11 04:30:43 +00002870 case ABIArgInfo::CoerceAndExpand: {
2871 auto coercionType = RetAI.getCoerceAndExpandType();
2872 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
2873
2874 // Load all of the coerced elements out into results.
2875 llvm::SmallVector<llvm::Value*, 4> results;
2876 Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType);
2877 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2878 auto coercedEltType = coercionType->getElementType(i);
2879 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
2880 continue;
2881
2882 auto eltAddr = Builder.CreateStructGEP(addr, i, layout);
2883 auto elt = Builder.CreateLoad(eltAddr);
2884 results.push_back(elt);
2885 }
2886
2887 // If we have one result, it's the single direct result type.
2888 if (results.size() == 1) {
2889 RV = results[0];
2890
2891 // Otherwise, we need to make a first-class aggregate.
2892 } else {
2893 // Construct a return type that lacks padding elements.
2894 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
2895
2896 RV = llvm::UndefValue::get(returnType);
2897 for (unsigned i = 0, e = results.size(); i != e; ++i) {
2898 RV = Builder.CreateInsertValue(RV, results[i], i);
2899 }
2900 }
2901 break;
2902 }
2903
Chris Lattner726b3d02010-06-26 23:13:19 +00002904 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002905 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002906 }
2907
Alexey Samsonovde443c52014-08-13 00:26:40 +00002908 llvm::Instruction *Ret;
2909 if (RV) {
John McCall9a2c1c92015-09-10 00:57:46 +00002910 if (CurCodeDecl && SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) {
2911 if (auto RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>()) {
Alexey Samsonov90452df2014-09-08 20:17:19 +00002912 SanitizerScope SanScope(this);
2913 llvm::Value *Cond = Builder.CreateICmpNE(
2914 RV, llvm::Constant::getNullValue(RV->getType()));
2915 llvm::Constant *StaticData[] = {
2916 EmitCheckSourceLocation(EndLoc),
2917 EmitCheckSourceLocation(RetNNAttr->getLocation()),
2918 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002919 EmitCheck(std::make_pair(Cond, SanitizerKind::ReturnsNonnullAttribute),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002920 SanitizerHandler::NonnullReturn, StaticData, None);
Alexey Samsonov90452df2014-09-08 20:17:19 +00002921 }
Alexey Samsonovde443c52014-08-13 00:26:40 +00002922 }
2923 Ret = Builder.CreateRet(RV);
2924 } else {
2925 Ret = Builder.CreateRetVoid();
2926 }
2927
Duncan P. N. Exon Smith2809cc72015-03-30 20:01:41 +00002928 if (RetDbgLoc)
Benjamin Kramer03278662015-02-07 13:15:54 +00002929 Ret->setDebugLoc(std::move(RetDbgLoc));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002930}
2931
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002932static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2933 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2934 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2935}
2936
John McCall7f416cc2015-09-08 08:05:57 +00002937static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
2938 QualType Ty) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002939 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2940 // placeholders.
2941 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
Peter Collingbourneb367c562016-11-28 22:30:21 +00002942 llvm::Type *IRPtrTy = IRTy->getPointerTo();
2943 llvm::Value *Placeholder = llvm::UndefValue::get(IRPtrTy->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +00002944
2945 // FIXME: When we generate this IR in one pass, we shouldn't need
2946 // this win32-specific alignment hack.
2947 CharUnits Align = CharUnits::fromQuantity(4);
Peter Collingbourneb367c562016-11-28 22:30:21 +00002948 Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align);
John McCall7f416cc2015-09-08 08:05:57 +00002949
2950 return AggValueSlot::forAddr(Address(Placeholder, Align),
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002951 Ty.getQualifiers(),
2952 AggValueSlot::IsNotDestructed,
2953 AggValueSlot::DoesNotNeedGCBarriers,
2954 AggValueSlot::IsNotAliased);
2955}
2956
John McCall32ea9692011-03-11 20:59:21 +00002957void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002958 const VarDecl *param,
2959 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002960 // StartFunction converted the ABI-lowered parameter(s) into a
2961 // local alloca. We need to turn that into an r-value suitable
2962 // for EmitCall.
John McCall7f416cc2015-09-08 08:05:57 +00002963 Address local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002964
John McCall32ea9692011-03-11 20:59:21 +00002965 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002966
Reid Klecknerab2090d2014-07-26 01:34:32 +00002967 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2968 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002969
John McCall811b2912016-11-18 01:08:24 +00002970 // GetAddrOfLocalVar returns a pointer-to-pointer for references,
2971 // but the argument needs to be the original pointer.
2972 if (type->isReferenceType()) {
2973 args.add(RValue::get(Builder.CreateLoad(local)), type);
2974
2975 // In ARC, move out of consumed arguments so that the release cleanup
2976 // entered by StartFunction doesn't cause an over-release. This isn't
2977 // optimal -O0 code generation, but it should get cleaned up when
2978 // optimization is enabled. This also assumes that delegate calls are
2979 // performed exactly once for a set of arguments, but that should be safe.
2980 } else if (getLangOpts().ObjCAutoRefCount &&
2981 param->hasAttr<NSConsumedAttr>() &&
2982 type->isObjCRetainableType()) {
2983 llvm::Value *ptr = Builder.CreateLoad(local);
2984 auto null =
2985 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType()));
2986 Builder.CreateStore(null, local);
2987 args.add(RValue::get(ptr), type);
2988
Richard Smithd62d4982016-06-14 01:13:21 +00002989 // For the most part, we just need to load the alloca, except that
2990 // aggregate r-values are actually pointers to temporaries.
John McCall811b2912016-11-18 01:08:24 +00002991 } else {
Richard Smithd62d4982016-06-14 01:13:21 +00002992 args.add(convertTempToRValue(local, type, loc), type);
John McCall811b2912016-11-18 01:08:24 +00002993 }
John McCall23f66262010-05-26 22:34:26 +00002994}
2995
John McCall31168b02011-06-15 23:02:42 +00002996static bool isProvablyNull(llvm::Value *addr) {
2997 return isa<llvm::ConstantPointerNull>(addr);
2998}
2999
John McCall31168b02011-06-15 23:02:42 +00003000/// Emit the actual writing-back of a writeback.
3001static void emitWriteback(CodeGenFunction &CGF,
3002 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00003003 const LValue &srcLV = writeback.Source;
John McCall7f416cc2015-09-08 08:05:57 +00003004 Address srcAddr = srcLV.getAddress();
3005 assert(!isProvablyNull(srcAddr.getPointer()) &&
John McCall31168b02011-06-15 23:02:42 +00003006 "shouldn't have writeback for provably null argument");
3007
Craig Topper8a13c412014-05-21 05:09:00 +00003008 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00003009
3010 // If the argument wasn't provably non-null, we need to null check
3011 // before doing the store.
Nick Lewyckyd9bce502016-09-20 15:49:58 +00003012 bool provablyNonNull = llvm::isKnownNonNull(srcAddr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00003013 if (!provablyNonNull) {
3014 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
3015 contBB = CGF.createBasicBlock("icr.done");
3016
John McCall7f416cc2015-09-08 08:05:57 +00003017 llvm::Value *isNull =
3018 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00003019 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
3020 CGF.EmitBlock(writebackBB);
3021 }
3022
3023 // Load the value to writeback.
3024 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
3025
3026 // Cast it back, in case we're writing an id to a Foo* or something.
John McCall7f416cc2015-09-08 08:05:57 +00003027 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
3028 "icr.writeback-cast");
John McCall31168b02011-06-15 23:02:42 +00003029
3030 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00003031
3032 // If we have a "to use" value, it's something we need to emit a use
3033 // of. This has to be carefully threaded in: if it's done after the
3034 // release it's potentially undefined behavior (and the optimizer
3035 // will ignore it), and if it happens before the retain then the
3036 // optimizer could move the release there.
3037 if (writeback.ToUse) {
3038 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
3039
3040 // Retain the new value. No need to block-copy here: the block's
3041 // being passed up the stack.
3042 value = CGF.EmitARCRetainNonBlock(value);
3043
3044 // Emit the intrinsic use here.
3045 CGF.EmitARCIntrinsicUse(writeback.ToUse);
3046
3047 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00003048 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00003049
3050 // Put the new value in place (primitively).
3051 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
3052
3053 // Release the old value.
3054 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
3055
3056 // Otherwise, we can just do a normal lvalue store.
3057 } else {
3058 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
3059 }
John McCall31168b02011-06-15 23:02:42 +00003060
3061 // Jump to the continuation block.
3062 if (!provablyNonNull)
3063 CGF.EmitBlock(contBB);
3064}
3065
3066static void emitWritebacks(CodeGenFunction &CGF,
3067 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00003068 for (const auto &I : args.writebacks())
3069 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00003070}
3071
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003072static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
3073 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00003074 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003075 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
3076 CallArgs.getCleanupsToDeactivate();
3077 // Iterate in reverse to increase the likelihood of popping the cleanup.
Pete Cooper57d3f142015-07-30 17:22:52 +00003078 for (const auto &I : llvm::reverse(Cleanups)) {
3079 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
3080 I.IsActiveIP->eraseFromParent();
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003081 }
3082}
3083
John McCalleff18842013-03-23 02:35:54 +00003084static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
3085 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
3086 if (uop->getOpcode() == UO_AddrOf)
3087 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00003088 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00003089}
3090
John McCall31168b02011-06-15 23:02:42 +00003091/// Emit an argument that's being passed call-by-writeback. That is,
John McCall7f416cc2015-09-08 08:05:57 +00003092/// we are passing the address of an __autoreleased temporary; it
3093/// might be copy-initialized with the current value of the given
3094/// address, but it will definitely be copied out of after the call.
John McCall31168b02011-06-15 23:02:42 +00003095static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
3096 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00003097 LValue srcLV;
3098
3099 // Make an optimistic effort to emit the address as an l-value.
Eric Christopher2c4555a2015-06-19 01:52:53 +00003100 // This can fail if the argument expression is more complicated.
John McCalleff18842013-03-23 02:35:54 +00003101 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
3102 srcLV = CGF.EmitLValue(lvExpr);
3103
3104 // Otherwise, just emit it as a scalar.
3105 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003106 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
John McCalleff18842013-03-23 02:35:54 +00003107
3108 QualType srcAddrType =
3109 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003110 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
John McCalleff18842013-03-23 02:35:54 +00003111 }
John McCall7f416cc2015-09-08 08:05:57 +00003112 Address srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00003113
3114 // The dest and src types don't necessarily match in LLVM terms
3115 // because of the crazy ObjC compatibility rules.
3116
Chris Lattner2192fe52011-07-18 04:24:23 +00003117 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00003118 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
3119
3120 // If the address is a constant null, just pass the appropriate null.
John McCall7f416cc2015-09-08 08:05:57 +00003121 if (isProvablyNull(srcAddr.getPointer())) {
John McCall31168b02011-06-15 23:02:42 +00003122 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
3123 CRE->getType());
3124 return;
3125 }
3126
John McCall31168b02011-06-15 23:02:42 +00003127 // Create the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003128 Address temp = CGF.CreateTempAlloca(destType->getElementType(),
3129 CGF.getPointerAlign(),
3130 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003131 // Loading an l-value can introduce a cleanup if the l-value is __weak,
3132 // and that cleanup will be conditional if we can't prove that the l-value
3133 // isn't null, so we need to register a dominating point so that the cleanups
3134 // system will make valid IR.
3135 CodeGenFunction::ConditionalEvaluation condEval(CGF);
3136
John McCall31168b02011-06-15 23:02:42 +00003137 // Zero-initialize it if we're not doing a copy-initialization.
3138 bool shouldCopy = CRE->shouldCopy();
3139 if (!shouldCopy) {
3140 llvm::Value *null =
3141 llvm::ConstantPointerNull::get(
3142 cast<llvm::PointerType>(destType->getElementType()));
3143 CGF.Builder.CreateStore(null, temp);
3144 }
Craig Topper8a13c412014-05-21 05:09:00 +00003145
3146 llvm::BasicBlock *contBB = nullptr;
3147 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00003148
3149 // If the address is *not* known to be non-null, we need to switch.
3150 llvm::Value *finalArgument;
3151
Nick Lewyckyd9bce502016-09-20 15:49:58 +00003152 bool provablyNonNull = llvm::isKnownNonNull(srcAddr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00003153 if (provablyNonNull) {
John McCall7f416cc2015-09-08 08:05:57 +00003154 finalArgument = temp.getPointer();
John McCall31168b02011-06-15 23:02:42 +00003155 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003156 llvm::Value *isNull =
3157 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00003158
3159 finalArgument = CGF.Builder.CreateSelect(isNull,
3160 llvm::ConstantPointerNull::get(destType),
John McCall7f416cc2015-09-08 08:05:57 +00003161 temp.getPointer(), "icr.argument");
John McCall31168b02011-06-15 23:02:42 +00003162
3163 // If we need to copy, then the load has to be conditional, which
3164 // means we need control flow.
3165 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00003166 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00003167 contBB = CGF.createBasicBlock("icr.cont");
3168 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
3169 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
3170 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003171 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00003172 }
3173 }
3174
Craig Topper8a13c412014-05-21 05:09:00 +00003175 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00003176
John McCall31168b02011-06-15 23:02:42 +00003177 // Perform a copy if necessary.
3178 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00003179 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00003180 assert(srcRV.isScalar());
3181
3182 llvm::Value *src = srcRV.getScalarVal();
3183 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
3184 "icr.cast");
3185
3186 // Use an ordinary store, not a store-to-lvalue.
3187 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00003188
3189 // If optimization is enabled, and the value was held in a
3190 // __strong variable, we need to tell the optimizer that this
3191 // value has to stay alive until we're doing the store back.
3192 // This is because the temporary is effectively unretained,
3193 // and so otherwise we can violate the high-level semantics.
3194 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3195 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
3196 valueToUse = src;
3197 }
John McCall31168b02011-06-15 23:02:42 +00003198 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003199
John McCall31168b02011-06-15 23:02:42 +00003200 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003201 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00003202 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00003203 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00003204
3205 // Make a phi for the value to intrinsically use.
3206 if (valueToUse) {
3207 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
3208 "icr.to-use");
3209 phiToUse->addIncoming(valueToUse, copyBB);
3210 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
3211 originBB);
3212 valueToUse = phiToUse;
3213 }
3214
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003215 condEval.end(CGF);
3216 }
John McCall31168b02011-06-15 23:02:42 +00003217
John McCalleff18842013-03-23 02:35:54 +00003218 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00003219 args.add(RValue::get(finalArgument), CRE->getType());
3220}
3221
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003222void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
Richard Smith762672a2016-09-28 19:09:10 +00003223 assert(!StackBase);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003224
3225 // Save the stack.
3226 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie43f9bb72015-05-18 22:14:03 +00003227 StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003228}
3229
Nico Weber8cdb3f92015-08-25 18:43:32 +00003230void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
3231 if (StackBase) {
Reid Kleckner7c2f9e82015-10-08 00:17:45 +00003232 // Restore the stack after the call.
Nico Weber8cdb3f92015-08-25 18:43:32 +00003233 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
Nico Weber8cdb3f92015-08-25 18:43:32 +00003234 CGF.Builder.CreateCall(F, StackBase);
3235 }
3236}
3237
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003238void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
3239 SourceLocation ArgLoc,
3240 const FunctionDecl *FD,
3241 unsigned ParmNum) {
3242 if (!SanOpts.has(SanitizerKind::NonnullAttribute) || !FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003243 return;
3244 auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
3245 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
3246 auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
3247 if (!NNAttr)
3248 return;
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003249 SanitizerScope SanScope(this);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003250 assert(RV.isScalar());
3251 llvm::Value *V = RV.getScalarVal();
3252 llvm::Value *Cond =
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003253 Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003254 llvm::Constant *StaticData[] = {
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003255 EmitCheckSourceLocation(ArgLoc),
3256 EmitCheckSourceLocation(NNAttr->getLocation()),
3257 llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003258 };
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003259 EmitCheck(std::make_pair(Cond, SanitizerKind::NonnullAttribute),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00003260 SanitizerHandler::NonnullArg, StaticData, None);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003261}
3262
David Blaikief05779e2015-07-21 18:37:18 +00003263void CodeGenFunction::EmitCallArgs(
3264 CallArgList &Args, ArrayRef<QualType> ArgTypes,
3265 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
Richard Smith762672a2016-09-28 19:09:10 +00003266 const FunctionDecl *CalleeDecl, unsigned ParamsToSkip,
Richard Smitha560ccf2016-09-29 21:30:12 +00003267 EvaluationOrder Order) {
David Blaikief05779e2015-07-21 18:37:18 +00003268 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003269
Reid Kleckner739756c2013-12-04 19:23:12 +00003270 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
Richard Smitha560ccf2016-09-29 21:30:12 +00003271 // because arguments are destroyed left to right in the callee. As a special
3272 // case, there are certain language constructs that require left-to-right
3273 // evaluation, and in those cases we consider the evaluation order requirement
3274 // to trump the "destruction order is reverse construction order" guarantee.
3275 bool LeftToRight =
3276 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()
3277 ? Order == EvaluationOrder::ForceLeftToRight
3278 : Order != EvaluationOrder::ForceRightToLeft;
3279
George Burgess IV0d6592a2017-02-23 05:59:56 +00003280 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg,
3281 RValue EmittedArg) {
3282 if (CalleeDecl == nullptr || I >= CalleeDecl->getNumParams())
3283 return;
3284 auto *PS = CalleeDecl->getParamDecl(I)->getAttr<PassObjectSizeAttr>();
3285 if (PS == nullptr)
3286 return;
3287
3288 const auto &Context = getContext();
3289 auto SizeTy = Context.getSizeType();
3290 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
3291 assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?");
3292 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T,
3293 EmittedArg.getScalarVal());
3294 Args.add(RValue::get(V), SizeTy);
3295 // If we're emitting args in reverse, be sure to do so with
3296 // pass_object_size, as well.
3297 if (!LeftToRight)
3298 std::swap(Args.back(), *(&Args.back() - 1));
3299 };
3300
Richard Smitha560ccf2016-09-29 21:30:12 +00003301 // Insert a stack save if we're going to need any inalloca args.
3302 bool HasInAllocaArgs = false;
3303 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003304 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
3305 I != E && !HasInAllocaArgs; ++I)
3306 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
3307 if (HasInAllocaArgs) {
3308 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3309 Args.allocateArgumentMemory(*this);
3310 }
Richard Smitha560ccf2016-09-29 21:30:12 +00003311 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003312
Richard Smitha560ccf2016-09-29 21:30:12 +00003313 // Evaluate each argument in the appropriate order.
3314 size_t CallArgsStart = Args.size();
3315 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
3316 unsigned Idx = LeftToRight ? I : E - I - 1;
3317 CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
George Burgess IV0d6592a2017-02-23 05:59:56 +00003318 unsigned InitialArgSize = Args.size();
Richard Smitha560ccf2016-09-29 21:30:12 +00003319 EmitCallArg(Args, *Arg, ArgTypes[Idx]);
George Burgess IV0d6592a2017-02-23 05:59:56 +00003320 // In particular, we depend on it being the last arg in Args, and the
3321 // objectsize bits depend on there only being one arg if !LeftToRight.
3322 assert(InitialArgSize + 1 == Args.size() &&
3323 "The code below depends on only adding one arg per EmitCallArg");
3324 (void)InitialArgSize;
3325 RValue RVArg = Args.back().RV;
3326 EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), CalleeDecl,
3327 ParamsToSkip + Idx);
3328 // @llvm.objectsize should never have side-effects and shouldn't need
3329 // destruction/cleanups, so we can safely "emit" it after its arg,
3330 // regardless of right-to-leftness
3331 MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
Richard Smitha560ccf2016-09-29 21:30:12 +00003332 }
Reid Kleckner739756c2013-12-04 19:23:12 +00003333
Richard Smitha560ccf2016-09-29 21:30:12 +00003334 if (!LeftToRight) {
Reid Kleckner739756c2013-12-04 19:23:12 +00003335 // Un-reverse the arguments we just evaluated so they match up with the LLVM
3336 // IR function.
3337 std::reverse(Args.begin() + CallArgsStart, Args.end());
Reid Kleckner739756c2013-12-04 19:23:12 +00003338 }
3339}
3340
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003341namespace {
3342
David Blaikie7e70d682015-08-18 22:40:54 +00003343struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +00003344 DestroyUnpassedArg(Address Addr, QualType Ty)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003345 : Addr(Addr), Ty(Ty) {}
3346
John McCall7f416cc2015-09-08 08:05:57 +00003347 Address Addr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003348 QualType Ty;
3349
Craig Topper4f12f102014-03-12 06:41:41 +00003350 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003351 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
3352 assert(!Dtor->isTrivial());
3353 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
3354 /*Delegating=*/false, Addr);
3355 }
3356};
3357
David Blaikie38b25912015-02-09 19:13:51 +00003358struct DisableDebugLocationUpdates {
3359 CodeGenFunction &CGF;
3360 bool disabledDebugInfo;
3361 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
3362 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
3363 CGF.disableDebugInfo();
3364 }
3365 ~DisableDebugLocationUpdates() {
3366 if (disabledDebugInfo)
3367 CGF.enableDebugInfo();
3368 }
3369};
3370
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00003371} // end anonymous namespace
3372
John McCall32ea9692011-03-11 20:59:21 +00003373void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
3374 QualType type) {
David Blaikie38b25912015-02-09 19:13:51 +00003375 DisableDebugLocationUpdates Dis(*this, E);
John McCall31168b02011-06-15 23:02:42 +00003376 if (const ObjCIndirectCopyRestoreExpr *CRE
3377 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00003378 assert(getLangOpts().ObjCAutoRefCount);
Vedant Kumar30914f32016-10-03 15:29:22 +00003379 assert(getContext().hasSameUnqualifiedType(E->getType(), type));
John McCall31168b02011-06-15 23:02:42 +00003380 return emitWritebackArg(*this, args, CRE);
3381 }
3382
John McCall0a76c0c2011-08-26 18:42:59 +00003383 assert(type->isReferenceType() == E->isGLValue() &&
3384 "reference binding to unmaterialized r-value!");
3385
John McCall17054bd62011-08-26 21:08:13 +00003386 if (E->isGLValue()) {
3387 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00003388 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00003389 }
Mike Stump11289f42009-09-09 15:08:12 +00003390
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003391 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
3392
3393 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
3394 // However, we still have to push an EH-only cleanup in case we unwind before
3395 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00003396 if (HasAggregateEvalKind &&
3397 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
3398 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00003399 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00003400 AggValueSlot Slot;
3401 if (args.isUsingInAlloca())
3402 Slot = createPlaceholderSlot(*this, type);
3403 else
3404 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00003405
3406 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
3407 bool DestroyedInCallee =
3408 RD && RD->hasNonTrivialDestructor() &&
3409 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
3410 if (DestroyedInCallee)
3411 Slot.setExternallyDestructed();
3412
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003413 EmitAggExpr(E, Slot);
3414 RValue RV = Slot.asRValue();
3415 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003416
Reid Klecknere39ee212014-05-03 00:33:28 +00003417 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003418 // Create a no-op GEP between the placeholder and the cleanup so we can
3419 // RAUW it successfully. It also serves as a marker of the first
3420 // instruction where the cleanup is active.
John McCall7f416cc2015-09-08 08:05:57 +00003421 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
3422 type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003423 // This unreachable is a temporary marker which will be removed later.
3424 llvm::Instruction *IsActive = Builder.CreateUnreachable();
3425 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003426 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003427 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003428 }
3429
3430 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00003431 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
3432 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
3433 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00003434 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
3435 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
3436 } else {
3437 // We can't represent a misaligned lvalue in the CallArgList, so copy
3438 // to an aligned temporary now.
John McCall7f416cc2015-09-08 08:05:57 +00003439 Address tmp = CreateMemTemp(type);
3440 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile());
Eli Friedman61f615a2013-06-11 01:08:22 +00003441 args.add(RValue::getAggregate(tmp), type);
3442 }
Eli Friedmandf968192011-05-26 00:10:27 +00003443 return;
3444 }
3445
John McCall32ea9692011-03-11 20:59:21 +00003446 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00003447}
3448
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003449QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
3450 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
3451 // implicitly widens null pointer constants that are arguments to varargs
3452 // functions to pointer-sized ints.
3453 if (!getTarget().getTriple().isOSWindows())
3454 return Arg->getType();
3455
3456 if (Arg->getType()->isIntegerType() &&
3457 getContext().getTypeSize(Arg->getType()) <
3458 getContext().getTargetInfo().getPointerWidth(0) &&
3459 Arg->isNullPointerConstant(getContext(),
3460 Expr::NPC_ValueDependentIsNotNull)) {
3461 return getContext().getIntPtrType();
3462 }
3463
3464 return Arg->getType();
3465}
3466
Dan Gohman515a60d2012-02-16 00:57:37 +00003467// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3468// optimizer it can aggressively ignore unwind edges.
3469void
3470CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
3471 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3472 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
3473 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
3474 CGM.getNoObjCARCExceptionsMetadata());
3475}
3476
John McCall882987f2013-02-28 19:01:20 +00003477/// Emits a call to the given no-arguments nounwind runtime function.
3478llvm::CallInst *
3479CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3480 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003481 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003482}
3483
3484/// Emits a call to the given nounwind runtime function.
3485llvm::CallInst *
3486CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3487 ArrayRef<llvm::Value*> args,
3488 const llvm::Twine &name) {
3489 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
3490 call->setDoesNotThrow();
3491 return call;
3492}
3493
3494/// Emits a simple call (never an invoke) to the given no-arguments
3495/// runtime function.
3496llvm::CallInst *
3497CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3498 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003499 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003500}
3501
David Majnemer0b17d442015-12-15 21:27:59 +00003502// Calls which may throw must have operand bundles indicating which funclet
3503// they are nested within.
3504static void
Sanjay Patel846b63b2016-01-18 22:15:33 +00003505getBundlesForFunclet(llvm::Value *Callee, llvm::Instruction *CurrentFuncletPad,
David Majnemer0b17d442015-12-15 21:27:59 +00003506 SmallVectorImpl<llvm::OperandBundleDef> &BundleList) {
Sanjay Patel846b63b2016-01-18 22:15:33 +00003507 // There is no need for a funclet operand bundle if we aren't inside a
3508 // funclet.
David Majnemer0b17d442015-12-15 21:27:59 +00003509 if (!CurrentFuncletPad)
3510 return;
3511
3512 // Skip intrinsics which cannot throw.
3513 auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts());
3514 if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow())
3515 return;
3516
3517 BundleList.emplace_back("funclet", CurrentFuncletPad);
3518}
3519
David Majnemer971d31b2016-02-24 17:02:45 +00003520/// Emits a simple call (never an invoke) to the given runtime function.
3521llvm::CallInst *
3522CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3523 ArrayRef<llvm::Value*> args,
3524 const llvm::Twine &name) {
3525 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3526 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList);
3527
3528 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList, name);
3529 call->setCallingConv(getRuntimeCC());
3530 return call;
3531}
3532
John McCall882987f2013-02-28 19:01:20 +00003533/// Emits a call or invoke to the given noreturn runtime function.
3534void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
3535 ArrayRef<llvm::Value*> args) {
David Majnemer0b17d442015-12-15 21:27:59 +00003536 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3537 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList);
3538
John McCall882987f2013-02-28 19:01:20 +00003539 if (getInvokeDest()) {
3540 llvm::InvokeInst *invoke =
3541 Builder.CreateInvoke(callee,
3542 getUnreachableBlock(),
3543 getInvokeDest(),
David Majnemer0b17d442015-12-15 21:27:59 +00003544 args,
3545 BundleList);
John McCall882987f2013-02-28 19:01:20 +00003546 invoke->setDoesNotReturn();
3547 invoke->setCallingConv(getRuntimeCC());
3548 } else {
David Majnemer0b17d442015-12-15 21:27:59 +00003549 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
John McCall882987f2013-02-28 19:01:20 +00003550 call->setDoesNotReturn();
3551 call->setCallingConv(getRuntimeCC());
3552 Builder.CreateUnreachable();
3553 }
3554}
3555
Sanjay Patel846b63b2016-01-18 22:15:33 +00003556/// Emits a call or invoke instruction to the given nullary runtime function.
John McCall882987f2013-02-28 19:01:20 +00003557llvm::CallSite
3558CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3559 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003560 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003561}
3562
3563/// Emits a call or invoke instruction to the given runtime function.
3564llvm::CallSite
3565CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3566 ArrayRef<llvm::Value*> args,
3567 const Twine &name) {
3568 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
3569 callSite.setCallingConv(getRuntimeCC());
3570 return callSite;
3571}
3572
John McCallbd309292010-07-06 01:34:17 +00003573/// Emits a call or invoke instruction to the given function, depending
3574/// on the current state of the EH stack.
3575llvm::CallSite
3576CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00003577 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003578 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00003579 llvm::BasicBlock *InvokeDest = getInvokeDest();
David Majnemer3df77bc2016-01-26 23:14:47 +00003580 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3581 getBundlesForFunclet(Callee, CurrentFuncletPad, BundleList);
John McCallbd309292010-07-06 01:34:17 +00003582
Dan Gohman515a60d2012-02-16 00:57:37 +00003583 llvm::Instruction *Inst;
3584 if (!InvokeDest)
David Majnemer3df77bc2016-01-26 23:14:47 +00003585 Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
Dan Gohman515a60d2012-02-16 00:57:37 +00003586 else {
3587 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
David Majnemer3df77bc2016-01-26 23:14:47 +00003588 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
3589 Name);
Dan Gohman515a60d2012-02-16 00:57:37 +00003590 EmitBlock(ContBB);
3591 }
3592
3593 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3594 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003595 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003596 AddObjCARCExceptionMetadata(Inst);
3597
Benjamin Kramerc19cde12015-04-10 14:49:31 +00003598 return llvm::CallSite(Inst);
John McCallbd309292010-07-06 01:34:17 +00003599}
3600
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003601/// \brief Store a non-aggregate value to an address to initialize it. For
3602/// initialization, a non-atomic store will be used.
3603static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
3604 LValue Dst) {
3605 if (Src.isScalar())
3606 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
3607 else
3608 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
3609}
3610
3611void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
3612 llvm::Value *New) {
3613 DeferredReplacements.push_back(std::make_pair(Old, New));
3614}
Chris Lattnerd59d8672011-07-12 06:29:11 +00003615
Daniel Dunbard931a872009-02-02 22:03:45 +00003616RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
John McCallb92ab1a2016-10-26 23:46:34 +00003617 const CGCallee &Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00003618 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003619 const CallArgList &CallArgs,
David Chisnallff5f88c2010-05-02 13:41:58 +00003620 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00003621 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00003622
John McCallb92ab1a2016-10-26 23:46:34 +00003623 assert(Callee.isOrdinary());
3624
Daniel Dunbar613855c2008-09-09 23:27:19 +00003625 // Handle struct-return functions by passing a pointer to the
3626 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00003627 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003628 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003629
John McCallb92ab1a2016-10-26 23:46:34 +00003630 llvm::FunctionType *IRFuncTy = Callee.getFunctionType();
3631
3632 // 1. Set up the arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003633
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003634 // If we're using inalloca, insert the allocation after the stack save.
3635 // FIXME: Do this earlier rather than hacking it in here!
John McCall7f416cc2015-09-08 08:05:57 +00003636 Address ArgMemory = Address::invalid();
3637 const llvm::StructLayout *ArgMemoryLayout = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003638 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
John McCall7f416cc2015-09-08 08:05:57 +00003639 ArgMemoryLayout = CGM.getDataLayout().getStructLayout(ArgStruct);
Reid Kleckner9df1d972014-04-10 01:40:15 +00003640 llvm::Instruction *IP = CallArgs.getStackBase();
3641 llvm::AllocaInst *AI;
3642 if (IP) {
3643 IP = IP->getNextNode();
3644 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
3645 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00003646 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00003647 }
John McCall7f416cc2015-09-08 08:05:57 +00003648 auto Align = CallInfo.getArgStructAlignment();
3649 AI->setAlignment(Align.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003650 AI->setUsedWithInAlloca(true);
3651 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
John McCall7f416cc2015-09-08 08:05:57 +00003652 ArgMemory = Address(AI, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003653 }
3654
John McCall7f416cc2015-09-08 08:05:57 +00003655 // Helper function to drill into the inalloca allocation.
3656 auto createInAllocaStructGEP = [&](unsigned FieldIndex) -> Address {
3657 auto FieldOffset =
3658 CharUnits::fromQuantity(ArgMemoryLayout->getElementOffset(FieldIndex));
3659 return Builder.CreateStructGEP(ArgMemory, FieldIndex, FieldOffset);
3660 };
3661
Alexey Samsonov153004f2014-09-29 22:08:00 +00003662 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003663 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
3664
Chris Lattner4ca97c32009-06-13 00:26:38 +00003665 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00003666 // alloca to hold the result, unless one is given to us.
John McCall7f416cc2015-09-08 08:05:57 +00003667 Address SRetPtr = Address::invalid();
Leny Kholodov6aab1112015-06-08 10:23:49 +00003668 size_t UnusedReturnSize = 0;
John McCallf26e73d2016-03-11 04:30:43 +00003669 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
John McCall7f416cc2015-09-08 08:05:57 +00003670 if (!ReturnValue.isNull()) {
3671 SRetPtr = ReturnValue.getValue();
3672 } else {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003673 SRetPtr = CreateMemTemp(RetTy);
Leny Kholodov6aab1112015-06-08 10:23:49 +00003674 if (HaveInsertPoint() && ReturnValue.isUnused()) {
3675 uint64_t size =
3676 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
John McCall7f416cc2015-09-08 08:05:57 +00003677 if (EmitLifetimeStart(size, SRetPtr.getPointer()))
Leny Kholodov6aab1112015-06-08 10:23:49 +00003678 UnusedReturnSize = size;
3679 }
3680 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003681 if (IRFunctionArgs.hasSRetArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00003682 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
John McCallf26e73d2016-03-11 04:30:43 +00003683 } else if (RetAI.isInAlloca()) {
John McCall7f416cc2015-09-08 08:05:57 +00003684 Address Addr = createInAllocaStructGEP(RetAI.getInAllocaFieldIndex());
3685 Builder.CreateStore(SRetPtr.getPointer(), Addr);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003686 }
Anders Carlsson17490832009-12-24 20:40:36 +00003687 }
Mike Stump11289f42009-09-09 15:08:12 +00003688
John McCall12f23522016-04-04 18:33:08 +00003689 Address swiftErrorTemp = Address::invalid();
3690 Address swiftErrorArg = Address::invalid();
3691
John McCallb92ab1a2016-10-26 23:46:34 +00003692 // Translate all of the arguments as necessary to match the IR lowering.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00003693 assert(CallInfo.arg_size() == CallArgs.size() &&
3694 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003695 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003696 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00003697 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003698 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003699 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003700 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003701
Rafael Espindolafad28de2012-10-24 01:59:00 +00003702 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003703 if (IRFunctionArgs.hasPaddingArg(ArgNo))
3704 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
3705 llvm::UndefValue::get(ArgInfo.getPaddingType());
3706
3707 unsigned FirstIRArg, NumIRArgs;
3708 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003709
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003710 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003711 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003712 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003713 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3714 if (RV.isAggregate()) {
3715 // Replace the placeholder with the appropriate argument slot GEP.
3716 llvm::Instruction *Placeholder =
John McCall7f416cc2015-09-08 08:05:57 +00003717 cast<llvm::Instruction>(RV.getAggregatePointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003718 CGBuilderTy::InsertPoint IP = Builder.saveIP();
3719 Builder.SetInsertPoint(Placeholder);
John McCall7f416cc2015-09-08 08:05:57 +00003720 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003721 Builder.restoreIP(IP);
John McCall7f416cc2015-09-08 08:05:57 +00003722 deferPlaceholderReplacement(Placeholder, Addr.getPointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003723 } else {
3724 // Store the RValue into the argument struct.
John McCall7f416cc2015-09-08 08:05:57 +00003725 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
3726 unsigned AS = Addr.getType()->getPointerAddressSpace();
David Majnemer32b57b02014-03-31 16:12:47 +00003727 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3728 // There are some cases where a trivial bitcast is not avoidable. The
3729 // definition of a type later in a translation unit may change it's type
3730 // from {}* to (%struct.foo*)*.
John McCall7f416cc2015-09-08 08:05:57 +00003731 if (Addr.getType() != MemType)
David Majnemer32b57b02014-03-31 16:12:47 +00003732 Addr = Builder.CreateBitCast(Addr, MemType);
John McCall7f416cc2015-09-08 08:05:57 +00003733 LValue argLV = MakeAddrLValue(Addr, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003734 EmitInitStoreOfNonAggregate(*this, RV, argLV);
3735 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003736 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003737 }
3738
Daniel Dunbar03816342010-08-21 02:24:36 +00003739 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003740 assert(NumIRArgs == 1);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003741 if (RV.isScalar() || RV.isComplex()) {
3742 // Make a temporary alloca to pass the argument.
John McCall7f416cc2015-09-08 08:05:57 +00003743 Address Addr = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3744 IRCallArgs[FirstIRArg] = Addr.getPointer();
John McCall47fb9502013-03-07 21:37:08 +00003745
John McCall7f416cc2015-09-08 08:05:57 +00003746 LValue argLV = MakeAddrLValue(Addr, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003747 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003748 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003749 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00003750 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003751 // 1. If the argument is not byval, and we are required to copy the
3752 // source. (This case doesn't occur on any common architecture.)
3753 // 2. If the argument is byval, RV is not sufficiently aligned, and
3754 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00003755 // 3. If the argument is byval, but RV is located in an address space
3756 // different than that of the argument (0).
John McCall7f416cc2015-09-08 08:05:57 +00003757 Address Addr = RV.getAggregateAddress();
3758 CharUnits Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003759 const llvm::DataLayout *TD = &CGM.getDataLayout();
John McCall7f416cc2015-09-08 08:05:57 +00003760 const unsigned RVAddrSpace = Addr.getType()->getAddressSpace();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003761 const unsigned ArgAddrSpace =
3762 (FirstIRArg < IRFuncTy->getNumParams()
3763 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
3764 : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00003765 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall7f416cc2015-09-08 08:05:57 +00003766 (ArgInfo.getIndirectByVal() && Addr.getAlignment() < Align &&
3767 llvm::getOrEnforceKnownAlignment(Addr.getPointer(),
3768 Align.getQuantity(), *TD)
3769 < Align.getQuantity()) ||
Mehdi Aminib3d52092015-03-10 02:36:43 +00003770 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003771 // Create an aligned temporary, and copy to it.
John McCall7f416cc2015-09-08 08:05:57 +00003772 Address AI = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3773 IRCallArgs[FirstIRArg] = AI.getPointer();
Chad Rosier615ed1a2012-03-29 17:37:10 +00003774 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003775 } else {
3776 // Skip the extra memcpy call.
John McCall7f416cc2015-09-08 08:05:57 +00003777 IRCallArgs[FirstIRArg] = Addr.getPointer();
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003778 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003779 }
3780 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00003781 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003782
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003783 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003784 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003785 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003786
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003787 case ABIArgInfo::Extend:
3788 case ABIArgInfo::Direct: {
3789 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003790 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3791 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003792 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003793 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003794 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003795 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003796 else
John McCall7f416cc2015-09-08 08:05:57 +00003797 V = Builder.CreateLoad(RV.getAggregateAddress());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003798
John McCall12f23522016-04-04 18:33:08 +00003799 // Implement swifterror by copying into a new swifterror argument.
3800 // We'll write back in the normal path out of the call.
3801 if (CallInfo.getExtParameterInfo(ArgNo).getABI()
3802 == ParameterABI::SwiftErrorResult) {
3803 assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
3804
3805 QualType pointeeTy = I->Ty->getPointeeType();
3806 swiftErrorArg =
3807 Address(V, getContext().getTypeAlignInChars(pointeeTy));
3808
3809 swiftErrorTemp =
3810 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
3811 V = swiftErrorTemp.getPointer();
3812 cast<llvm::AllocaInst>(V)->setSwiftError(true);
3813
3814 llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
3815 Builder.CreateStore(errorValue, swiftErrorTemp);
3816 }
3817
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003818 // We might have to widen integers, but we should never truncate.
3819 if (ArgInfo.getCoerceToType() != V->getType() &&
3820 V->getType()->isIntegerTy())
3821 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
3822
Chris Lattner3ce86682011-07-12 04:53:39 +00003823 // If the argument doesn't match, perform a bitcast to coerce it. This
3824 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003825 if (FirstIRArg < IRFuncTy->getNumParams() &&
3826 V->getType() != IRFuncTy->getParamType(FirstIRArg))
3827 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
John McCall12f23522016-04-04 18:33:08 +00003828
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003829 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003830 break;
3831 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003832
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003833 // FIXME: Avoid the conversion through memory if possible.
John McCall7f416cc2015-09-08 08:05:57 +00003834 Address Src = Address::invalid();
John McCall47fb9502013-03-07 21:37:08 +00003835 if (RV.isScalar() || RV.isComplex()) {
John McCall7f416cc2015-09-08 08:05:57 +00003836 Src = CreateMemTemp(I->Ty, "coerce");
3837 LValue SrcLV = MakeAddrLValue(Src, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003838 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00003839 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003840 Src = RV.getAggregateAddress();
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00003841 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003842
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003843 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00003844 Src = emitAddressAtOffset(*this, Src, ArgInfo);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003845
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003846 // Fast-isel and the optimizer generally like scalar values better than
3847 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00003848 llvm::StructType *STy =
3849 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003850 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
John McCall7f416cc2015-09-08 08:05:57 +00003851 llvm::Type *SrcTy = Src.getType()->getElementType();
Chandler Carrutha6399a52012-10-10 11:29:08 +00003852 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
3853 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
3854
3855 // If the source type is smaller than the destination type of the
3856 // coerce-to logic, copy the source value into a temp alloca the size
3857 // of the destination type to allow loading all of it. The bits past
3858 // the source value are left undef.
3859 if (SrcSize < DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00003860 Address TempAlloca
3861 = CreateTempAlloca(STy, Src.getAlignment(),
3862 Src.getName() + ".coerce");
3863 Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
3864 Src = TempAlloca;
Chandler Carrutha6399a52012-10-10 11:29:08 +00003865 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003866 Src = Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(STy));
Chandler Carrutha6399a52012-10-10 11:29:08 +00003867 }
3868
John McCall7f416cc2015-09-08 08:05:57 +00003869 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003870 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00003871 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00003872 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
3873 Address EltPtr = Builder.CreateStructGEP(Src, i, Offset);
3874 llvm::Value *LI = Builder.CreateLoad(EltPtr);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003875 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00003876 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00003877 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00003878 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003879 assert(NumIRArgs == 1);
3880 IRCallArgs[FirstIRArg] =
John McCall7f416cc2015-09-08 08:05:57 +00003881 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00003882 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003883
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003884 break;
3885 }
3886
John McCallf26e73d2016-03-11 04:30:43 +00003887 case ABIArgInfo::CoerceAndExpand: {
John McCallf26e73d2016-03-11 04:30:43 +00003888 auto coercionType = ArgInfo.getCoerceAndExpandType();
3889 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
3890
John McCall12f23522016-04-04 18:33:08 +00003891 llvm::Value *tempSize = nullptr;
3892 Address addr = Address::invalid();
3893 if (RV.isAggregate()) {
3894 addr = RV.getAggregateAddress();
3895 } else {
3896 assert(RV.isScalar()); // complex should always just be direct
3897
3898 llvm::Type *scalarType = RV.getScalarVal()->getType();
3899 auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
3900 auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType);
3901
3902 tempSize = llvm::ConstantInt::get(CGM.Int64Ty, scalarSize);
3903
3904 // Materialize to a temporary.
3905 addr = CreateTempAlloca(RV.getScalarVal()->getType(),
3906 CharUnits::fromQuantity(std::max(layout->getAlignment(),
3907 scalarAlign)));
3908 EmitLifetimeStart(scalarSize, addr.getPointer());
3909
3910 Builder.CreateStore(RV.getScalarVal(), addr);
3911 }
3912
John McCallf26e73d2016-03-11 04:30:43 +00003913 addr = Builder.CreateElementBitCast(addr, coercionType);
3914
3915 unsigned IRArgPos = FirstIRArg;
3916 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3917 llvm::Type *eltType = coercionType->getElementType(i);
3918 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
3919 Address eltAddr = Builder.CreateStructGEP(addr, i, layout);
3920 llvm::Value *elt = Builder.CreateLoad(eltAddr);
3921 IRCallArgs[IRArgPos++] = elt;
3922 }
3923 assert(IRArgPos == FirstIRArg + NumIRArgs);
3924
John McCall12f23522016-04-04 18:33:08 +00003925 if (tempSize) {
3926 EmitLifetimeEnd(tempSize, addr.getPointer());
3927 }
3928
John McCallf26e73d2016-03-11 04:30:43 +00003929 break;
3930 }
3931
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003932 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003933 unsigned IRArgPos = FirstIRArg;
3934 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
3935 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003936 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003937 }
3938 }
Mike Stump11289f42009-09-09 15:08:12 +00003939
John McCallb92ab1a2016-10-26 23:46:34 +00003940 llvm::Value *CalleePtr = Callee.getFunctionPointer();
3941
3942 // If we're using inalloca, set up that argument.
John McCall7f416cc2015-09-08 08:05:57 +00003943 if (ArgMemory.isValid()) {
3944 llvm::Value *Arg = ArgMemory.getPointer();
Reid Klecknerafba553e2014-07-08 02:24:27 +00003945 if (CallInfo.isVariadic()) {
3946 // When passing non-POD arguments by value to variadic functions, we will
3947 // end up with a variadic prototype and an inalloca call site. In such
3948 // cases, we can't do any parameter mismatch checks. Give up and bitcast
3949 // the callee.
John McCallb92ab1a2016-10-26 23:46:34 +00003950 unsigned CalleeAS = CalleePtr->getType()->getPointerAddressSpace();
3951 auto FnTy = getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS);
3952 CalleePtr = Builder.CreateBitCast(CalleePtr, FnTy);
Reid Klecknerafba553e2014-07-08 02:24:27 +00003953 } else {
3954 llvm::Type *LastParamTy =
3955 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
3956 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003957#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00003958 // Assert that these structs have equivalent element types.
3959 llvm::StructType *FullTy = CallInfo.getArgStruct();
3960 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3961 cast<llvm::PointerType>(LastParamTy)->getElementType());
3962 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3963 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3964 DE = DeclaredTy->element_end(),
3965 FI = FullTy->element_begin();
3966 DI != DE; ++DI, ++FI)
3967 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003968#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00003969 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3970 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003971 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003972 assert(IRFunctionArgs.hasInallocaArg());
3973 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003974 }
3975
John McCallb92ab1a2016-10-26 23:46:34 +00003976 // 2. Prepare the function pointer.
3977
3978 // If the callee is a bitcast of a non-variadic function to have a
3979 // variadic function pointer type, check to see if we can remove the
3980 // bitcast. This comes up with unprototyped functions.
3981 //
3982 // This makes the IR nicer, but more importantly it ensures that we
3983 // can inline the function at -O0 if it is marked always_inline.
3984 auto simplifyVariadicCallee = [](llvm::Value *Ptr) -> llvm::Value* {
3985 llvm::FunctionType *CalleeFT =
3986 cast<llvm::FunctionType>(Ptr->getType()->getPointerElementType());
3987 if (!CalleeFT->isVarArg())
3988 return Ptr;
3989
3990 llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr);
3991 if (!CE || CE->getOpcode() != llvm::Instruction::BitCast)
3992 return Ptr;
3993
3994 llvm::Function *OrigFn = dyn_cast<llvm::Function>(CE->getOperand(0));
3995 if (!OrigFn)
3996 return Ptr;
3997
3998 llvm::FunctionType *OrigFT = OrigFn->getFunctionType();
3999
4000 // If the original type is variadic, or if any of the component types
4001 // disagree, we cannot remove the cast.
4002 if (OrigFT->isVarArg() ||
4003 OrigFT->getNumParams() != CalleeFT->getNumParams() ||
4004 OrigFT->getReturnType() != CalleeFT->getReturnType())
4005 return Ptr;
4006
4007 for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i)
4008 if (OrigFT->getParamType(i) != CalleeFT->getParamType(i))
4009 return Ptr;
4010
4011 return OrigFn;
4012 };
4013 CalleePtr = simplifyVariadicCallee(CalleePtr);
4014
4015 // 3. Perform the actual call.
4016
4017 // Deactivate any cleanups that we're supposed to do immediately before
4018 // the call.
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00004019 if (!CallArgs.getCleanupsToDeactivate().empty())
4020 deactivateArgCleanupsBeforeCall(*this, CallArgs);
4021
John McCallb92ab1a2016-10-26 23:46:34 +00004022 // Assert that the arguments we computed match up. The IR verifier
4023 // will catch this, but this is a common enough source of problems
4024 // during IRGen changes that it's way better for debugging to catch
4025 // it ourselves here.
4026#ifndef NDEBUG
Alexey Samsonov91cf4552014-08-22 01:06:06 +00004027 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
4028 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
4029 // Inalloca argument can have different type.
4030 if (IRFunctionArgs.hasInallocaArg() &&
4031 i == IRFunctionArgs.getInallocaArgNo())
4032 continue;
4033 if (i < IRFuncTy->getNumParams())
4034 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
4035 }
John McCallb92ab1a2016-10-26 23:46:34 +00004036#endif
Alexey Samsonov91cf4552014-08-22 01:06:06 +00004037
John McCallb92ab1a2016-10-26 23:46:34 +00004038 // Compute the calling convention and attributes.
Daniel Dunbar0ef34792009-09-12 00:59:20 +00004039 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00004040 CodeGen::AttributeListType AttributeList;
John McCallb92ab1a2016-10-26 23:46:34 +00004041 CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo,
4042 Callee.getAbstractInfo(),
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00004043 AttributeList, CallingConv,
4044 /*AttrOnCallSite=*/true);
Bill Wendling3087d022012-12-07 23:17:26 +00004045 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00004046 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00004047
John McCallb92ab1a2016-10-26 23:46:34 +00004048 // Apply some call-site-specific attributes.
4049 // TODO: work this into building the attribute set.
4050
4051 // Apply always_inline to all calls within flatten functions.
4052 // FIXME: should this really take priority over __try, below?
4053 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
4054 !(Callee.getAbstractInfo().getCalleeDecl() &&
4055 Callee.getAbstractInfo().getCalleeDecl()->hasAttr<NoInlineAttr>())) {
4056 Attrs =
4057 Attrs.addAttribute(getLLVMContext(),
4058 llvm::AttributeSet::FunctionIndex,
4059 llvm::Attribute::AlwaysInline);
4060 }
4061
4062 // Disable inlining inside SEH __try blocks.
4063 if (isSEHTryScope()) {
4064 Attrs =
4065 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
4066 llvm::Attribute::NoInline);
4067 }
4068
4069 // Decide whether to use a call or an invoke.
David Majnemer4e52d6f2015-12-12 05:39:21 +00004070 bool CannotThrow;
4071 if (currentFunctionUsesSEHTry()) {
John McCallb92ab1a2016-10-26 23:46:34 +00004072 // SEH cares about asynchronous exceptions, so everything can "throw."
David Majnemer4e52d6f2015-12-12 05:39:21 +00004073 CannotThrow = false;
4074 } else if (isCleanupPadScope() &&
4075 EHPersonality::get(*this).isMSVCXXPersonality()) {
4076 // The MSVC++ personality will implicitly terminate the program if an
John McCallb92ab1a2016-10-26 23:46:34 +00004077 // exception is thrown during a cleanup outside of a try/catch.
4078 // We don't need to model anything in IR to get this behavior.
David Majnemer4e52d6f2015-12-12 05:39:21 +00004079 CannotThrow = true;
4080 } else {
John McCallb92ab1a2016-10-26 23:46:34 +00004081 // Otherwise, nounwind call sites will never throw.
David Majnemer4e52d6f2015-12-12 05:39:21 +00004082 CannotThrow = Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
4083 llvm::Attribute::NoUnwind);
4084 }
4085 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00004086
David Majnemer0b17d442015-12-15 21:27:59 +00004087 SmallVector<llvm::OperandBundleDef, 1> BundleList;
John McCallb92ab1a2016-10-26 23:46:34 +00004088 getBundlesForFunclet(CalleePtr, CurrentFuncletPad, BundleList);
David Majnemer0b17d442015-12-15 21:27:59 +00004089
John McCallb92ab1a2016-10-26 23:46:34 +00004090 // Emit the actual call/invoke instruction.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004091 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00004092 if (!InvokeDest) {
John McCallb92ab1a2016-10-26 23:46:34 +00004093 CS = Builder.CreateCall(CalleePtr, IRCallArgs, BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00004094 } else {
4095 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
John McCallb92ab1a2016-10-26 23:46:34 +00004096 CS = Builder.CreateInvoke(CalleePtr, Cont, InvokeDest, IRCallArgs,
David Majnemer0b17d442015-12-15 21:27:59 +00004097 BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00004098 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00004099 }
John McCallb92ab1a2016-10-26 23:46:34 +00004100 llvm::Instruction *CI = CS.getInstruction();
Chris Lattnere70a0072010-06-29 16:40:28 +00004101 if (callOrInvoke)
John McCallb92ab1a2016-10-26 23:46:34 +00004102 *callOrInvoke = CI;
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00004103
John McCallb92ab1a2016-10-26 23:46:34 +00004104 // Apply the attributes and calling convention.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004105 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00004106 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004107
John McCallb92ab1a2016-10-26 23:46:34 +00004108 // Apply various metadata.
4109
4110 if (!CI->getType()->isVoidTy())
4111 CI->setName("call");
4112
Adam Nemet1e217bc2016-03-28 22:18:53 +00004113 // Insert instrumentation or attach profile metadata at indirect call sites.
4114 // For more details, see the comment before the definition of
4115 // IPVK_IndirectCallTarget in InstrProfData.inc.
Betul Buyukkurt518276a2016-01-23 22:50:44 +00004116 if (!CS.getCalledFunction())
4117 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
John McCallb92ab1a2016-10-26 23:46:34 +00004118 CI, CalleePtr);
Betul Buyukkurt518276a2016-01-23 22:50:44 +00004119
Dan Gohman515a60d2012-02-16 00:57:37 +00004120 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4121 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004122 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallb92ab1a2016-10-26 23:46:34 +00004123 AddObjCARCExceptionMetadata(CI);
4124
4125 // Suppress tail calls if requested.
4126 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
4127 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl();
4128 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
4129 Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
4130 }
4131
4132 // 4. Finish the call.
Dan Gohman515a60d2012-02-16 00:57:37 +00004133
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004134 // If the call doesn't return, finish the basic block and clear the
John McCallb92ab1a2016-10-26 23:46:34 +00004135 // insertion point; this allows the rest of IRGen to discard
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004136 // unreachable code.
4137 if (CS.doesNotReturn()) {
Leny Kholodov6aab1112015-06-08 10:23:49 +00004138 if (UnusedReturnSize)
4139 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
John McCall7f416cc2015-09-08 08:05:57 +00004140 SRetPtr.getPointer());
Leny Kholodov6aab1112015-06-08 10:23:49 +00004141
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004142 Builder.CreateUnreachable();
4143 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00004144
Mike Stump18bb9282009-05-16 07:57:57 +00004145 // FIXME: For now, emit a dummy basic block because expr emitters in
4146 // generally are not ready to handle emitting expressions at unreachable
4147 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004148 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00004149
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004150 // Return a reasonable RValue.
4151 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00004152 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004153
John McCall12f23522016-04-04 18:33:08 +00004154 // Perform the swifterror writeback.
4155 if (swiftErrorTemp.isValid()) {
4156 llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
4157 Builder.CreateStore(errorResult, swiftErrorArg);
4158 }
4159
John McCallb92ab1a2016-10-26 23:46:34 +00004160 // Emit any call-associated writebacks immediately. Arguably this
4161 // should happen after any return-value munging.
John McCall31168b02011-06-15 23:02:42 +00004162 if (CallArgs.hasWritebacks())
4163 emitWritebacks(*this, CallArgs);
4164
Nico Weber8cdb3f92015-08-25 18:43:32 +00004165 // The stack cleanup for inalloca arguments has to run out of the normal
4166 // lexical order, so deactivate it and run it manually here.
4167 CallArgs.freeArgumentMemory(*this);
4168
John McCallb92ab1a2016-10-26 23:46:34 +00004169 // Extract the return value.
Hal Finkelee90a222014-09-26 05:04:30 +00004170 RValue Ret = [&] {
4171 switch (RetAI.getKind()) {
John McCallf26e73d2016-03-11 04:30:43 +00004172 case ABIArgInfo::CoerceAndExpand: {
4173 auto coercionType = RetAI.getCoerceAndExpandType();
4174 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
4175
4176 Address addr = SRetPtr;
4177 addr = Builder.CreateElementBitCast(addr, coercionType);
4178
John McCall12f23522016-04-04 18:33:08 +00004179 assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
4180 bool requiresExtract = isa<llvm::StructType>(CI->getType());
4181
John McCallf26e73d2016-03-11 04:30:43 +00004182 unsigned unpaddedIndex = 0;
4183 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
4184 llvm::Type *eltType = coercionType->getElementType(i);
4185 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
4186 Address eltAddr = Builder.CreateStructGEP(addr, i, layout);
John McCall12f23522016-04-04 18:33:08 +00004187 llvm::Value *elt = CI;
4188 if (requiresExtract)
4189 elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
4190 else
4191 assert(unpaddedIndex == 0);
John McCallf26e73d2016-03-11 04:30:43 +00004192 Builder.CreateStore(elt, eltAddr);
4193 }
John McCall12f23522016-04-04 18:33:08 +00004194 // FALLTHROUGH
4195 }
4196
4197 case ABIArgInfo::InAlloca:
4198 case ABIArgInfo::Indirect: {
4199 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
4200 if (UnusedReturnSize)
4201 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
4202 SRetPtr.getPointer());
4203 return ret;
John McCallf26e73d2016-03-11 04:30:43 +00004204 }
4205
Hal Finkelee90a222014-09-26 05:04:30 +00004206 case ABIArgInfo::Ignore:
4207 // If we are ignoring an argument that had a result, make sure to
4208 // construct the appropriate return value for our caller.
4209 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004210
Hal Finkelee90a222014-09-26 05:04:30 +00004211 case ABIArgInfo::Extend:
4212 case ABIArgInfo::Direct: {
4213 llvm::Type *RetIRTy = ConvertType(RetTy);
4214 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
4215 switch (getEvaluationKind(RetTy)) {
4216 case TEK_Complex: {
4217 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
4218 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
4219 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004220 }
Hal Finkelee90a222014-09-26 05:04:30 +00004221 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +00004222 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00004223 bool DestIsVolatile = ReturnValue.isVolatile();
4224
John McCall7f416cc2015-09-08 08:05:57 +00004225 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00004226 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
4227 DestIsVolatile = false;
4228 }
John McCall7f416cc2015-09-08 08:05:57 +00004229 BuildAggStore(*this, CI, DestPtr, DestIsVolatile);
Hal Finkelee90a222014-09-26 05:04:30 +00004230 return RValue::getAggregate(DestPtr);
4231 }
4232 case TEK_Scalar: {
4233 // If the argument doesn't match, perform a bitcast to coerce it. This
4234 // can happen due to trivial type mismatches.
4235 llvm::Value *V = CI;
4236 if (V->getType() != RetIRTy)
4237 V = Builder.CreateBitCast(V, RetIRTy);
4238 return RValue::get(V);
4239 }
4240 }
4241 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004242 }
Hal Finkelee90a222014-09-26 05:04:30 +00004243
John McCall7f416cc2015-09-08 08:05:57 +00004244 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00004245 bool DestIsVolatile = ReturnValue.isVolatile();
4246
John McCall7f416cc2015-09-08 08:05:57 +00004247 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00004248 DestPtr = CreateMemTemp(RetTy, "coerce");
4249 DestIsVolatile = false;
John McCall47fb9502013-03-07 21:37:08 +00004250 }
Hal Finkelee90a222014-09-26 05:04:30 +00004251
4252 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00004253 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
4254 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Hal Finkelee90a222014-09-26 05:04:30 +00004255
4256 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004257 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004258
Hal Finkelee90a222014-09-26 05:04:30 +00004259 case ABIArgInfo::Expand:
4260 llvm_unreachable("Invalid ABI kind for return argument");
Anders Carlsson17490832009-12-24 20:40:36 +00004261 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004262
Hal Finkelee90a222014-09-26 05:04:30 +00004263 llvm_unreachable("Unhandled ABIArgInfo::Kind");
4264 } ();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004265
John McCallb92ab1a2016-10-26 23:46:34 +00004266 // Emit the assume_aligned check on the return value.
4267 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl();
Hal Finkelee90a222014-09-26 05:04:30 +00004268 if (Ret.isScalar() && TargetDecl) {
4269 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
4270 llvm::Value *OffsetValue = nullptr;
4271 if (const auto *Offset = AA->getOffset())
4272 OffsetValue = EmitScalarExpr(Offset);
4273
4274 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
4275 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
4276 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
4277 OffsetValue);
4278 }
Daniel Dunbar573884e2008-09-10 07:04:09 +00004279 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00004280
Hal Finkelee90a222014-09-26 05:04:30 +00004281 return Ret;
Daniel Dunbar613855c2008-09-09 23:27:19 +00004282}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00004283
4284/* VarArg handling */
4285
Charles Davisc7d5c942015-09-17 20:55:33 +00004286Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
4287 VAListAddr = VE->isMicrosoftABI()
4288 ? EmitMSVAListRef(VE->getSubExpr())
4289 : EmitVAListRef(VE->getSubExpr());
4290 QualType Ty = VE->getType();
4291 if (VE->isMicrosoftABI())
4292 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004293 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00004294}