blob: 75713419aa11aaa85b3b1a84a6e7267aa7fdeaf2 [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CGCXXABI.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000018#include "CodeGenFunction.h"
Daniel Dunbarc68897d2008-09-10 00:41:16 +000019#include "CodeGenModule.h"
John McCalla729c622012-02-17 03:33:10 +000020#include "TargetInfo.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000021#include "clang/AST/Decl.h"
Anders Carlssonb15b55c2009-04-03 22:48:58 +000022#include "clang/AST/DeclCXX.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000023#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000025#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth85098242010-06-15 23:19:56 +000026#include "clang/Frontend/CodeGenOptions.h"
Bill Wendling706469b2013-02-28 22:49:57 +000027#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000028#include "llvm/IR/Attributes.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000029#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000030#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/InlineAsm.h"
Reid Kleckner314ef7b2014-02-01 00:04:45 +000032#include "llvm/IR/Intrinsics.h"
Eli Friedmanf7456192011-06-15 22:09:18 +000033#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000034using namespace clang;
35using namespace CodeGen;
36
37/***/
38
John McCallab26cfa2010-02-05 21:31:56 +000039static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) {
40 switch (CC) {
41 default: return llvm::CallingConv::C;
42 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
43 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
Douglas Gregora941dca2010-05-18 16:57:00 +000044 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Charles Davisb5a214e2013-08-30 04:39:01 +000045 case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64;
46 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
Anton Korobeynikov231e8752011-04-14 20:06:49 +000047 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
48 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Guy Benyeif0a014b2012-12-25 08:53:55 +000049 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Dawn Perchik335e16b2010-09-03 01:29:35 +000050 // TODO: add support for CC_X86Pascal to llvm
John McCallab26cfa2010-02-05 21:31:56 +000051 }
52}
53
John McCall8ee376f2010-02-24 07:14:12 +000054/// Derives the 'this' type for codegen purposes, i.e. ignoring method
55/// qualification.
56/// FIXME: address space qualification?
John McCall2da83a32010-02-26 00:48:12 +000057static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
58 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
59 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000060}
61
John McCall8ee376f2010-02-24 07:14:12 +000062/// Returns the canonical formal type of the given C++ method.
John McCall2da83a32010-02-26 00:48:12 +000063static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
64 return MD->getType()->getCanonicalTypeUnqualified()
65 .getAs<FunctionProtoType>();
John McCall8ee376f2010-02-24 07:14:12 +000066}
67
68/// Returns the "extra-canonicalized" return type, which discards
69/// qualifiers on the return type. Codegen doesn't care about them,
70/// and it makes ABI code a little easier to be able to assume that
71/// all parameter and return types are top-level unqualified.
John McCall2da83a32010-02-26 00:48:12 +000072static CanQualType GetReturnType(QualType RetTy) {
73 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall8ee376f2010-02-24 07:14:12 +000074}
75
John McCall8dda7b22012-07-07 06:41:13 +000076/// Arrange the argument and result information for a value of the given
77/// unprototyped freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +000078const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +000079CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCalla729c622012-02-17 03:33:10 +000080 // When translating an unprototyped function type, always use a
81 // variadic type.
Alp Toker314cc812014-01-25 16:55:45 +000082 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
Reid Kleckner4982b822014-01-31 22:54:50 +000083 false, None, FTNP->getExtInfo(),
84 RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +000085}
86
John McCall8dda7b22012-07-07 06:41:13 +000087/// Arrange the LLVM function layout for a value of the given function
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +000088/// type, on top of any implicit parameters already stored.
89static const CGFunctionInfo &
90arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool IsInstanceMethod,
91 SmallVectorImpl<CanQualType> &prefix,
92 CanQual<FunctionProtoType> FTP) {
John McCall8dda7b22012-07-07 06:41:13 +000093 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +000094 // FIXME: Kill copy.
Alp Toker9cacbab2014-01-20 20:26:09 +000095 for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
96 prefix.push_back(FTP->getParamType(i));
Alp Toker314cc812014-01-25 16:55:45 +000097 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
Reid Kleckner4982b822014-01-31 22:54:50 +000098 return CGT.arrangeLLVMFunctionInfo(resultType, IsInstanceMethod, prefix,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +000099 FTP->getExtInfo(), required);
John McCall8ee376f2010-02-24 07:14:12 +0000100}
101
John McCalla729c622012-02-17 03:33:10 +0000102/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000103/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000104const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000105CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
John McCalla729c622012-02-17 03:33:10 +0000106 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000107 return ::arrangeLLVMFunctionInfo(*this, false, argTypes, FTP);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000108}
109
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000110static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000111 // Set the appropriate calling convention for the Function.
112 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000113 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000114
115 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000116 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000117
Douglas Gregora941dca2010-05-18 16:57:00 +0000118 if (D->hasAttr<ThisCallAttr>())
119 return CC_X86ThisCall;
120
Dawn Perchik335e16b2010-09-03 01:29:35 +0000121 if (D->hasAttr<PascalAttr>())
122 return CC_X86Pascal;
123
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000124 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
125 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
126
Derek Schuffa2020962012-10-16 22:30:41 +0000127 if (D->hasAttr<PnaclCallAttr>())
128 return CC_PnaclCall;
129
Guy Benyeif0a014b2012-12-25 08:53:55 +0000130 if (D->hasAttr<IntelOclBiccAttr>())
131 return CC_IntelOclBicc;
132
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000133 if (D->hasAttr<MSABIAttr>())
134 return IsWindows ? CC_C : CC_X86_64Win64;
135
136 if (D->hasAttr<SysVABIAttr>())
137 return IsWindows ? CC_X86_64SysV : CC_C;
138
John McCallab26cfa2010-02-05 21:31:56 +0000139 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000140}
141
John McCalla729c622012-02-17 03:33:10 +0000142/// Arrange the argument and result information for a call to an
143/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000144/// (Zero value of RD means we don't have any meaningful "this" argument type,
145/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000146/// The member function must be an ordinary function, i.e. not a
147/// constructor or destructor.
148const CGFunctionInfo &
149CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
150 const FunctionProtoType *FTP) {
151 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000152
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000153 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000154 if (RD)
155 argTypes.push_back(GetThisType(Context, RD));
156 else
157 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000158
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000159 return ::arrangeLLVMFunctionInfo(
160 *this, true, argTypes,
161 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000162}
163
John McCalla729c622012-02-17 03:33:10 +0000164/// Arrange the argument and result information for a declaration or
165/// definition of the given C++ non-static member function. The
166/// member function must be an ordinary function, i.e. not a
167/// constructor or destructor.
168const CGFunctionInfo &
169CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000170 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000171 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
172
John McCalla729c622012-02-17 03:33:10 +0000173 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000174
John McCalla729c622012-02-17 03:33:10 +0000175 if (MD->isInstance()) {
176 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000177 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000178 return arrangeCXXMethodType(ThisType, prototype.getTypePtr());
John McCalla729c622012-02-17 03:33:10 +0000179 }
180
John McCall8dda7b22012-07-07 06:41:13 +0000181 return arrangeFreeFunctionType(prototype);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000182}
183
John McCalla729c622012-02-17 03:33:10 +0000184/// Arrange the argument and result information for a declaration
185/// or definition to the given constructor variant.
186const CGFunctionInfo &
187CodeGenTypes::arrangeCXXConstructorDeclaration(const CXXConstructorDecl *D,
188 CXXCtorType ctorKind) {
189 SmallVector<CanQualType, 16> argTypes;
190 argTypes.push_back(GetThisType(Context, D->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000191
192 GlobalDecl GD(D, ctorKind);
193 CanQualType resultType =
194 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000195
John McCall5d865c322010-08-31 07:33:07 +0000196 CanQual<FunctionProtoType> FTP = GetFormalType(D);
197
198 // Add the formal parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000199 for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
200 argTypes.push_back(FTP->getParamType(i));
John McCall5d865c322010-08-31 07:33:07 +0000201
Reid Kleckner89077a12013-12-17 19:46:40 +0000202 TheCXXABI.BuildConstructorSignature(D, ctorKind, resultType, argTypes);
203
204 RequiredArgs required =
205 (D->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All);
206
John McCall8dda7b22012-07-07 06:41:13 +0000207 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
Reid Kleckner4982b822014-01-31 22:54:50 +0000208 return arrangeLLVMFunctionInfo(resultType, true, argTypes, extInfo, required);
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000209}
210
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000211/// Arrange a call to a C++ method, passing the given arguments.
212const CGFunctionInfo &
213CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
214 const CXXConstructorDecl *D,
215 CXXCtorType CtorKind,
216 unsigned ExtraArgs) {
217 // FIXME: Kill copy.
218 SmallVector<CanQualType, 16> ArgTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000219 for (const auto &Arg : args)
220 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000221
222 CanQual<FunctionProtoType> FPT = GetFormalType(D);
223 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs);
224 GlobalDecl GD(D, CtorKind);
225 CanQualType ResultType =
226 TheCXXABI.HasThisReturn(GD) ? ArgTypes.front() : Context.VoidTy;
227
228 FunctionType::ExtInfo Info = FPT->getExtInfo();
229 return arrangeLLVMFunctionInfo(ResultType, true, ArgTypes, Info, Required);
230}
231
John McCalla729c622012-02-17 03:33:10 +0000232/// Arrange the argument and result information for a declaration,
233/// definition, or call to the given destructor variant. It so
234/// happens that all three cases produce the same information.
235const CGFunctionInfo &
236CodeGenTypes::arrangeCXXDestructor(const CXXDestructorDecl *D,
237 CXXDtorType dtorKind) {
238 SmallVector<CanQualType, 2> argTypes;
239 argTypes.push_back(GetThisType(Context, D->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000240
241 GlobalDecl GD(D, dtorKind);
242 CanQualType resultType =
243 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
John McCall8ee376f2010-02-24 07:14:12 +0000244
John McCalla729c622012-02-17 03:33:10 +0000245 TheCXXABI.BuildDestructorSignature(D, dtorKind, resultType, argTypes);
John McCall5d865c322010-08-31 07:33:07 +0000246
247 CanQual<FunctionProtoType> FTP = GetFormalType(D);
Alp Toker9cacbab2014-01-20 20:26:09 +0000248 assert(FTP->getNumParams() == 0 && "dtor with formal parameters");
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +0000249 assert(FTP->isVariadic() == 0 && "dtor with formal parameters");
John McCall5d865c322010-08-31 07:33:07 +0000250
John McCall8dda7b22012-07-07 06:41:13 +0000251 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
Reid Kleckner4982b822014-01-31 22:54:50 +0000252 return arrangeLLVMFunctionInfo(resultType, true, argTypes, extInfo,
John McCall8dda7b22012-07-07 06:41:13 +0000253 RequiredArgs::All);
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000254}
255
John McCalla729c622012-02-17 03:33:10 +0000256/// Arrange the argument and result information for the declaration or
257/// definition of the given function.
258const CGFunctionInfo &
259CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000260 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000261 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000262 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000263
John McCall2da83a32010-02-26 00:48:12 +0000264 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000265
John McCall2da83a32010-02-26 00:48:12 +0000266 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000267
268 // When declaring a function without a prototype, always use a
269 // non-variadic type.
270 if (isa<FunctionNoProtoType>(FTy)) {
271 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Reid Kleckner4982b822014-01-31 22:54:50 +0000272 return arrangeLLVMFunctionInfo(noProto->getReturnType(), false, None,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000273 noProto->getExtInfo(), RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000274 }
275
John McCall2da83a32010-02-26 00:48:12 +0000276 assert(isa<FunctionProtoType>(FTy));
John McCall8dda7b22012-07-07 06:41:13 +0000277 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>());
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000278}
279
John McCalla729c622012-02-17 03:33:10 +0000280/// Arrange the argument and result information for the declaration or
281/// definition of an Objective-C method.
282const CGFunctionInfo &
283CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
284 // It happens that this is the same as a call with no optional
285 // arguments, except also using the formal 'self' type.
286 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
287}
288
289/// Arrange the argument and result information for the function type
290/// through which to perform a send to the given Objective-C method,
291/// using the given receiver type. The receiver type is not always
292/// the 'self' type of the method or even an Objective-C pointer type.
293/// This is *not* the right method for actually performing such a
294/// message send, due to the possibility of optional arguments.
295const CGFunctionInfo &
296CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
297 QualType receiverType) {
298 SmallVector<CanQualType, 16> argTys;
299 argTys.push_back(Context.getCanonicalParamType(receiverType));
300 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000301 // FIXME: Kill copy?
Aaron Ballman43b68be2014-03-07 17:50:17 +0000302 for (const auto *I : MD->params()) {
303 argTys.push_back(Context.getCanonicalParamType(I->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000304 }
John McCall31168b02011-06-15 23:02:42 +0000305
306 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000307 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
308 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000309
David Blaikiebbafb8a2012-03-11 07:00:24 +0000310 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000311 MD->hasAttr<NSReturnsRetainedAttr>())
312 einfo = einfo.withProducesResult(true);
313
John McCalla729c622012-02-17 03:33:10 +0000314 RequiredArgs required =
315 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
316
Reid Kleckner4982b822014-01-31 22:54:50 +0000317 return arrangeLLVMFunctionInfo(GetReturnType(MD->getReturnType()), false,
318 argTys, einfo, required);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000319}
320
John McCalla729c622012-02-17 03:33:10 +0000321const CGFunctionInfo &
322CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000323 // FIXME: Do we need to handle ObjCMethodDecl?
324 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000325
Anders Carlsson6710c532010-02-06 02:44:09 +0000326 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
John McCalla729c622012-02-17 03:33:10 +0000327 return arrangeCXXConstructorDeclaration(CD, GD.getCtorType());
Anders Carlsson6710c532010-02-06 02:44:09 +0000328
329 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
John McCalla729c622012-02-17 03:33:10 +0000330 return arrangeCXXDestructor(DD, GD.getDtorType());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000331
John McCalla729c622012-02-17 03:33:10 +0000332 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000333}
334
John McCallc818bbb2012-12-07 07:03:17 +0000335/// Arrange a call as unto a free function, except possibly with an
336/// additional number of formal parameters considered required.
337static const CGFunctionInfo &
338arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000339 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000340 const CallArgList &args,
341 const FunctionType *fnType,
342 unsigned numExtraRequiredArgs) {
343 assert(args.size() >= numExtraRequiredArgs);
344
345 // In most cases, there are no optional arguments.
346 RequiredArgs required = RequiredArgs::All;
347
348 // If we have a variadic prototype, the required arguments are the
349 // extra prefix plus the arguments in the prototype.
350 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
351 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000352 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000353
354 // If we don't have a prototype at all, but we're supposed to
355 // explicitly use the variadic convention for unprototyped calls,
356 // treat all of the arguments as required but preserve the nominal
357 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000358 } else if (CGM.getTargetCodeGenInfo()
359 .isNoProtoCallVariadic(args,
360 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000361 required = RequiredArgs(args.size());
362 }
363
Alp Toker314cc812014-01-25 16:55:45 +0000364 return CGT.arrangeFreeFunctionCall(fnType->getReturnType(), args,
John McCallc818bbb2012-12-07 07:03:17 +0000365 fnType->getExtInfo(), required);
366}
367
John McCalla729c622012-02-17 03:33:10 +0000368/// Figure out the rules for calling a function with the given formal
369/// type using the given arguments. The arguments are necessary
370/// because the function might be unprototyped, in which case it's
371/// target-dependent in crazy ways.
372const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000373CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
374 const FunctionType *fnType) {
Mark Lacey23455752013-10-10 20:57:00 +0000375 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 0);
John McCallc818bbb2012-12-07 07:03:17 +0000376}
John McCalla729c622012-02-17 03:33:10 +0000377
John McCallc818bbb2012-12-07 07:03:17 +0000378/// A block function call is essentially a free-function call with an
379/// extra implicit argument.
380const CGFunctionInfo &
381CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
382 const FunctionType *fnType) {
Mark Lacey23455752013-10-10 20:57:00 +0000383 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1);
John McCalla729c622012-02-17 03:33:10 +0000384}
385
386const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000387CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
388 const CallArgList &args,
389 FunctionType::ExtInfo info,
390 RequiredArgs required) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000391 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000392 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000393 for (const auto &Arg : args)
394 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner4982b822014-01-31 22:54:50 +0000395 return arrangeLLVMFunctionInfo(GetReturnType(resultType), false, argTypes,
396 info, required);
John McCall8dda7b22012-07-07 06:41:13 +0000397}
398
399/// Arrange a call to a C++ method, passing the given arguments.
400const CGFunctionInfo &
401CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
402 const FunctionProtoType *FPT,
403 RequiredArgs required) {
404 // FIXME: Kill copy.
405 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000406 for (const auto &Arg : args)
407 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
John McCall8dda7b22012-07-07 06:41:13 +0000408
409 FunctionType::ExtInfo info = FPT->getExtInfo();
Reid Kleckner4982b822014-01-31 22:54:50 +0000410 return arrangeLLVMFunctionInfo(GetReturnType(FPT->getReturnType()), true,
411 argTypes, info, required);
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000412}
413
Reid Kleckner4982b822014-01-31 22:54:50 +0000414const CGFunctionInfo &CodeGenTypes::arrangeFreeFunctionDeclaration(
415 QualType resultType, const FunctionArgList &args,
416 const FunctionType::ExtInfo &info, bool isVariadic) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000417 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000418 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000419 for (auto Arg : args)
420 argTypes.push_back(Context.getCanonicalParamType(Arg->getType()));
John McCalla729c622012-02-17 03:33:10 +0000421
422 RequiredArgs required =
423 (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
Reid Kleckner4982b822014-01-31 22:54:50 +0000424 return arrangeLLVMFunctionInfo(GetReturnType(resultType), false, argTypes, info,
John McCall8dda7b22012-07-07 06:41:13 +0000425 required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000426}
427
John McCalla729c622012-02-17 03:33:10 +0000428const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Reid Kleckner4982b822014-01-31 22:54:50 +0000429 return arrangeLLVMFunctionInfo(getContext().VoidTy, false, None,
John McCall8dda7b22012-07-07 06:41:13 +0000430 FunctionType::ExtInfo(), RequiredArgs::All);
John McCalla738c252011-03-09 04:27:21 +0000431}
432
John McCalla729c622012-02-17 03:33:10 +0000433/// Arrange the argument and result information for an abstract value
434/// of a given function type. This is the method which all of the
435/// above functions ultimately defer to.
436const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000437CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Reid Kleckner4982b822014-01-31 22:54:50 +0000438 bool IsInstanceMethod,
John McCall8dda7b22012-07-07 06:41:13 +0000439 ArrayRef<CanQualType> argTypes,
440 FunctionType::ExtInfo info,
441 RequiredArgs required) {
John McCall2da83a32010-02-26 00:48:12 +0000442#ifndef NDEBUG
John McCalla729c622012-02-17 03:33:10 +0000443 for (ArrayRef<CanQualType>::const_iterator
444 I = argTypes.begin(), E = argTypes.end(); I != E; ++I)
John McCall2da83a32010-02-26 00:48:12 +0000445 assert(I->isCanonicalAsParam());
446#endif
447
John McCalla729c622012-02-17 03:33:10 +0000448 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
John McCallab26cfa2010-02-05 21:31:56 +0000449
Daniel Dunbare0be8292009-02-03 00:07:12 +0000450 // Lookup or create unique function info.
451 llvm::FoldingSetNodeID ID;
Reid Kleckner4982b822014-01-31 22:54:50 +0000452 CGFunctionInfo::Profile(ID, IsInstanceMethod, info, required, resultType,
453 argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000454
Craig Topper8a13c412014-05-21 05:09:00 +0000455 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000456 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000457 if (FI)
458 return *FI;
459
John McCalla729c622012-02-17 03:33:10 +0000460 // Construct the function info. We co-allocate the ArgInfos.
Reid Kleckner4982b822014-01-31 22:54:50 +0000461 FI = CGFunctionInfo::create(CC, IsInstanceMethod, info, resultType, argTypes,
462 required);
John McCalla729c622012-02-17 03:33:10 +0000463 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000464
John McCalla729c622012-02-17 03:33:10 +0000465 bool inserted = FunctionsBeingProcessed.insert(FI); (void)inserted;
466 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000467
Daniel Dunbar313321e2009-02-03 05:31:23 +0000468 // Compute ABI information.
Chris Lattner22326a12010-07-29 02:31:05 +0000469 getABIInfo().computeInfo(*FI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000470
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000471 // Loop over all of the computed argument and return value info. If any of
472 // them are direct or extend without a specified coerce type, specify the
473 // default now.
John McCalla729c622012-02-17 03:33:10 +0000474 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000475 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000476 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000477
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000478 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000479 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000480 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000481
John McCalla729c622012-02-17 03:33:10 +0000482 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
483 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000484
Daniel Dunbare0be8292009-02-03 00:07:12 +0000485 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000486}
487
John McCalla729c622012-02-17 03:33:10 +0000488CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Reid Kleckner4982b822014-01-31 22:54:50 +0000489 bool IsInstanceMethod,
John McCalla729c622012-02-17 03:33:10 +0000490 const FunctionType::ExtInfo &info,
491 CanQualType resultType,
492 ArrayRef<CanQualType> argTypes,
493 RequiredArgs required) {
494 void *buffer = operator new(sizeof(CGFunctionInfo) +
495 sizeof(ArgInfo) * (argTypes.size() + 1));
496 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
497 FI->CallingConvention = llvmCC;
498 FI->EffectiveCallingConvention = llvmCC;
499 FI->ASTCallingConvention = info.getCC();
Reid Kleckner4982b822014-01-31 22:54:50 +0000500 FI->InstanceMethod = IsInstanceMethod;
John McCalla729c622012-02-17 03:33:10 +0000501 FI->NoReturn = info.getNoReturn();
502 FI->ReturnsRetained = info.getProducesResult();
503 FI->Required = required;
504 FI->HasRegParm = info.getHasRegParm();
505 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000506 FI->ArgStruct = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000507 FI->NumArgs = argTypes.size();
508 FI->getArgsBuffer()[0].type = resultType;
509 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
510 FI->getArgsBuffer()[i + 1].type = argTypes[i];
511 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000512}
513
514/***/
515
John McCall85dd2c52011-05-15 02:19:42 +0000516void CodeGenTypes::GetExpandedTypes(QualType type,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000517 SmallVectorImpl<llvm::Type*> &expandedTypes) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000518 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(type)) {
519 uint64_t NumElts = AT->getSize().getZExtValue();
520 for (uint64_t Elt = 0; Elt < NumElts; ++Elt)
521 GetExpandedTypes(AT->getElementType(), expandedTypes);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000522 } else if (const RecordType *RT = type->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000523 const RecordDecl *RD = RT->getDecl();
524 assert(!RD->hasFlexibleArrayMember() &&
525 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000526 if (RD->isUnion()) {
527 // Unions can be here only in degenerative cases - all the fields are same
528 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000529 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000530 CharUnits UnionSize = CharUnits::Zero();
531
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000532 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000533 assert(!FD->isBitField() &&
534 "Cannot expand structure with bit-field members.");
535 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
536 if (UnionSize < FieldSize) {
537 UnionSize = FieldSize;
538 LargestFD = FD;
539 }
540 }
541 if (LargestFD)
542 GetExpandedTypes(LargestFD->getType(), expandedTypes);
543 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000544 for (const auto *I : RD->fields()) {
545 assert(!I->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000546 "Cannot expand structure with bit-field members.");
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000547 GetExpandedTypes(I->getType(), expandedTypes);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000548 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000549 }
550 } else if (const ComplexType *CT = type->getAs<ComplexType>()) {
551 llvm::Type *EltTy = ConvertType(CT->getElementType());
552 expandedTypes.push_back(EltTy);
553 expandedTypes.push_back(EltTy);
554 } else
555 expandedTypes.push_back(ConvertType(type));
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000556}
557
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000558void CodeGenFunction::ExpandTypeFromArgs(
559 QualType Ty, LValue LV, SmallVectorImpl<llvm::Argument *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000560 assert(LV.isSimple() &&
561 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000562
Bob Wilsone826a2a2011-08-03 05:58:22 +0000563 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
564 unsigned NumElts = AT->getSize().getZExtValue();
565 QualType EltTy = AT->getElementType();
566 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
Eli Friedman7f1ff602012-04-16 03:54:45 +0000567 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, Elt);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000568 LValue LV = MakeAddrLValue(EltAddr, EltTy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000569 ExpandTypeFromArgs(EltTy, LV, AI);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000570 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000571 return;
572 }
573 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000574 RecordDecl *RD = RT->getDecl();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000575 if (RD->isUnion()) {
576 // Unions can be here only in degenerative cases - all the fields are same
577 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000578 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000579 CharUnits UnionSize = CharUnits::Zero();
Bob Wilsone826a2a2011-08-03 05:58:22 +0000580
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000581 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000582 assert(!FD->isBitField() &&
583 "Cannot expand structure with bit-field members.");
584 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
585 if (UnionSize < FieldSize) {
586 UnionSize = FieldSize;
587 LargestFD = FD;
588 }
589 }
590 if (LargestFD) {
591 // FIXME: What are the right qualifiers here?
Eli Friedman7f1ff602012-04-16 03:54:45 +0000592 LValue SubLV = EmitLValueForField(LV, LargestFD);
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000593 ExpandTypeFromArgs(LargestFD->getType(), SubLV, AI);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000594 }
595 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000596 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000597 QualType FT = FD->getType();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000598 // FIXME: What are the right qualifiers here?
Eli Friedman7f1ff602012-04-16 03:54:45 +0000599 LValue SubLV = EmitLValueForField(LV, FD);
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000600 ExpandTypeFromArgs(FT, SubLV, AI);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000601 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000602 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000603 return;
604 }
605 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000606 QualType EltTy = CT->getElementType();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000607 llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real");
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000608 EmitStoreThroughLValue(RValue::get(*AI++), MakeAddrLValue(RealAddr, EltTy));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000609 llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag");
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000610 EmitStoreThroughLValue(RValue::get(*AI++), MakeAddrLValue(ImagAddr, EltTy));
611 return;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000612 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000613 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000614}
615
Chris Lattner895c52b2010-06-27 06:04:18 +0000616/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +0000617/// accessing some number of bytes out of it, try to gep into the struct to get
618/// at its inner goodness. Dive as deep as possible without entering an element
619/// with an in-memory size smaller than DstSize.
620static llvm::Value *
Chris Lattner895c52b2010-06-27 06:04:18 +0000621EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000622 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +0000623 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +0000624 // We can't dive into a zero-element struct.
625 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000626
Chris Lattner2192fe52011-07-18 04:24:23 +0000627 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000628
Chris Lattner1cd66982010-06-27 05:56:15 +0000629 // If the first elt is at least as large as what we're looking for, or if the
630 // first element is the same size as the whole struct, we can enter it.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000631 uint64_t FirstEltSize =
Micah Villmowdd31ca12012-10-08 16:25:52 +0000632 CGF.CGM.getDataLayout().getTypeAllocSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000633 if (FirstEltSize < DstSize &&
Micah Villmowdd31ca12012-10-08 16:25:52 +0000634 FirstEltSize < CGF.CGM.getDataLayout().getTypeAllocSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +0000635 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000636
Chris Lattner1cd66982010-06-27 05:56:15 +0000637 // GEP into the first element.
638 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000639
Chris Lattner1cd66982010-06-27 05:56:15 +0000640 // If the first element is a struct, recurse.
Chris Lattner2192fe52011-07-18 04:24:23 +0000641 llvm::Type *SrcTy =
Chris Lattner1cd66982010-06-27 05:56:15 +0000642 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000643 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +0000644 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000645
646 return SrcPtr;
647}
648
Chris Lattner055097f2010-06-27 06:26:04 +0000649/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
650/// are either integers or pointers. This does a truncation of the value if it
651/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000652///
653/// This behaves as if the value were coerced through memory, so on big-endian
654/// targets the high bits are preserved in a truncation, while little-endian
655/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +0000656static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +0000657 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +0000658 CodeGenFunction &CGF) {
659 if (Val->getType() == Ty)
660 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000661
Chris Lattner055097f2010-06-27 06:26:04 +0000662 if (isa<llvm::PointerType>(Val->getType())) {
663 // If this is Pointer->Pointer avoid conversion to and from int.
664 if (isa<llvm::PointerType>(Ty))
665 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000666
Chris Lattner055097f2010-06-27 06:26:04 +0000667 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +0000668 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +0000669 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000670
Chris Lattner2192fe52011-07-18 04:24:23 +0000671 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +0000672 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +0000673 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000674
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000675 if (Val->getType() != DestIntTy) {
676 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
677 if (DL.isBigEndian()) {
678 // Preserve the high bits on big-endian targets.
679 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +0000680 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
681 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
682
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000683 if (SrcSize > DstSize) {
684 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
685 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
686 } else {
687 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
688 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
689 }
690 } else {
691 // Little-endian targets preserve the low bits. No shifts required.
692 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
693 }
694 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000695
Chris Lattner055097f2010-06-27 06:26:04 +0000696 if (isa<llvm::PointerType>(Ty))
697 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
698 return Val;
699}
700
Chris Lattner1cd66982010-06-27 05:56:15 +0000701
702
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000703/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
704/// a pointer to an object of type \arg Ty.
705///
706/// This safely handles the case when the src type is smaller than the
707/// destination type; in this situation the values of bits which not
708/// present in the src are undefined.
709static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000710 llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000711 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000712 llvm::Type *SrcTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000713 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000714
Chris Lattnerd200eda2010-06-28 22:51:39 +0000715 // If SrcTy and Ty are the same, just do a load.
716 if (SrcTy == Ty)
717 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000718
Micah Villmowdd31ca12012-10-08 16:25:52 +0000719 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000720
Chris Lattner2192fe52011-07-18 04:24:23 +0000721 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000722 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000723 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
724 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000725
Micah Villmowdd31ca12012-10-08 16:25:52 +0000726 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000727
Chris Lattner055097f2010-06-27 06:26:04 +0000728 // If the source and destination are integer or pointer types, just do an
729 // extension or truncation to the desired type.
730 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
731 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
732 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
733 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
734 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000735
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000736 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000737 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +0000738 // Generally SrcSize is never greater than DstSize, since this means we are
739 // losing bits. However, this can happen in cases where the structure has
740 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000741 //
Mike Stump18bb9282009-05-16 07:57:57 +0000742 // FIXME: Assert that we aren't truncating non-padding bits when have access
743 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000744 llvm::Value *Casted =
745 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000746 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
747 // FIXME: Use better alignment / avoid requiring aligned load.
748 Load->setAlignment(1);
749 return Load;
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000750 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000751
Chris Lattner3fcc7902010-06-27 01:06:27 +0000752 // Otherwise do coercion through memory. This is stupid, but
753 // simple.
754 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
Manman Ren84b921f2012-11-28 22:08:52 +0000755 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
756 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
757 llvm::Value *SrcCasted = CGF.Builder.CreateBitCast(SrcPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000758 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000759 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
760 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
761 1, false);
Chris Lattner3fcc7902010-06-27 01:06:27 +0000762 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000763}
764
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000765// Function to store a first-class aggregate into memory. We prefer to
766// store the elements rather than the aggregate to be more friendly to
767// fast-isel.
768// FIXME: Do we need to recurse here?
769static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
770 llvm::Value *DestPtr, bool DestIsVolatile,
771 bool LowAlignment) {
772 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +0000773 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000774 dyn_cast<llvm::StructType>(Val->getType())) {
775 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
776 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
777 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
778 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
779 DestIsVolatile);
780 if (LowAlignment)
781 SI->setAlignment(1);
782 }
783 } else {
Bill Wendlingf6af30f2012-03-16 21:45:12 +0000784 llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
785 if (LowAlignment)
786 SI->setAlignment(1);
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000787 }
788}
789
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000790/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
791/// where the source and destination may have different types.
792///
793/// This safely handles the case when the src type is larger than the
794/// destination type; the upper bits of the src will be lost.
795static void CreateCoercedStore(llvm::Value *Src,
796 llvm::Value *DstPtr,
Anders Carlsson17490832009-12-24 20:40:36 +0000797 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000798 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000799 llvm::Type *SrcTy = Src->getType();
800 llvm::Type *DstTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000801 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +0000802 if (SrcTy == DstTy) {
803 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
804 return;
805 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000806
Micah Villmowdd31ca12012-10-08 16:25:52 +0000807 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000808
Chris Lattner2192fe52011-07-18 04:24:23 +0000809 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000810 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
811 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
812 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000813
Chris Lattner055097f2010-06-27 06:26:04 +0000814 // If the source and destination are integer or pointer types, just do an
815 // extension or truncation to the desired type.
816 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
817 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
818 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
819 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
820 return;
821 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000822
Micah Villmowdd31ca12012-10-08 16:25:52 +0000823 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000824
Daniel Dunbar313321e2009-02-03 05:31:23 +0000825 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000826 if (SrcSize <= DstSize) {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000827 llvm::Value *Casted =
828 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000829 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000830 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000831 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000832 // Otherwise do coercion through memory. This is stupid, but
833 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000834
835 // Generally SrcSize is never greater than DstSize, since this means we are
836 // losing bits. However, this can happen in cases where the structure has
837 // additional padding, for example due to a user specified alignment.
838 //
839 // FIXME: Assert that we aren't truncating non-padding bits when have access
840 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000841 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
842 CGF.Builder.CreateStore(Src, Tmp);
Manman Ren84b921f2012-11-28 22:08:52 +0000843 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
844 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
845 llvm::Value *DstCasted = CGF.Builder.CreateBitCast(DstPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000846 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000847 CGF.Builder.CreateMemCpy(DstCasted, Casted,
848 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
849 1, false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000850 }
851}
852
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000853/***/
854
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000855bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000856 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +0000857}
858
Tim Northovere77cc392014-03-29 13:28:05 +0000859bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
860 return ReturnTypeUsesSRet(FI) &&
861 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
862}
863
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000864bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
865 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
866 switch (BT->getKind()) {
867 default:
868 return false;
869 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +0000870 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000871 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +0000872 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000873 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +0000874 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000875 }
876 }
877
878 return false;
879}
880
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000881bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
882 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
883 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
884 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +0000885 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000886 }
887 }
888
889 return false;
890}
891
Chris Lattnera5f58b02011-07-09 17:41:47 +0000892llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +0000893 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
894 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +0000895}
896
Chris Lattnera5f58b02011-07-09 17:41:47 +0000897llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +0000898CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000899
900 bool Inserted = FunctionsBeingProcessed.insert(&FI); (void)Inserted;
901 assert(Inserted && "Recursively being processed?");
902
Reid Kleckner37abaca2014-05-09 22:46:15 +0000903 bool SwapThisWithSRet = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000904 SmallVector<llvm::Type*, 8> argTypes;
Craig Topper8a13c412014-05-21 05:09:00 +0000905 llvm::Type *resultType = nullptr;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000906
John McCall85dd2c52011-05-15 02:19:42 +0000907 const ABIArgInfo &retAI = FI.getReturnInfo();
908 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +0000909 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +0000910 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +0000911
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000912 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +0000913 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +0000914 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +0000915 break;
916
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000917 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +0000918 if (retAI.getInAllocaSRet()) {
919 // sret things on win32 aren't void, they return the sret pointer.
920 QualType ret = FI.getReturnType();
921 llvm::Type *ty = ConvertType(ret);
922 unsigned addressSpace = Context.getTargetAddressSpace(ret);
923 resultType = llvm::PointerType::get(ty, addressSpace);
924 } else {
925 resultType = llvm::Type::getVoidTy(getLLVMContext());
926 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000927 break;
928
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000929 case ABIArgInfo::Indirect: {
John McCall85dd2c52011-05-15 02:19:42 +0000930 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
931 resultType = llvm::Type::getVoidTy(getLLVMContext());
932
933 QualType ret = FI.getReturnType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000934 llvm::Type *ty = ConvertType(ret);
John McCall85dd2c52011-05-15 02:19:42 +0000935 unsigned addressSpace = Context.getTargetAddressSpace(ret);
936 argTypes.push_back(llvm::PointerType::get(ty, addressSpace));
Reid Kleckner37abaca2014-05-09 22:46:15 +0000937
938 SwapThisWithSRet = retAI.isSRetAfterThis();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000939 break;
940 }
941
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000942 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +0000943 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000944 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000945 }
Mike Stump11289f42009-09-09 15:08:12 +0000946
John McCallc818bbb2012-12-07 07:03:17 +0000947 // Add in all of the required arguments.
948 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), ie;
949 if (FI.isVariadic()) {
950 ie = it + FI.getRequiredArgs().getNumRequiredArgs();
951 } else {
952 ie = FI.arg_end();
953 }
954 for (; it != ie; ++it) {
John McCall85dd2c52011-05-15 02:19:42 +0000955 const ABIArgInfo &argAI = it->info;
Mike Stump11289f42009-09-09 15:08:12 +0000956
Rafael Espindolafad28de2012-10-24 01:59:00 +0000957 // Insert a padding type to ensure proper alignment.
958 if (llvm::Type *PaddingType = argAI.getPaddingType())
959 argTypes.push_back(PaddingType);
960
John McCall85dd2c52011-05-15 02:19:42 +0000961 switch (argAI.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000962 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000963 case ABIArgInfo::InAlloca:
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000964 break;
965
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000966 case ABIArgInfo::Indirect: {
967 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +0000968 llvm::Type *LTy = ConvertTypeForMem(it->type);
John McCall85dd2c52011-05-15 02:19:42 +0000969 argTypes.push_back(LTy->getPointerTo());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000970 break;
971 }
972
973 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +0000974 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +0000975 // Fast-isel and the optimizer generally like scalar values better than
976 // FCAs, so we flatten them if this is safe to do for this argument.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000977 llvm::Type *argType = argAI.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +0000978 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +0000979 if (st && argAI.isDirect() && argAI.getCanBeFlattened()) {
John McCall85dd2c52011-05-15 02:19:42 +0000980 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
981 argTypes.push_back(st->getElementType(i));
Chris Lattner3dd716c2010-06-28 23:44:11 +0000982 } else {
John McCall85dd2c52011-05-15 02:19:42 +0000983 argTypes.push_back(argType);
Chris Lattner3dd716c2010-06-28 23:44:11 +0000984 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +0000985 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +0000986 }
Mike Stump11289f42009-09-09 15:08:12 +0000987
Daniel Dunbard3674e62008-09-11 01:48:57 +0000988 case ABIArgInfo::Expand:
Chris Lattnera5f58b02011-07-09 17:41:47 +0000989 GetExpandedTypes(it->type, argTypes);
Daniel Dunbard3674e62008-09-11 01:48:57 +0000990 break;
991 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000992 }
993
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000994 // Add the inalloca struct as the last parameter type.
995 if (llvm::StructType *ArgStruct = FI.getArgStruct())
996 argTypes.push_back(ArgStruct->getPointerTo());
997
Reid Kleckner37abaca2014-05-09 22:46:15 +0000998 if (SwapThisWithSRet)
999 std::swap(argTypes[0], argTypes[1]);
1000
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001001 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1002 assert(Erased && "Not in set?");
1003
John McCalla729c622012-02-17 03:33:10 +00001004 return llvm::FunctionType::get(resultType, argTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001005}
1006
Chris Lattner2192fe52011-07-18 04:24:23 +00001007llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001008 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001009 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001010
Chris Lattner8806e322011-07-10 00:18:59 +00001011 if (!isFuncTypeConvertible(FPT))
1012 return llvm::StructType::get(getLLVMContext());
1013
1014 const CGFunctionInfo *Info;
1015 if (isa<CXXDestructorDecl>(MD))
John McCalla729c622012-02-17 03:33:10 +00001016 Info = &arrangeCXXDestructor(cast<CXXDestructorDecl>(MD), GD.getDtorType());
Chris Lattner8806e322011-07-10 00:18:59 +00001017 else
John McCalla729c622012-02-17 03:33:10 +00001018 Info = &arrangeCXXMethodDeclaration(MD);
1019 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001020}
1021
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001022namespace {
1023
1024/// Encapsulates information about the way function arguments from
1025/// CGFunctionInfo should be passed to actual LLVM IR function.
1026class ClangToLLVMArgMapping {
1027 static const unsigned InvalidIndex = ~0U;
1028 unsigned InallocaArgNo;
1029 unsigned SRetArgNo;
1030 unsigned TotalIRArgs;
1031
1032 /// Arguments of LLVM IR function corresponding to single Clang argument.
1033 struct IRArgs {
1034 unsigned PaddingArgIndex;
1035 // Argument is expanded to IR arguments at positions
1036 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1037 unsigned FirstArgIndex;
1038 unsigned NumberOfArgs;
1039
1040 IRArgs()
1041 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1042 NumberOfArgs(0) {}
1043 };
1044
1045 SmallVector<IRArgs, 8> ArgInfo;
1046
1047public:
1048 ClangToLLVMArgMapping(CodeGenModule &CGM, const CGFunctionInfo &FI)
1049 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1050 ArgInfo(FI.arg_size()) {
1051 construct(CGM, FI);
1052 }
1053
1054 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1055 unsigned getInallocaArgNo() const {
1056 assert(hasInallocaArg());
1057 return InallocaArgNo;
1058 }
1059
1060 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1061 unsigned getSRetArgNo() const {
1062 assert(hasSRetArg());
1063 return SRetArgNo;
1064 }
1065
1066 unsigned totalIRArgs() const { return TotalIRArgs; }
1067
1068 bool hasPaddingArg(unsigned ArgNo) const {
1069 assert(ArgNo < ArgInfo.size());
1070 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1071 }
1072 unsigned getPaddingArgNo(unsigned ArgNo) const {
1073 assert(hasPaddingArg(ArgNo));
1074 return ArgInfo[ArgNo].PaddingArgIndex;
1075 }
1076
1077 /// Returns index of first IR argument corresponding to ArgNo, and their
1078 /// quantity.
1079 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1080 assert(ArgNo < ArgInfo.size());
1081 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1082 ArgInfo[ArgNo].NumberOfArgs);
1083 }
1084
1085private:
1086 void construct(CodeGenModule &CGM, const CGFunctionInfo &FI);
1087};
1088
1089void ClangToLLVMArgMapping::construct(CodeGenModule &CGM,
1090 const CGFunctionInfo &FI) {
1091 unsigned IRArgNo = 0;
1092 bool SwapThisWithSRet = false;
1093 const ABIArgInfo &RetAI = FI.getReturnInfo();
1094
1095 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1096 SwapThisWithSRet = RetAI.isSRetAfterThis();
1097 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1098 }
1099
1100 unsigned ArgNo = 0;
1101 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1102 E = FI.arg_end();
1103 I != E; ++I, ++ArgNo) {
1104 QualType ArgType = I->type;
1105 const ABIArgInfo &AI = I->info;
1106 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1107 auto &IRArgs = ArgInfo[ArgNo];
1108
1109 if (AI.getPaddingType())
1110 IRArgs.PaddingArgIndex = IRArgNo++;
1111
1112 switch (AI.getKind()) {
1113 case ABIArgInfo::Extend:
1114 case ABIArgInfo::Direct: {
1115 // FIXME: handle sseregparm someday...
1116 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001117 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001118 IRArgs.NumberOfArgs = STy->getNumElements();
1119 } else {
1120 IRArgs.NumberOfArgs = 1;
1121 }
1122 break;
1123 }
1124 case ABIArgInfo::Indirect:
1125 IRArgs.NumberOfArgs = 1;
1126 break;
1127 case ABIArgInfo::Ignore:
1128 case ABIArgInfo::InAlloca:
1129 // ignore and inalloca doesn't have matching LLVM parameters.
1130 IRArgs.NumberOfArgs = 0;
1131 break;
1132 case ABIArgInfo::Expand: {
1133 SmallVector<llvm::Type*, 8> Types;
1134 // FIXME: This is rather inefficient. Do we ever actually need to do
1135 // anything here? The result should be just reconstructed on the other
1136 // side, so extension should be a non-issue.
1137 CGM.getTypes().GetExpandedTypes(ArgType, Types);
1138 IRArgs.NumberOfArgs = Types.size();
1139 break;
1140 }
1141 }
1142
1143 if (IRArgs.NumberOfArgs > 0) {
1144 IRArgs.FirstArgIndex = IRArgNo;
1145 IRArgNo += IRArgs.NumberOfArgs;
1146 }
1147
1148 // Skip over the sret parameter when it comes second. We already handled it
1149 // above.
1150 if (IRArgNo == 1 && SwapThisWithSRet)
1151 IRArgNo++;
1152 }
1153 assert(ArgNo == FI.arg_size());
1154
1155 if (FI.usesInAlloca())
1156 InallocaArgNo = IRArgNo++;
1157
1158 TotalIRArgs = IRArgNo;
1159}
1160} // namespace
1161
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001162void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbard931a872009-02-02 22:03:45 +00001163 const Decl *TargetDecl,
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001164 AttributeListType &PAL,
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00001165 unsigned &CallingConv,
1166 bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001167 llvm::AttrBuilder FuncAttrs;
1168 llvm::AttrBuilder RetAttrs;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001169
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001170 CallingConv = FI.getEffectiveCallingConvention();
1171
John McCallab26cfa2010-02-05 21:31:56 +00001172 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001173 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001174
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001175 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001176 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001177 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001178 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001179 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001180 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001181 if (TargetDecl->hasAttr<NoReturnAttr>())
1182 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001183 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1184 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smithdebc59d2013-01-30 05:45:05 +00001185
1186 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
John McCallbe349de2010-07-08 06:48:12 +00001187 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl31ad7542011-03-13 17:09:40 +00001188 if (FPT && FPT->isNothrow(getContext()))
Bill Wendling207f0532012-12-20 19:27:06 +00001189 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith49af6292013-03-05 08:30:04 +00001190 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1191 // These attributes are not inherited by overloads.
1192 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1193 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001194 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001195 }
1196
Eric Christopherbf005ec2011-08-15 22:38:22 +00001197 // 'const' and 'pure' attribute functions are also nounwind.
1198 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001199 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1200 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001201 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001202 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1203 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001204 }
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001205 if (TargetDecl->hasAttr<MallocAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001206 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001207 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1208 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001209 }
1210
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001211 if (CodeGenOpts.OptimizeSize)
Bill Wendling207f0532012-12-20 19:27:06 +00001212 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
Quentin Colombet5ee5ca12012-10-26 00:29:48 +00001213 if (CodeGenOpts.OptimizeSize == 2)
Bill Wendling207f0532012-12-20 19:27:06 +00001214 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001215 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001216 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001217 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001218 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001219 if (CodeGenOpts.EnableSegmentedStacks &&
1220 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001221 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001222
Bill Wendling2f81db62013-02-22 20:53:29 +00001223 if (AttrOnCallSite) {
1224 // Attributes that should go on the call site only.
1225 if (!CodeGenOpts.SimplifyLibCalls)
1226 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Bill Wendling706469b2013-02-28 22:49:57 +00001227 } else {
1228 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001229 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001230 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001231 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001232 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001233 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001234 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001235 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001236 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001237 }
1238
Bill Wendlingdabafea2013-03-13 22:24:33 +00001239 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001240 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001241 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001242 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001243 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001244 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001245 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001246 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001247 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001248 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001249 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001250 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001251
Bill Wendlingd8f49502013-08-01 21:41:02 +00001252 if (!CodeGenOpts.StackRealignment)
1253 FuncAttrs.addAttribute("no-realign-stack");
Bill Wendling985d1c52013-02-15 21:30:01 +00001254 }
1255
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001256 ClangToLLVMArgMapping IRFunctionArgs(*this, FI);
1257
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001258 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001259 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001260 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001261 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001262 if (RetTy->hasSignedIntegerRepresentation())
1263 RetAttrs.addAttribute(llvm::Attribute::SExt);
1264 else if (RetTy->hasUnsignedIntegerRepresentation())
1265 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001266 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001267 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001268 if (RetAI.getInReg())
1269 RetAttrs.addAttribute(llvm::Attribute::InReg);
1270 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001271 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001272 break;
1273
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001274 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001275 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001276 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001277 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1278 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001279 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001280 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001281
Daniel Dunbard3674e62008-09-11 01:48:57 +00001282 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001283 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001284 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001285
Hal Finkela2347ba2014-07-18 15:52:10 +00001286 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1287 QualType PTy = RefTy->getPointeeType();
1288 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1289 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1290 .getQuantity());
1291 else if (getContext().getTargetAddressSpace(PTy) == 0)
1292 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1293 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001294
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001295 // Attach return attributes.
1296 if (RetAttrs.hasAttributes()) {
1297 PAL.push_back(llvm::AttributeSet::get(
1298 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1299 }
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001300
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001301 // Attach attributes to sret.
1302 if (IRFunctionArgs.hasSRetArg()) {
1303 llvm::AttrBuilder SRETAttrs;
1304 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
1305 if (RetAI.getInReg())
1306 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1307 PAL.push_back(llvm::AttributeSet::get(
1308 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1309 }
1310
1311 // Attach attributes to inalloca argument.
1312 if (IRFunctionArgs.hasInallocaArg()) {
1313 llvm::AttrBuilder Attrs;
1314 Attrs.addAttribute(llvm::Attribute::InAlloca);
1315 PAL.push_back(llvm::AttributeSet::get(
1316 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1317 }
1318
1319
1320 unsigned ArgNo = 0;
1321 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1322 E = FI.arg_end();
1323 I != E; ++I, ++ArgNo) {
1324 QualType ParamType = I->type;
1325 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001326 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001327
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001328 // Add attribute for padding argument, if necessary.
1329 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendling290d9522013-01-27 02:46:53 +00001330 if (AI.getPaddingInReg())
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001331 PAL.push_back(llvm::AttributeSet::get(
1332 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1333 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001334 }
1335
John McCall39ec71f2010-03-27 00:47:27 +00001336 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1337 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001338 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001339 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001340 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001341 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001342 Attrs.addAttribute(llvm::Attribute::SExt);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001343 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001344 Attrs.addAttribute(llvm::Attribute::ZExt);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001345 // FALL THROUGH
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001346 case ABIArgInfo::Direct:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001347 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001348 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001349 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001350
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001351 case ABIArgInfo::Indirect:
Rafael Espindola703c47f2012-10-19 05:04:37 +00001352 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001353 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001354
Anders Carlsson20759ad2009-09-16 15:53:40 +00001355 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001356 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001357
Bill Wendlinga7912f82012-10-10 07:36:56 +00001358 Attrs.addAlignmentAttr(AI.getIndirectAlign());
1359
Daniel Dunbarc2304432009-03-18 19:51:01 +00001360 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001361 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1362 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001363 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001364
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001365 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001366 case ABIArgInfo::Expand:
Mike Stump11289f42009-09-09 15:08:12 +00001367 continue;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001368
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001369 case ABIArgInfo::InAlloca:
1370 // inalloca disables readnone and readonly.
1371 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1372 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001373 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001374 }
Mike Stump11289f42009-09-09 15:08:12 +00001375
Hal Finkela2347ba2014-07-18 15:52:10 +00001376 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1377 QualType PTy = RefTy->getPointeeType();
1378 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1379 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1380 .getQuantity());
1381 else if (getContext().getTargetAddressSpace(PTy) == 0)
1382 Attrs.addAttribute(llvm::Attribute::NonNull);
1383 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001384
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001385 if (Attrs.hasAttributes()) {
1386 unsigned FirstIRArg, NumIRArgs;
1387 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1388 for (unsigned i = 0; i < NumIRArgs; i++)
1389 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
1390 FirstIRArg + i + 1, Attrs));
1391 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001392 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001393 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001394
Bill Wendlinga7912f82012-10-10 07:36:56 +00001395 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001396 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001397 AttributeSet::get(getLLVMContext(),
1398 llvm::AttributeSet::FunctionIndex,
1399 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001400}
1401
John McCalla738c252011-03-09 04:27:21 +00001402/// An argument came in as a promoted argument; demote it back to its
1403/// declared type.
1404static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1405 const VarDecl *var,
1406 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001407 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001408
1409 // This can happen with promotions that actually don't change the
1410 // underlying type, like the enum promotions.
1411 if (value->getType() == varType) return value;
1412
1413 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1414 && "unexpected promotion type");
1415
1416 if (isa<llvm::IntegerType>(varType))
1417 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1418
1419 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1420}
1421
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001422static bool shouldAddNonNullAttr(const Decl *FD, const ParmVarDecl *PVD) {
1423 // FIXME: __attribute__((nonnull)) can also be applied to:
1424 // - references to pointers, where the pointee is known to be
1425 // nonnull (apparently a Clang extension)
1426 // - transparent unions containing pointers
1427 // In the former case, LLVM IR cannot represent the constraint. In
1428 // the latter case, we have no guarantee that the transparent union
1429 // is in fact passed as a pointer.
1430 if (!PVD->getType()->isAnyPointerType() &&
1431 !PVD->getType()->isBlockPointerType())
1432 return false;
1433 // First, check attribute on parameter itself.
1434 if (PVD->hasAttr<NonNullAttr>())
1435 return true;
1436 // Check function attributes.
1437 if (!FD)
1438 return false;
1439 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
1440 if (NNAttr->isNonNull(PVD->getFunctionScopeIndex()))
1441 return true;
1442 }
1443 return false;
1444}
1445
Daniel Dunbard931a872009-02-02 22:03:45 +00001446void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1447 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00001448 const FunctionArgList &Args) {
John McCallcaa19452009-07-28 01:00:58 +00001449 // If this is an implicit-return-zero function, go ahead and
1450 // initialize the return value. TODO: it might be nice to have
1451 // a more general mechanism for this that didn't require synthesized
1452 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00001453 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00001454 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00001455 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001456 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00001457 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00001458 Builder.CreateStore(Zero, ReturnValue);
1459 }
1460 }
1461
Mike Stump18bb9282009-05-16 07:57:57 +00001462 // FIXME: We no longer need the types from FunctionArgList; lift up and
1463 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00001464
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001465 ClangToLLVMArgMapping IRFunctionArgs(CGM, FI);
1466 // Flattened function arguments.
1467 SmallVector<llvm::Argument *, 16> FnArgs;
1468 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
1469 for (auto &Arg : Fn->args()) {
1470 FnArgs.push_back(&Arg);
1471 }
1472 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00001473
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001474 // If we're using inalloca, all the memory arguments are GEPs off of the last
1475 // parameter, which is a pointer to the complete memory area.
Craig Topper8a13c412014-05-21 05:09:00 +00001476 llvm::Value *ArgStruct = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001477 if (IRFunctionArgs.hasInallocaArg()) {
1478 ArgStruct = FnArgs[IRFunctionArgs.getInallocaArgNo()];
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001479 assert(ArgStruct->getType() == FI.getArgStruct()->getPointerTo());
1480 }
1481
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001482 // Name the struct return parameter.
1483 if (IRFunctionArgs.hasSRetArg()) {
1484 auto AI = FnArgs[IRFunctionArgs.getSRetArgNo()];
Daniel Dunbar613855c2008-09-09 23:27:19 +00001485 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00001486 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001487 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00001488 }
Mike Stump11289f42009-09-09 15:08:12 +00001489
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001490 // Track if we received the parameter as a pointer (indirect, byval, or
1491 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
1492 // into a local alloca for us.
1493 enum ValOrPointer { HaveValue = 0, HavePointer = 1 };
Reid Kleckner8ae16272014-02-01 00:23:22 +00001494 typedef llvm::PointerIntPair<llvm::Value *, 1> ValueAndIsPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001495 SmallVector<ValueAndIsPtr, 16> ArgVals;
1496 ArgVals.reserve(Args.size());
1497
Reid Kleckner739756c2013-12-04 19:23:12 +00001498 // Create a pointer value for every parameter declaration. This usually
1499 // entails copying one or more LLVM IR arguments into an alloca. Don't push
1500 // any cleanups or do anything that might unwind. We do that separately, so
1501 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00001502 assert(FI.arg_size() == Args.size() &&
1503 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001504 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001505 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001506 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00001507 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00001508 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001509 QualType Ty = info_it->type;
1510 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001511
John McCalla738c252011-03-09 04:27:21 +00001512 bool isPromoted =
1513 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1514
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001515 unsigned FirstIRArg, NumIRArgs;
1516 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00001517
Daniel Dunbard3674e62008-09-11 01:48:57 +00001518 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001519 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001520 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001521 llvm::Value *V = Builder.CreateStructGEP(
1522 ArgStruct, ArgI.getInAllocaFieldIndex(), Arg->getName());
1523 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001524 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001525 }
1526
Daniel Dunbar747865a2009-02-05 09:16:39 +00001527 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001528 assert(NumIRArgs == 1);
1529 llvm::Value *V = FnArgs[FirstIRArg];
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001530
John McCall47fb9502013-03-07 21:37:08 +00001531 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001532 // Aggregates and complex variables are accessed by reference. All we
1533 // need to do is realign the value, if requested
1534 if (ArgI.getIndirectRealign()) {
1535 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1536
1537 // Copy from the incoming argument pointer to the temporary with the
1538 // appropriate alignment.
1539 //
1540 // FIXME: We should have a common utility for generating an aggregate
1541 // copy.
Chris Lattner2192fe52011-07-18 04:24:23 +00001542 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyck705ba072011-01-19 01:58:38 +00001543 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumidd634362011-03-10 14:02:21 +00001544 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1545 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1546 Builder.CreateMemCpy(Dst,
1547 Src,
Ken Dyck705ba072011-01-19 01:58:38 +00001548 llvm::ConstantInt::get(IntPtrTy,
1549 Size.getQuantity()),
Benjamin Krameracc6b4e2010-12-30 00:13:21 +00001550 ArgI.getIndirectAlign(),
1551 false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001552 V = AlignedTemp;
1553 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001554 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001555 } else {
1556 // Load scalar value from indirect argument.
Ken Dyck705ba072011-01-19 01:58:38 +00001557 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
Nick Lewycky2d84e842013-10-02 02:29:49 +00001558 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty,
1559 Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001560
1561 if (isPromoted)
1562 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001563 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001564 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00001565 break;
1566 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001567
1568 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001569 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00001570
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001571 // If we have the trivial case, handle it with no muss and fuss.
1572 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001573 ArgI.getCoerceToType() == ConvertType(Ty) &&
1574 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001575 assert(NumIRArgs == 1);
1576 auto AI = FnArgs[FirstIRArg];
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001577 llvm::Value *V = AI;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001578
Hal Finkel48d53e22014-07-19 01:41:07 +00001579 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001580 if (shouldAddNonNullAttr(CurCodeDecl, PVD))
Hal Finkel82504f02014-07-11 17:35:21 +00001581 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1582 AI->getArgNo() + 1,
1583 llvm::Attribute::NonNull));
1584
Hal Finkel48d53e22014-07-19 01:41:07 +00001585 QualType OTy = PVD->getOriginalType();
1586 if (const auto *ArrTy =
1587 getContext().getAsConstantArrayType(OTy)) {
1588 // A C99 array parameter declaration with the static keyword also
1589 // indicates dereferenceability, and if the size is constant we can
1590 // use the dereferenceable attribute (which requires the size in
1591 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00001592 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00001593 QualType ETy = ArrTy->getElementType();
1594 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
1595 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
1596 ArrSize) {
1597 llvm::AttrBuilder Attrs;
1598 Attrs.addDereferenceableAttr(
1599 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
1600 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1601 AI->getArgNo() + 1, Attrs));
1602 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
1603 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1604 AI->getArgNo() + 1,
1605 llvm::Attribute::NonNull));
1606 }
1607 }
1608 } else if (const auto *ArrTy =
1609 getContext().getAsVariableArrayType(OTy)) {
1610 // For C99 VLAs with the static keyword, we don't know the size so
1611 // we can't use the dereferenceable attribute, but in addrspace(0)
1612 // we know that it must be nonnull.
1613 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
1614 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
1615 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1616 AI->getArgNo() + 1,
1617 llvm::Attribute::NonNull));
1618 }
1619 }
1620
Bill Wendling507c3512012-10-16 05:23:44 +00001621 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001622 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1623 AI->getArgNo() + 1,
1624 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00001625
Chris Lattner7369c142011-07-20 06:29:00 +00001626 // Ensure the argument is the correct type.
1627 if (V->getType() != ArgI.getCoerceToType())
1628 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1629
John McCalla738c252011-03-09 04:27:21 +00001630 if (isPromoted)
1631 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00001632
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001633 if (const CXXMethodDecl *MD =
1634 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001635 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001636 V = CGM.getCXXABI().
1637 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001638 }
1639
Rafael Espindola8778c282012-11-29 16:09:03 +00001640 // Because of merging of function types from multiple decls it is
1641 // possible for the type of an argument to not match the corresponding
1642 // type in the function type. Since we are codegening the callee
1643 // in here, add a cast to the argument type.
1644 llvm::Type *LTy = ConvertType(Arg->getType());
1645 if (V->getType() != LTy)
1646 V = Builder.CreateBitCast(V, LTy);
1647
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001648 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001649 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00001650 }
Mike Stump11289f42009-09-09 15:08:12 +00001651
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001652 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001653
Chris Lattnerff941a62010-07-28 18:24:28 +00001654 // The alignment we need to use is the max of the requested alignment for
1655 // the argument plus the alignment required by our access code below.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001656 unsigned AlignmentToUse =
Micah Villmowdd31ca12012-10-08 16:25:52 +00001657 CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerff941a62010-07-28 18:24:28 +00001658 AlignmentToUse = std::max(AlignmentToUse,
1659 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001660
Chris Lattnerff941a62010-07-28 18:24:28 +00001661 Alloca->setAlignment(AlignmentToUse);
Chris Lattnerc401de92010-07-05 20:21:00 +00001662 llvm::Value *V = Alloca;
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001663 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001664
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001665 // If the value is offset in memory, apply the offset now.
1666 if (unsigned Offs = ArgI.getDirectOffset()) {
1667 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1668 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001669 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001670 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1671 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001672
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001673 // Fast-isel and the optimizer generally like scalar values better than
1674 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001675 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001676 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
1677 STy->getNumElements() > 1) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001678 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001679 llvm::Type *DstTy =
1680 cast<llvm::PointerType>(Ptr->getType())->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00001681 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001682
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001683 if (SrcSize <= DstSize) {
1684 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1685
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001686 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001687 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001688 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001689 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1690 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001691 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001692 }
1693 } else {
1694 llvm::AllocaInst *TempAlloca =
1695 CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1696 TempAlloca->setAlignment(AlignmentToUse);
1697 llvm::Value *TempV = TempAlloca;
1698
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001699 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001700 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001701 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001702 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1703 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(TempV, 0, i);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001704 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001705 }
1706
1707 Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
Chris Lattner15ec3612010-06-29 00:06:42 +00001708 }
1709 } else {
1710 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001711 assert(NumIRArgs == 1);
1712 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00001713 AI->setName(Arg->getName() + ".coerce");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001714 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00001715 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001716
1717
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001718 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00001719 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001720 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001721 if (isPromoted)
1722 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001723 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
1724 } else {
1725 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00001726 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001727 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001728 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001729
1730 case ABIArgInfo::Expand: {
1731 // If this structure was expanded into multiple arguments then
1732 // we need to create a temporary and reconstruct it from the
1733 // arguments.
Eli Friedman3d9f47f2011-11-03 21:39:02 +00001734 llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
Eli Friedmana0544d62011-12-03 04:14:32 +00001735 CharUnits Align = getContext().getDeclAlign(Arg);
1736 Alloca->setAlignment(Align.getQuantity());
1737 LValue LV = MakeAddrLValue(Alloca, Ty, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001738 ArgVals.push_back(ValueAndIsPtr(Alloca, HavePointer));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001739
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001740 auto FnArgIter = FnArgs.begin() + FirstIRArg;
1741 ExpandTypeFromArgs(Ty, LV, FnArgIter);
1742 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
1743 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
1744 auto AI = FnArgs[FirstIRArg + i];
1745 AI->setName(Arg->getName() + "." + Twine(i));
1746 }
1747 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001748 }
1749
1750 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001751 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001752 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001753 if (!hasScalarEvaluationKind(Ty)) {
1754 ArgVals.push_back(ValueAndIsPtr(CreateMemTemp(Ty), HavePointer));
1755 } else {
1756 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
1757 ArgVals.push_back(ValueAndIsPtr(U, HaveValue));
1758 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001759 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001760 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00001761 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001762
Reid Kleckner739756c2013-12-04 19:23:12 +00001763 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1764 for (int I = Args.size() - 1; I >= 0; --I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001765 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1766 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00001767 } else {
1768 for (unsigned I = 0, E = Args.size(); I != E; ++I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001769 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1770 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00001771 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00001772}
1773
John McCallffa2c1a2012-01-29 07:46:59 +00001774static void eraseUnusedBitCasts(llvm::Instruction *insn) {
1775 while (insn->use_empty()) {
1776 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
1777 if (!bitcast) return;
1778
1779 // This is "safe" because we would have used a ConstantExpr otherwise.
1780 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
1781 bitcast->eraseFromParent();
1782 }
1783}
1784
John McCall31168b02011-06-15 23:02:42 +00001785/// Try to emit a fused autorelease of a return result.
1786static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
1787 llvm::Value *result) {
1788 // We must be immediately followed the cast.
1789 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00001790 if (BB->empty()) return nullptr;
1791 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001792
Chris Lattner2192fe52011-07-18 04:24:23 +00001793 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00001794
1795 // result is in a BasicBlock and is therefore an Instruction.
1796 llvm::Instruction *generator = cast<llvm::Instruction>(result);
1797
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001798 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00001799
1800 // Look for:
1801 // %generator = bitcast %type1* %generator2 to %type2*
1802 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
1803 // We would have emitted this as a constant if the operand weren't
1804 // an Instruction.
1805 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
1806
1807 // Require the generator to be immediately followed by the cast.
1808 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00001809 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001810
1811 insnsToKill.push_back(bitcast);
1812 }
1813
1814 // Look for:
1815 // %generator = call i8* @objc_retain(i8* %originalResult)
1816 // or
1817 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
1818 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00001819 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001820
1821 bool doRetainAutorelease;
1822
1823 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
1824 doRetainAutorelease = true;
1825 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
1826 .objc_retainAutoreleasedReturnValue) {
1827 doRetainAutorelease = false;
1828
John McCallcfa4e9b2012-09-07 23:30:50 +00001829 // If we emitted an assembly marker for this call (and the
1830 // ARCEntrypoints field should have been set if so), go looking
1831 // for that call. If we can't find it, we can't do this
1832 // optimization. But it should always be the immediately previous
1833 // instruction, unless we needed bitcasts around the call.
1834 if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
1835 llvm::Instruction *prev = call->getPrevNode();
1836 assert(prev);
1837 if (isa<llvm::BitCastInst>(prev)) {
1838 prev = prev->getPrevNode();
1839 assert(prev);
1840 }
1841 assert(isa<llvm::CallInst>(prev));
1842 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
1843 CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
1844 insnsToKill.push_back(prev);
1845 }
John McCall31168b02011-06-15 23:02:42 +00001846 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00001847 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001848 }
1849
1850 result = call->getArgOperand(0);
1851 insnsToKill.push_back(call);
1852
1853 // Keep killing bitcasts, for sanity. Note that we no longer care
1854 // about precise ordering as long as there's exactly one use.
1855 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
1856 if (!bitcast->hasOneUse()) break;
1857 insnsToKill.push_back(bitcast);
1858 result = bitcast->getOperand(0);
1859 }
1860
1861 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001862 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00001863 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
1864 (*i)->eraseFromParent();
1865
1866 // Do the fused retain/autorelease if we were asked to.
1867 if (doRetainAutorelease)
1868 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
1869
1870 // Cast back to the result type.
1871 return CGF.Builder.CreateBitCast(result, resultType);
1872}
1873
John McCallffa2c1a2012-01-29 07:46:59 +00001874/// If this is a +1 of the value of an immutable 'self', remove it.
1875static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
1876 llvm::Value *result) {
1877 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00001878 const ObjCMethodDecl *method =
1879 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00001880 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00001881 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00001882 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00001883
1884 // Look for a retain call.
1885 llvm::CallInst *retainCall =
1886 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
1887 if (!retainCall ||
1888 retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00001889 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00001890
1891 // Look for an ordinary load of 'self'.
1892 llvm::Value *retainedValue = retainCall->getArgOperand(0);
1893 llvm::LoadInst *load =
1894 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
1895 if (!load || load->isAtomic() || load->isVolatile() ||
1896 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
Craig Topper8a13c412014-05-21 05:09:00 +00001897 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00001898
1899 // Okay! Burn it all down. This relies for correctness on the
1900 // assumption that the retain is emitted as part of the return and
1901 // that thereafter everything is used "linearly".
1902 llvm::Type *resultType = result->getType();
1903 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
1904 assert(retainCall->use_empty());
1905 retainCall->eraseFromParent();
1906 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
1907
1908 return CGF.Builder.CreateBitCast(load, resultType);
1909}
1910
John McCall31168b02011-06-15 23:02:42 +00001911/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00001912///
1913/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00001914static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
1915 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00001916 // If we're returning 'self', kill the initial retain. This is a
1917 // heuristic attempt to "encourage correctness" in the really unfortunate
1918 // case where we have a return of self during a dealloc and we desperately
1919 // need to avoid the possible autorelease.
1920 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
1921 return self;
1922
John McCall31168b02011-06-15 23:02:42 +00001923 // At -O0, try to emit a fused retain/autorelease.
1924 if (CGF.shouldUseFusedARCCalls())
1925 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
1926 return fused;
1927
1928 return CGF.EmitARCAutoreleaseReturnValue(result);
1929}
1930
John McCall6e1c0122012-01-29 02:35:02 +00001931/// Heuristically search for a dominating store to the return-value slot.
1932static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
1933 // If there are multiple uses of the return-value slot, just check
1934 // for something immediately preceding the IP. Sometimes this can
1935 // happen with how we generate implicit-returns; it can also happen
1936 // with noreturn cleanups.
1937 if (!CGF.ReturnValue->hasOneUse()) {
1938 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00001939 if (IP->empty()) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00001940 llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back());
Craig Topper8a13c412014-05-21 05:09:00 +00001941 if (!store) return nullptr;
1942 if (store->getPointerOperand() != CGF.ReturnValue) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00001943 assert(!store->isAtomic() && !store->isVolatile()); // see below
1944 return store;
1945 }
1946
1947 llvm::StoreInst *store =
Chandler Carruth4d01fff2014-03-09 03:16:50 +00001948 dyn_cast<llvm::StoreInst>(CGF.ReturnValue->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00001949 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00001950
1951 // These aren't actually possible for non-coerced returns, and we
1952 // only care about non-coerced returns on this code path.
1953 assert(!store->isAtomic() && !store->isVolatile());
1954
1955 // Now do a first-and-dirty dominance check: just walk up the
1956 // single-predecessors chain from the current insertion point.
1957 llvm::BasicBlock *StoreBB = store->getParent();
1958 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
1959 while (IP != StoreBB) {
1960 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00001961 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00001962 }
1963
1964 // Okay, the store's basic block dominates the insertion point; we
1965 // can do our thing.
1966 return store;
1967}
1968
Adrian Prantl3be10542013-05-02 17:30:20 +00001969void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001970 bool EmitRetDbgLoc,
1971 SourceLocation EndLoc) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001972 // Functions with no result always return void.
Craig Topper8a13c412014-05-21 05:09:00 +00001973 if (!ReturnValue) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001974 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00001975 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001976 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00001977
Dan Gohman481e40c2010-07-20 20:13:52 +00001978 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00001979 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00001980 QualType RetTy = FI.getReturnType();
1981 const ABIArgInfo &RetAI = FI.getReturnInfo();
1982
1983 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001984 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001985 // Aggregrates get evaluated directly into the destination. Sometimes we
1986 // need to return the sret value in a register, though.
1987 assert(hasAggregateEvaluationKind(RetTy));
1988 if (RetAI.getInAllocaSRet()) {
1989 llvm::Function::arg_iterator EI = CurFn->arg_end();
1990 --EI;
1991 llvm::Value *ArgStruct = EI;
1992 llvm::Value *SRet =
1993 Builder.CreateStructGEP(ArgStruct, RetAI.getInAllocaFieldIndex());
1994 RV = Builder.CreateLoad(SRet, "sret");
1995 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001996 break;
1997
Daniel Dunbar03816342010-08-21 02:24:36 +00001998 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00001999 auto AI = CurFn->arg_begin();
2000 if (RetAI.isSRetAfterThis())
2001 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002002 switch (getEvaluationKind(RetTy)) {
2003 case TEK_Complex: {
2004 ComplexPairTy RT =
Nick Lewycky2d84e842013-10-02 02:29:49 +00002005 EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
2006 EndLoc);
Reid Kleckner37abaca2014-05-09 22:46:15 +00002007 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002008 /*isInit*/ true);
2009 break;
2010 }
2011 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002012 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002013 break;
2014 case TEK_Scalar:
2015 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Reid Kleckner37abaca2014-05-09 22:46:15 +00002016 MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002017 /*isInit*/ true);
2018 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002019 }
2020 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002021 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002022
2023 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002024 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002025 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2026 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002027 // The internal return value temp always will have pointer-to-return-type
2028 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002029
John McCall6e1c0122012-01-29 02:35:02 +00002030 // If there is a dominating store to ReturnValue, we can elide
2031 // the load, zap the store, and usually zap the alloca.
2032 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002033 // Reuse the debug location from the store unless there is
2034 // cleanup code to be emitted between the store and return
2035 // instruction.
2036 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002037 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002038 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002039 RV = SI->getValueOperand();
2040 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002041
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002042 // If that was the only use of the return value, nuke it as well now.
2043 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
2044 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00002045 ReturnValue = nullptr;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002046 }
John McCall6e1c0122012-01-29 02:35:02 +00002047
2048 // Otherwise, we have to do a simple load.
2049 } else {
2050 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002051 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002052 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002053 llvm::Value *V = ReturnValue;
2054 // If the value is offset in memory, apply the offset now.
2055 if (unsigned Offs = RetAI.getDirectOffset()) {
2056 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
2057 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002058 V = Builder.CreateBitCast(V,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002059 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
2060 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002061
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002062 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002063 }
John McCall31168b02011-06-15 23:02:42 +00002064
2065 // In ARC, end functions that return a retainable type with a call
2066 // to objc_autoreleaseReturnValue.
2067 if (AutoreleaseResult) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002068 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002069 !FI.isReturnsRetained() &&
2070 RetTy->isObjCRetainableType());
2071 RV = emitAutoreleaseOfResult(*this, RV);
2072 }
2073
Chris Lattner726b3d02010-06-26 23:13:19 +00002074 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002075
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002076 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002077 break;
2078
2079 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002080 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002081 }
2082
Alexey Samsonovde443c52014-08-13 00:26:40 +00002083 llvm::Instruction *Ret;
2084 if (RV) {
2085 if (SanOpts->ReturnsNonnullAttribute &&
2086 CurGD.getDecl()->hasAttr<ReturnsNonNullAttr>()) {
2087 SanitizerScope SanScope(this);
2088 llvm::Value *Cond =
2089 Builder.CreateICmpNE(RV, llvm::Constant::getNullValue(RV->getType()));
2090 llvm::Constant *StaticData[] = {
2091 EmitCheckSourceLocation(EndLoc)
2092 };
Craig Topper5fc8fc22014-08-27 06:28:36 +00002093 EmitCheck(Cond, "nonnull_return", StaticData, None, CRK_Recoverable);
Alexey Samsonovde443c52014-08-13 00:26:40 +00002094 }
2095 Ret = Builder.CreateRet(RV);
2096 } else {
2097 Ret = Builder.CreateRetVoid();
2098 }
2099
Devang Patel65497582010-07-21 18:08:50 +00002100 if (!RetDbgLoc.isUnknown())
2101 Ret->setDebugLoc(RetDbgLoc);
Daniel Dunbar613855c2008-09-09 23:27:19 +00002102}
2103
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002104static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2105 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2106 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2107}
2108
2109static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty) {
2110 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2111 // placeholders.
2112 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2113 llvm::Value *Placeholder =
2114 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2115 Placeholder = CGF.Builder.CreateLoad(Placeholder);
2116 return AggValueSlot::forAddr(Placeholder, CharUnits::Zero(),
2117 Ty.getQualifiers(),
2118 AggValueSlot::IsNotDestructed,
2119 AggValueSlot::DoesNotNeedGCBarriers,
2120 AggValueSlot::IsNotAliased);
2121}
2122
John McCall32ea9692011-03-11 20:59:21 +00002123void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002124 const VarDecl *param,
2125 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002126 // StartFunction converted the ABI-lowered parameter(s) into a
2127 // local alloca. We need to turn that into an r-value suitable
2128 // for EmitCall.
John McCall32ea9692011-03-11 20:59:21 +00002129 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002130
John McCall32ea9692011-03-11 20:59:21 +00002131 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002132
John McCall23f66262010-05-26 22:34:26 +00002133 // For the most part, we just need to load the alloca, except:
2134 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall47fb9502013-03-07 21:37:08 +00002135 // 2) references to non-scalars are pointers directly to the aggregate.
2136 // I don't know why references to scalars are different here.
John McCall32ea9692011-03-11 20:59:21 +00002137 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall47fb9502013-03-07 21:37:08 +00002138 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall32ea9692011-03-11 20:59:21 +00002139 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00002140
2141 // Locals which are references to scalars are represented
2142 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00002143 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00002144 }
2145
Reid Klecknerab2090d2014-07-26 01:34:32 +00002146 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2147 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002148
Nick Lewycky2d84e842013-10-02 02:29:49 +00002149 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00002150}
2151
John McCall31168b02011-06-15 23:02:42 +00002152static bool isProvablyNull(llvm::Value *addr) {
2153 return isa<llvm::ConstantPointerNull>(addr);
2154}
2155
2156static bool isProvablyNonNull(llvm::Value *addr) {
2157 return isa<llvm::AllocaInst>(addr);
2158}
2159
2160/// Emit the actual writing-back of a writeback.
2161static void emitWriteback(CodeGenFunction &CGF,
2162 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002163 const LValue &srcLV = writeback.Source;
2164 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002165 assert(!isProvablyNull(srcAddr) &&
2166 "shouldn't have writeback for provably null argument");
2167
Craig Topper8a13c412014-05-21 05:09:00 +00002168 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002169
2170 // If the argument wasn't provably non-null, we need to null check
2171 // before doing the store.
2172 bool provablyNonNull = isProvablyNonNull(srcAddr);
2173 if (!provablyNonNull) {
2174 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2175 contBB = CGF.createBasicBlock("icr.done");
2176
2177 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2178 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2179 CGF.EmitBlock(writebackBB);
2180 }
2181
2182 // Load the value to writeback.
2183 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2184
2185 // Cast it back, in case we're writing an id to a Foo* or something.
2186 value = CGF.Builder.CreateBitCast(value,
2187 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
2188 "icr.writeback-cast");
2189
2190 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00002191
2192 // If we have a "to use" value, it's something we need to emit a use
2193 // of. This has to be carefully threaded in: if it's done after the
2194 // release it's potentially undefined behavior (and the optimizer
2195 // will ignore it), and if it happens before the retain then the
2196 // optimizer could move the release there.
2197 if (writeback.ToUse) {
2198 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2199
2200 // Retain the new value. No need to block-copy here: the block's
2201 // being passed up the stack.
2202 value = CGF.EmitARCRetainNonBlock(value);
2203
2204 // Emit the intrinsic use here.
2205 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2206
2207 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00002208 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00002209
2210 // Put the new value in place (primitively).
2211 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2212
2213 // Release the old value.
2214 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2215
2216 // Otherwise, we can just do a normal lvalue store.
2217 } else {
2218 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2219 }
John McCall31168b02011-06-15 23:02:42 +00002220
2221 // Jump to the continuation block.
2222 if (!provablyNonNull)
2223 CGF.EmitBlock(contBB);
2224}
2225
2226static void emitWritebacks(CodeGenFunction &CGF,
2227 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00002228 for (const auto &I : args.writebacks())
2229 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00002230}
2231
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002232static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2233 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002234 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002235 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2236 CallArgs.getCleanupsToDeactivate();
2237 // Iterate in reverse to increase the likelihood of popping the cleanup.
2238 for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
2239 I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
2240 CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
2241 I->IsActiveIP->eraseFromParent();
2242 }
2243}
2244
John McCalleff18842013-03-23 02:35:54 +00002245static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2246 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2247 if (uop->getOpcode() == UO_AddrOf)
2248 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002249 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00002250}
2251
John McCall31168b02011-06-15 23:02:42 +00002252/// Emit an argument that's being passed call-by-writeback. That is,
2253/// we are passing the address of
2254static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2255 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00002256 LValue srcLV;
2257
2258 // Make an optimistic effort to emit the address as an l-value.
2259 // This can fail if the the argument expression is more complicated.
2260 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2261 srcLV = CGF.EmitLValue(lvExpr);
2262
2263 // Otherwise, just emit it as a scalar.
2264 } else {
2265 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
2266
2267 QualType srcAddrType =
2268 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
2269 srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
2270 }
2271 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002272
2273 // The dest and src types don't necessarily match in LLVM terms
2274 // because of the crazy ObjC compatibility rules.
2275
Chris Lattner2192fe52011-07-18 04:24:23 +00002276 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00002277 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
2278
2279 // If the address is a constant null, just pass the appropriate null.
2280 if (isProvablyNull(srcAddr)) {
2281 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
2282 CRE->getType());
2283 return;
2284 }
2285
John McCall31168b02011-06-15 23:02:42 +00002286 // Create the temporary.
2287 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
2288 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002289 // Loading an l-value can introduce a cleanup if the l-value is __weak,
2290 // and that cleanup will be conditional if we can't prove that the l-value
2291 // isn't null, so we need to register a dominating point so that the cleanups
2292 // system will make valid IR.
2293 CodeGenFunction::ConditionalEvaluation condEval(CGF);
2294
John McCall31168b02011-06-15 23:02:42 +00002295 // Zero-initialize it if we're not doing a copy-initialization.
2296 bool shouldCopy = CRE->shouldCopy();
2297 if (!shouldCopy) {
2298 llvm::Value *null =
2299 llvm::ConstantPointerNull::get(
2300 cast<llvm::PointerType>(destType->getElementType()));
2301 CGF.Builder.CreateStore(null, temp);
2302 }
Craig Topper8a13c412014-05-21 05:09:00 +00002303
2304 llvm::BasicBlock *contBB = nullptr;
2305 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002306
2307 // If the address is *not* known to be non-null, we need to switch.
2308 llvm::Value *finalArgument;
2309
2310 bool provablyNonNull = isProvablyNonNull(srcAddr);
2311 if (provablyNonNull) {
2312 finalArgument = temp;
2313 } else {
2314 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2315
2316 finalArgument = CGF.Builder.CreateSelect(isNull,
2317 llvm::ConstantPointerNull::get(destType),
2318 temp, "icr.argument");
2319
2320 // If we need to copy, then the load has to be conditional, which
2321 // means we need control flow.
2322 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00002323 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002324 contBB = CGF.createBasicBlock("icr.cont");
2325 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
2326 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
2327 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002328 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00002329 }
2330 }
2331
Craig Topper8a13c412014-05-21 05:09:00 +00002332 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00002333
John McCall31168b02011-06-15 23:02:42 +00002334 // Perform a copy if necessary.
2335 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002336 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002337 assert(srcRV.isScalar());
2338
2339 llvm::Value *src = srcRV.getScalarVal();
2340 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
2341 "icr.cast");
2342
2343 // Use an ordinary store, not a store-to-lvalue.
2344 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00002345
2346 // If optimization is enabled, and the value was held in a
2347 // __strong variable, we need to tell the optimizer that this
2348 // value has to stay alive until we're doing the store back.
2349 // This is because the temporary is effectively unretained,
2350 // and so otherwise we can violate the high-level semantics.
2351 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2352 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
2353 valueToUse = src;
2354 }
John McCall31168b02011-06-15 23:02:42 +00002355 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002356
John McCall31168b02011-06-15 23:02:42 +00002357 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002358 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00002359 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002360 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00002361
2362 // Make a phi for the value to intrinsically use.
2363 if (valueToUse) {
2364 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2365 "icr.to-use");
2366 phiToUse->addIncoming(valueToUse, copyBB);
2367 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2368 originBB);
2369 valueToUse = phiToUse;
2370 }
2371
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002372 condEval.end(CGF);
2373 }
John McCall31168b02011-06-15 23:02:42 +00002374
John McCalleff18842013-03-23 02:35:54 +00002375 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00002376 args.add(RValue::get(finalArgument), CRE->getType());
2377}
2378
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002379void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
2380 assert(!StackBase && !StackCleanup.isValid());
2381
2382 // Save the stack.
2383 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
2384 StackBase = CGF.Builder.CreateCall(F, "inalloca.save");
2385
2386 // Control gets really tied up in landing pads, so we have to spill the
2387 // stacksave to an alloca to avoid violating SSA form.
2388 // TODO: This is dead if we never emit the cleanup. We should create the
2389 // alloca and store lazily on the first cleanup emission.
2390 StackBaseMem = CGF.CreateTempAlloca(CGF.Int8PtrTy, "inalloca.spmem");
2391 CGF.Builder.CreateStore(StackBase, StackBaseMem);
2392 CGF.pushStackRestore(EHCleanup, StackBaseMem);
2393 StackCleanup = CGF.EHStack.getInnermostEHScope();
2394 assert(StackCleanup.isValid());
2395}
2396
2397void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
2398 if (StackBase) {
2399 CGF.DeactivateCleanupBlock(StackCleanup, StackBase);
2400 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
2401 // We could load StackBase from StackBaseMem, but in the non-exceptional
2402 // case we can skip it.
2403 CGF.Builder.CreateCall(F, StackBase);
2404 }
2405}
2406
Reid Kleckner739756c2013-12-04 19:23:12 +00002407void CodeGenFunction::EmitCallArgs(CallArgList &Args,
2408 ArrayRef<QualType> ArgTypes,
2409 CallExpr::const_arg_iterator ArgBeg,
2410 CallExpr::const_arg_iterator ArgEnd,
2411 bool ForceColumnInfo) {
2412 CGDebugInfo *DI = getDebugInfo();
2413 SourceLocation CallLoc;
2414 if (DI) CallLoc = DI->getLocation();
2415
2416 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
2417 // because arguments are destroyed left to right in the callee.
2418 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002419 // Insert a stack save if we're going to need any inalloca args.
2420 bool HasInAllocaArgs = false;
2421 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
2422 I != E && !HasInAllocaArgs; ++I)
2423 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
2424 if (HasInAllocaArgs) {
2425 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2426 Args.allocateArgumentMemory(*this);
2427 }
2428
2429 // Evaluate each argument.
Reid Kleckner739756c2013-12-04 19:23:12 +00002430 size_t CallArgsStart = Args.size();
2431 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
2432 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2433 EmitCallArg(Args, *Arg, ArgTypes[I]);
2434 // Restore the debug location.
2435 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2436 }
2437
2438 // Un-reverse the arguments we just evaluated so they match up with the LLVM
2439 // IR function.
2440 std::reverse(Args.begin() + CallArgsStart, Args.end());
2441 return;
2442 }
2443
2444 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
2445 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2446 assert(Arg != ArgEnd);
2447 EmitCallArg(Args, *Arg, ArgTypes[I]);
2448 // Restore the debug location.
2449 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2450 }
2451}
2452
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002453namespace {
2454
2455struct DestroyUnpassedArg : EHScopeStack::Cleanup {
2456 DestroyUnpassedArg(llvm::Value *Addr, QualType Ty)
2457 : Addr(Addr), Ty(Ty) {}
2458
2459 llvm::Value *Addr;
2460 QualType Ty;
2461
Craig Topper4f12f102014-03-12 06:41:41 +00002462 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002463 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
2464 assert(!Dtor->isTrivial());
2465 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
2466 /*Delegating=*/false, Addr);
2467 }
2468};
2469
2470}
2471
John McCall32ea9692011-03-11 20:59:21 +00002472void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2473 QualType type) {
John McCall31168b02011-06-15 23:02:42 +00002474 if (const ObjCIndirectCopyRestoreExpr *CRE
2475 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002476 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00002477 assert(getContext().hasSameType(E->getType(), type));
2478 return emitWritebackArg(*this, args, CRE);
2479 }
2480
John McCall0a76c0c2011-08-26 18:42:59 +00002481 assert(type->isReferenceType() == E->isGLValue() &&
2482 "reference binding to unmaterialized r-value!");
2483
John McCall17054bd62011-08-26 21:08:13 +00002484 if (E->isGLValue()) {
2485 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00002486 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00002487 }
Mike Stump11289f42009-09-09 15:08:12 +00002488
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002489 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2490
2491 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2492 // However, we still have to push an EH-only cleanup in case we unwind before
2493 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00002494 if (HasAggregateEvalKind &&
2495 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2496 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00002497 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00002498 AggValueSlot Slot;
2499 if (args.isUsingInAlloca())
2500 Slot = createPlaceholderSlot(*this, type);
2501 else
2502 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00002503
2504 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2505 bool DestroyedInCallee =
2506 RD && RD->hasNonTrivialDestructor() &&
2507 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
2508 if (DestroyedInCallee)
2509 Slot.setExternallyDestructed();
2510
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002511 EmitAggExpr(E, Slot);
2512 RValue RV = Slot.asRValue();
2513 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002514
Reid Klecknere39ee212014-05-03 00:33:28 +00002515 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002516 // Create a no-op GEP between the placeholder and the cleanup so we can
2517 // RAUW it successfully. It also serves as a marker of the first
2518 // instruction where the cleanup is active.
2519 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddr(), type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002520 // This unreachable is a temporary marker which will be removed later.
2521 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2522 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002523 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002524 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002525 }
2526
2527 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00002528 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2529 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2530 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00002531 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2532 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2533 } else {
2534 // We can't represent a misaligned lvalue in the CallArgList, so copy
2535 // to an aligned temporary now.
2536 llvm::Value *tmp = CreateMemTemp(type);
2537 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2538 L.getAlignment());
2539 args.add(RValue::getAggregate(tmp), type);
2540 }
Eli Friedmandf968192011-05-26 00:10:27 +00002541 return;
2542 }
2543
John McCall32ea9692011-03-11 20:59:21 +00002544 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00002545}
2546
Dan Gohman515a60d2012-02-16 00:57:37 +00002547// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2548// optimizer it can aggressively ignore unwind edges.
2549void
2550CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2551 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2552 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2553 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2554 CGM.getNoObjCARCExceptionsMetadata());
2555}
2556
John McCall882987f2013-02-28 19:01:20 +00002557/// Emits a call to the given no-arguments nounwind runtime function.
2558llvm::CallInst *
2559CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2560 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002561 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002562}
2563
2564/// Emits a call to the given nounwind runtime function.
2565llvm::CallInst *
2566CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2567 ArrayRef<llvm::Value*> args,
2568 const llvm::Twine &name) {
2569 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2570 call->setDoesNotThrow();
2571 return call;
2572}
2573
2574/// Emits a simple call (never an invoke) to the given no-arguments
2575/// runtime function.
2576llvm::CallInst *
2577CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2578 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002579 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002580}
2581
2582/// Emits a simple call (never an invoke) to the given runtime
2583/// function.
2584llvm::CallInst *
2585CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2586 ArrayRef<llvm::Value*> args,
2587 const llvm::Twine &name) {
2588 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2589 call->setCallingConv(getRuntimeCC());
2590 return call;
2591}
2592
2593/// Emits a call or invoke to the given noreturn runtime function.
2594void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2595 ArrayRef<llvm::Value*> args) {
2596 if (getInvokeDest()) {
2597 llvm::InvokeInst *invoke =
2598 Builder.CreateInvoke(callee,
2599 getUnreachableBlock(),
2600 getInvokeDest(),
2601 args);
2602 invoke->setDoesNotReturn();
2603 invoke->setCallingConv(getRuntimeCC());
2604 } else {
2605 llvm::CallInst *call = Builder.CreateCall(callee, args);
2606 call->setDoesNotReturn();
2607 call->setCallingConv(getRuntimeCC());
2608 Builder.CreateUnreachable();
2609 }
Justin Bogner06bd6d02014-01-13 21:24:18 +00002610 PGO.setCurrentRegionUnreachable();
John McCall882987f2013-02-28 19:01:20 +00002611}
2612
2613/// Emits a call or invoke instruction to the given nullary runtime
2614/// function.
2615llvm::CallSite
2616CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2617 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002618 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002619}
2620
2621/// Emits a call or invoke instruction to the given runtime function.
2622llvm::CallSite
2623CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2624 ArrayRef<llvm::Value*> args,
2625 const Twine &name) {
2626 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2627 callSite.setCallingConv(getRuntimeCC());
2628 return callSite;
2629}
2630
2631llvm::CallSite
2632CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2633 const Twine &Name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002634 return EmitCallOrInvoke(Callee, None, Name);
John McCall882987f2013-02-28 19:01:20 +00002635}
2636
John McCallbd309292010-07-06 01:34:17 +00002637/// Emits a call or invoke instruction to the given function, depending
2638/// on the current state of the EH stack.
2639llvm::CallSite
2640CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00002641 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002642 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00002643 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00002644
Dan Gohman515a60d2012-02-16 00:57:37 +00002645 llvm::Instruction *Inst;
2646 if (!InvokeDest)
2647 Inst = Builder.CreateCall(Callee, Args, Name);
2648 else {
2649 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
2650 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
2651 EmitBlock(ContBB);
2652 }
2653
2654 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2655 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002656 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00002657 AddObjCARCExceptionMetadata(Inst);
2658
2659 return Inst;
John McCallbd309292010-07-06 01:34:17 +00002660}
2661
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002662void CodeGenFunction::ExpandTypeToArgs(
2663 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
2664 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002665 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2666 unsigned NumElts = AT->getSize().getZExtValue();
2667 QualType EltTy = AT->getElementType();
2668 llvm::Value *Addr = RV.getAggregateAddr();
2669 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
2670 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, Elt);
Nick Lewycky2d84e842013-10-02 02:29:49 +00002671 RValue EltRV = convertTempToRValue(EltAddr, EltTy, SourceLocation());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002672 ExpandTypeToArgs(EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
Chris Lattnerd59d8672011-07-12 06:29:11 +00002673 }
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002674 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002675 RecordDecl *RD = RT->getDecl();
2676 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
Eli Friedman7f1ff602012-04-16 03:54:45 +00002677 LValue LV = MakeAddrLValue(RV.getAggregateAddr(), Ty);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002678
2679 if (RD->isUnion()) {
Craig Topper8a13c412014-05-21 05:09:00 +00002680 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002681 CharUnits UnionSize = CharUnits::Zero();
2682
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002683 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002684 assert(!FD->isBitField() &&
2685 "Cannot expand structure with bit-field members.");
2686 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
2687 if (UnionSize < FieldSize) {
2688 UnionSize = FieldSize;
2689 LargestFD = FD;
2690 }
2691 }
2692 if (LargestFD) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002693 RValue FldRV = EmitRValueForField(LV, LargestFD, SourceLocation());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002694 ExpandTypeToArgs(LargestFD->getType(), FldRV, IRFuncTy, IRCallArgs,
2695 IRCallArgPos);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002696 }
2697 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002698 for (const auto *FD : RD->fields()) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002699 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002700 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs, IRCallArgPos);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002701 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00002702 }
Eli Friedman95ff7002011-11-15 02:46:03 +00002703 } else if (Ty->isAnyComplexType()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002704 ComplexPairTy CV = RV.getComplexVal();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002705 IRCallArgs[IRCallArgPos++] = CV.first;
2706 IRCallArgs[IRCallArgPos++] = CV.second;
Bob Wilsone826a2a2011-08-03 05:58:22 +00002707 } else {
Chris Lattnerd59d8672011-07-12 06:29:11 +00002708 assert(RV.isScalar() &&
2709 "Unexpected non-scalar rvalue during struct expansion.");
2710
2711 // Insert a bitcast as needed.
2712 llvm::Value *V = RV.getScalarVal();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002713 if (IRCallArgPos < IRFuncTy->getNumParams() &&
2714 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
2715 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
Chris Lattnerd59d8672011-07-12 06:29:11 +00002716
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002717 IRCallArgs[IRCallArgPos++] = V;
Chris Lattnerd59d8672011-07-12 06:29:11 +00002718 }
2719}
2720
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002721/// \brief Store a non-aggregate value to an address to initialize it. For
2722/// initialization, a non-atomic store will be used.
2723static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
2724 LValue Dst) {
2725 if (Src.isScalar())
2726 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
2727 else
2728 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
2729}
2730
2731void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
2732 llvm::Value *New) {
2733 DeferredReplacements.push_back(std::make_pair(Old, New));
2734}
Chris Lattnerd59d8672011-07-12 06:29:11 +00002735
Daniel Dunbard931a872009-02-02 22:03:45 +00002736RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00002737 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00002738 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002739 const CallArgList &CallArgs,
David Chisnall9eecafa2010-05-01 11:15:56 +00002740 const Decl *TargetDecl,
David Chisnallff5f88c2010-05-02 13:41:58 +00002741 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00002742 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00002743
2744 // Handle struct-return functions by passing a pointer to the
2745 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00002746 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002747 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002748
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002749 llvm::FunctionType *IRFuncTy =
2750 cast<llvm::FunctionType>(
2751 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00002752
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002753 // If we're using inalloca, insert the allocation after the stack save.
2754 // FIXME: Do this earlier rather than hacking it in here!
Craig Topper8a13c412014-05-21 05:09:00 +00002755 llvm::Value *ArgMemory = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002756 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
Reid Kleckner9df1d972014-04-10 01:40:15 +00002757 llvm::Instruction *IP = CallArgs.getStackBase();
2758 llvm::AllocaInst *AI;
2759 if (IP) {
2760 IP = IP->getNextNode();
2761 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
2762 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00002763 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00002764 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002765 AI->setUsedWithInAlloca(true);
2766 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
2767 ArgMemory = AI;
2768 }
2769
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002770 ClangToLLVMArgMapping IRFunctionArgs(CGM, CallInfo);
2771 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
2772
Chris Lattner4ca97c32009-06-13 00:26:38 +00002773 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00002774 // alloca to hold the result, unless one is given to us.
Craig Topper8a13c412014-05-21 05:09:00 +00002775 llvm::Value *SRetPtr = nullptr;
Reid Kleckner37abaca2014-05-09 22:46:15 +00002776 if (RetAI.isIndirect() || RetAI.isInAlloca()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002777 SRetPtr = ReturnValue.getValue();
2778 if (!SRetPtr)
2779 SRetPtr = CreateMemTemp(RetTy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002780 if (IRFunctionArgs.hasSRetArg()) {
2781 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002782 } else {
2783 llvm::Value *Addr =
2784 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
2785 Builder.CreateStore(SRetPtr, Addr);
2786 }
Anders Carlsson17490832009-12-24 20:40:36 +00002787 }
Mike Stump11289f42009-09-09 15:08:12 +00002788
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002789 assert(CallInfo.arg_size() == CallArgs.size() &&
2790 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002791 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002792 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002793 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002794 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002795 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00002796 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002797
John McCall47fb9502013-03-07 21:37:08 +00002798 CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002799
2800 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002801 if (IRFunctionArgs.hasPaddingArg(ArgNo))
2802 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
2803 llvm::UndefValue::get(ArgInfo.getPaddingType());
2804
2805 unsigned FirstIRArg, NumIRArgs;
2806 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002807
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002808 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002809 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002810 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002811 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2812 if (RV.isAggregate()) {
2813 // Replace the placeholder with the appropriate argument slot GEP.
2814 llvm::Instruction *Placeholder =
2815 cast<llvm::Instruction>(RV.getAggregateAddr());
2816 CGBuilderTy::InsertPoint IP = Builder.saveIP();
2817 Builder.SetInsertPoint(Placeholder);
2818 llvm::Value *Addr = Builder.CreateStructGEP(
2819 ArgMemory, ArgInfo.getInAllocaFieldIndex());
2820 Builder.restoreIP(IP);
2821 deferPlaceholderReplacement(Placeholder, Addr);
2822 } else {
2823 // Store the RValue into the argument struct.
2824 llvm::Value *Addr =
2825 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
David Majnemer32b57b02014-03-31 16:12:47 +00002826 unsigned AS = Addr->getType()->getPointerAddressSpace();
2827 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
2828 // There are some cases where a trivial bitcast is not avoidable. The
2829 // definition of a type later in a translation unit may change it's type
2830 // from {}* to (%struct.foo*)*.
2831 if (Addr->getType() != MemType)
2832 Addr = Builder.CreateBitCast(Addr, MemType);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002833 LValue argLV = MakeAddrLValue(Addr, I->Ty, TypeAlign);
2834 EmitInitStoreOfNonAggregate(*this, RV, argLV);
2835 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002836 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002837 }
2838
Daniel Dunbar03816342010-08-21 02:24:36 +00002839 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002840 assert(NumIRArgs == 1);
Daniel Dunbar747865a2009-02-05 09:16:39 +00002841 if (RV.isScalar() || RV.isComplex()) {
2842 // Make a temporary alloca to pass the argument.
Eli Friedman7e68c882011-06-15 18:26:32 +00002843 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2844 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
2845 AI->setAlignment(ArgInfo.getIndirectAlign());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002846 IRCallArgs[FirstIRArg] = AI;
John McCall47fb9502013-03-07 21:37:08 +00002847
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002848 LValue argLV = MakeAddrLValue(AI, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002849 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar747865a2009-02-05 09:16:39 +00002850 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002851 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00002852 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002853 // 1. If the argument is not byval, and we are required to copy the
2854 // source. (This case doesn't occur on any common architecture.)
2855 // 2. If the argument is byval, RV is not sufficiently aligned, and
2856 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00002857 // 3. If the argument is byval, but RV is located in an address space
2858 // different than that of the argument (0).
Eli Friedmanf7456192011-06-15 22:09:18 +00002859 llvm::Value *Addr = RV.getAggregateAddr();
2860 unsigned Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002861 const llvm::DataLayout *TD = &CGM.getDataLayout();
Guy Benyei3832bfd2013-03-10 12:59:00 +00002862 const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002863 const unsigned ArgAddrSpace =
2864 (FirstIRArg < IRFuncTy->getNumParams()
2865 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
2866 : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00002867 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall47fb9502013-03-07 21:37:08 +00002868 (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
Guy Benyei3832bfd2013-03-10 12:59:00 +00002869 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align) ||
2870 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002871 // Create an aligned temporary, and copy to it.
Eli Friedmanf7456192011-06-15 22:09:18 +00002872 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2873 if (Align > AI->getAlignment())
2874 AI->setAlignment(Align);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002875 IRCallArgs[FirstIRArg] = AI;
Chad Rosier615ed1a2012-03-29 17:37:10 +00002876 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002877 } else {
2878 // Skip the extra memcpy call.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002879 IRCallArgs[FirstIRArg] = Addr;
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002880 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002881 }
2882 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002883 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002884
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002885 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002886 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002887 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002888
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002889 case ABIArgInfo::Extend:
2890 case ABIArgInfo::Direct: {
2891 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002892 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
2893 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002894 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002895 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002896 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002897 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002898 else
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002899 V = Builder.CreateLoad(RV.getAggregateAddr());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002900
Chris Lattner3ce86682011-07-12 04:53:39 +00002901 // If the argument doesn't match, perform a bitcast to coerce it. This
2902 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002903 if (FirstIRArg < IRFuncTy->getNumParams() &&
2904 V->getType() != IRFuncTy->getParamType(FirstIRArg))
2905 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
2906 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002907 break;
2908 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002909
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002910 // FIXME: Avoid the conversion through memory if possible.
2911 llvm::Value *SrcPtr;
John McCall47fb9502013-03-07 21:37:08 +00002912 if (RV.isScalar() || RV.isComplex()) {
Eli Friedmanf4258eb2011-05-02 18:05:27 +00002913 SrcPtr = CreateMemTemp(I->Ty, "coerce");
John McCall47fb9502013-03-07 21:37:08 +00002914 LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002915 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Mike Stump11289f42009-09-09 15:08:12 +00002916 } else
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002917 SrcPtr = RV.getAggregateAddr();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002918
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002919 // If the value is offset in memory, apply the offset now.
2920 if (unsigned Offs = ArgInfo.getDirectOffset()) {
2921 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
2922 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002923 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002924 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
2925
2926 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002927
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002928 // Fast-isel and the optimizer generally like scalar values better than
2929 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00002930 llvm::StructType *STy =
2931 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002932 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
Chandler Carrutha6399a52012-10-10 11:29:08 +00002933 llvm::Type *SrcTy =
2934 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
2935 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
2936 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
2937
2938 // If the source type is smaller than the destination type of the
2939 // coerce-to logic, copy the source value into a temp alloca the size
2940 // of the destination type to allow loading all of it. The bits past
2941 // the source value are left undef.
2942 if (SrcSize < DstSize) {
2943 llvm::AllocaInst *TempAlloca
2944 = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
2945 Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
2946 SrcPtr = TempAlloca;
2947 } else {
2948 SrcPtr = Builder.CreateBitCast(SrcPtr,
2949 llvm::PointerType::getUnqual(STy));
2950 }
2951
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002952 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00002953 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2954 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerff941a62010-07-28 18:24:28 +00002955 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
2956 // We don't know what we're loading from.
2957 LI->setAlignment(1);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002958 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00002959 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00002960 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00002961 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002962 assert(NumIRArgs == 1);
2963 IRCallArgs[FirstIRArg] =
2964 CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00002965 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002966
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002967 break;
2968 }
2969
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002970 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002971 unsigned IRArgPos = FirstIRArg;
2972 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
2973 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002974 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00002975 }
2976 }
Mike Stump11289f42009-09-09 15:08:12 +00002977
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002978 if (ArgMemory) {
2979 llvm::Value *Arg = ArgMemory;
Reid Klecknerafba553e2014-07-08 02:24:27 +00002980 if (CallInfo.isVariadic()) {
2981 // When passing non-POD arguments by value to variadic functions, we will
2982 // end up with a variadic prototype and an inalloca call site. In such
2983 // cases, we can't do any parameter mismatch checks. Give up and bitcast
2984 // the callee.
2985 unsigned CalleeAS =
2986 cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
2987 Callee = Builder.CreateBitCast(
2988 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
2989 } else {
2990 llvm::Type *LastParamTy =
2991 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
2992 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002993#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00002994 // Assert that these structs have equivalent element types.
2995 llvm::StructType *FullTy = CallInfo.getArgStruct();
2996 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
2997 cast<llvm::PointerType>(LastParamTy)->getElementType());
2998 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
2999 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3000 DE = DeclaredTy->element_end(),
3001 FI = FullTy->element_begin();
3002 DI != DE; ++DI, ++FI)
3003 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003004#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00003005 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3006 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003007 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003008 assert(IRFunctionArgs.hasInallocaArg());
3009 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003010 }
3011
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003012 if (!CallArgs.getCleanupsToDeactivate().empty())
3013 deactivateArgCleanupsBeforeCall(*this, CallArgs);
3014
Chris Lattner4ca97c32009-06-13 00:26:38 +00003015 // If the callee is a bitcast of a function to a varargs pointer to function
3016 // type, check to see if we can remove the bitcast. This handles some cases
3017 // with unprototyped functions.
3018 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
3019 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003020 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
3021 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00003022 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00003023 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00003024
Chris Lattner4ca97c32009-06-13 00:26:38 +00003025 if (CE->getOpcode() == llvm::Instruction::BitCast &&
3026 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00003027 ActualFT->getNumParams() == CurFT->getNumParams() &&
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003028 ActualFT->getNumParams() == IRCallArgs.size() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00003029 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00003030 bool ArgsMatch = true;
3031 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
3032 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
3033 ArgsMatch = false;
3034 break;
3035 }
Mike Stump11289f42009-09-09 15:08:12 +00003036
Chris Lattner4ca97c32009-06-13 00:26:38 +00003037 // Strip the cast if we can get away with it. This is a nice cleanup,
3038 // but also allows us to inline the function at -O0 if it is marked
3039 // always_inline.
3040 if (ArgsMatch)
3041 Callee = CalleeF;
3042 }
3043 }
Mike Stump11289f42009-09-09 15:08:12 +00003044
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003045 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
3046 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
3047 // Inalloca argument can have different type.
3048 if (IRFunctionArgs.hasInallocaArg() &&
3049 i == IRFunctionArgs.getInallocaArgNo())
3050 continue;
3051 if (i < IRFuncTy->getNumParams())
3052 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
3053 }
3054
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003055 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00003056 CodeGen::AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003057 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
3058 CallingConv, true);
Bill Wendling3087d022012-12-07 23:17:26 +00003059 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003060 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00003061
Craig Topper8a13c412014-05-21 05:09:00 +00003062 llvm::BasicBlock *InvokeDest = nullptr;
Bill Wendling5e85be42012-12-30 10:32:17 +00003063 if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
3064 llvm::Attribute::NoUnwind))
John McCallbd309292010-07-06 01:34:17 +00003065 InvokeDest = getInvokeDest();
3066
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003067 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00003068 if (!InvokeDest) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003069 CS = Builder.CreateCall(Callee, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003070 } else {
3071 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003072 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003073 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003074 }
Chris Lattnere70a0072010-06-29 16:40:28 +00003075 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00003076 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003077
Peter Collingbourne41af7c22014-05-20 17:12:51 +00003078 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
3079 !CS.hasFnAttr(llvm::Attribute::NoInline))
3080 Attrs =
3081 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3082 llvm::Attribute::AlwaysInline);
3083
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003084 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003085 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003086
Dan Gohman515a60d2012-02-16 00:57:37 +00003087 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3088 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003089 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003090 AddObjCARCExceptionMetadata(CS.getInstruction());
3091
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003092 // If the call doesn't return, finish the basic block and clear the
3093 // insertion point; this allows the rest of IRgen to discard
3094 // unreachable code.
3095 if (CS.doesNotReturn()) {
3096 Builder.CreateUnreachable();
3097 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003098
Mike Stump18bb9282009-05-16 07:57:57 +00003099 // FIXME: For now, emit a dummy basic block because expr emitters in
3100 // generally are not ready to handle emitting expressions at unreachable
3101 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003102 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003103
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003104 // Return a reasonable RValue.
3105 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00003106 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003107
3108 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00003109 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00003110 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003111
John McCall31168b02011-06-15 23:02:42 +00003112 // Emit any writebacks immediately. Arguably this should happen
3113 // after any return-value munging.
3114 if (CallArgs.hasWritebacks())
3115 emitWritebacks(*this, CallArgs);
3116
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003117 // The stack cleanup for inalloca arguments has to run out of the normal
3118 // lexical order, so deactivate it and run it manually here.
3119 CallArgs.freeArgumentMemory(*this);
3120
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003121 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003122 case ABIArgInfo::InAlloca:
John McCall47fb9502013-03-07 21:37:08 +00003123 case ABIArgInfo::Indirect:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003124 return convertTempToRValue(SRetPtr, RetTy, SourceLocation());
Daniel Dunbard3674e62008-09-11 01:48:57 +00003125
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003126 case ABIArgInfo::Ignore:
Daniel Dunbar01362822009-02-03 06:30:17 +00003127 // If we are ignoring an argument that had a result, make sure to
3128 // construct the appropriate return value for our caller.
Daniel Dunbarc79407f2009-02-05 07:09:07 +00003129 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003130
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003131 case ABIArgInfo::Extend:
3132 case ABIArgInfo::Direct: {
Chris Lattner3517f142011-07-13 03:59:32 +00003133 llvm::Type *RetIRTy = ConvertType(RetTy);
3134 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
John McCall47fb9502013-03-07 21:37:08 +00003135 switch (getEvaluationKind(RetTy)) {
3136 case TEK_Complex: {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003137 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
3138 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
3139 return RValue::getComplex(std::make_pair(Real, Imag));
3140 }
John McCall47fb9502013-03-07 21:37:08 +00003141 case TEK_Aggregate: {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003142 llvm::Value *DestPtr = ReturnValue.getValue();
3143 bool DestIsVolatile = ReturnValue.isVolatile();
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003144
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003145 if (!DestPtr) {
3146 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
3147 DestIsVolatile = false;
3148 }
Eli Friedmanaf9b3252011-05-17 21:08:01 +00003149 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003150 return RValue::getAggregate(DestPtr);
3151 }
John McCall47fb9502013-03-07 21:37:08 +00003152 case TEK_Scalar: {
3153 // If the argument doesn't match, perform a bitcast to coerce it. This
3154 // can happen due to trivial type mismatches.
3155 llvm::Value *V = CI;
3156 if (V->getType() != RetIRTy)
3157 V = Builder.CreateBitCast(V, RetIRTy);
3158 return RValue::get(V);
3159 }
3160 }
3161 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003162 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003163
Anders Carlsson17490832009-12-24 20:40:36 +00003164 llvm::Value *DestPtr = ReturnValue.getValue();
3165 bool DestIsVolatile = ReturnValue.isVolatile();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003166
Anders Carlsson17490832009-12-24 20:40:36 +00003167 if (!DestPtr) {
Daniel Dunbara7566f12010-02-09 02:48:28 +00003168 DestPtr = CreateMemTemp(RetTy, "coerce");
Anders Carlsson17490832009-12-24 20:40:36 +00003169 DestIsVolatile = false;
3170 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003171
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003172 // If the value is offset in memory, apply the offset now.
3173 llvm::Value *StorePtr = DestPtr;
3174 if (unsigned Offs = RetAI.getDirectOffset()) {
3175 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
3176 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003177 StorePtr = Builder.CreateBitCast(StorePtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003178 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
3179 }
3180 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003181
Nick Lewycky2d84e842013-10-02 02:29:49 +00003182 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Daniel Dunbar573884e2008-09-10 07:04:09 +00003183 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00003184
Daniel Dunbard3674e62008-09-11 01:48:57 +00003185 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00003186 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar613855c2008-09-09 23:27:19 +00003187 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003188
David Blaikie83d382b2011-09-23 05:06:16 +00003189 llvm_unreachable("Unhandled ABIArgInfo::Kind");
Daniel Dunbar613855c2008-09-09 23:27:19 +00003190}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00003191
3192/* VarArg handling */
3193
3194llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
3195 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
3196}