blob: f0eeba06f9cbb5845d9b650416e3f162a3911dbf [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
Reid Klecknerc3473512014-08-29 21:43:29 +0000335/// Arrange a thunk that takes 'this' as the first parameter followed by
336/// varargs. Return a void pointer, regardless of the actual return type.
337/// The body of the thunk will end in a musttail call to a function of the
338/// correct type, and the caller will bitcast the function to the correct
339/// prototype.
340const CGFunctionInfo &
341CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) {
342 assert(MD->isVirtual() && "only virtual memptrs have thunks");
343 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
344 CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
345 return arrangeLLVMFunctionInfo(Context.VoidTy, false, ArgTys,
346 FTP->getExtInfo(), RequiredArgs(1));
347}
348
John McCallc818bbb2012-12-07 07:03:17 +0000349/// Arrange a call as unto a free function, except possibly with an
350/// additional number of formal parameters considered required.
351static const CGFunctionInfo &
352arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000353 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000354 const CallArgList &args,
355 const FunctionType *fnType,
356 unsigned numExtraRequiredArgs) {
357 assert(args.size() >= numExtraRequiredArgs);
358
359 // In most cases, there are no optional arguments.
360 RequiredArgs required = RequiredArgs::All;
361
362 // If we have a variadic prototype, the required arguments are the
363 // extra prefix plus the arguments in the prototype.
364 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
365 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000366 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000367
368 // If we don't have a prototype at all, but we're supposed to
369 // explicitly use the variadic convention for unprototyped calls,
370 // treat all of the arguments as required but preserve the nominal
371 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000372 } else if (CGM.getTargetCodeGenInfo()
373 .isNoProtoCallVariadic(args,
374 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000375 required = RequiredArgs(args.size());
376 }
377
Alp Toker314cc812014-01-25 16:55:45 +0000378 return CGT.arrangeFreeFunctionCall(fnType->getReturnType(), args,
John McCallc818bbb2012-12-07 07:03:17 +0000379 fnType->getExtInfo(), required);
380}
381
John McCalla729c622012-02-17 03:33:10 +0000382/// Figure out the rules for calling a function with the given formal
383/// type using the given arguments. The arguments are necessary
384/// because the function might be unprototyped, in which case it's
385/// target-dependent in crazy ways.
386const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000387CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
388 const FunctionType *fnType) {
Mark Lacey23455752013-10-10 20:57:00 +0000389 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 0);
John McCallc818bbb2012-12-07 07:03:17 +0000390}
John McCalla729c622012-02-17 03:33:10 +0000391
John McCallc818bbb2012-12-07 07:03:17 +0000392/// A block function call is essentially a free-function call with an
393/// extra implicit argument.
394const CGFunctionInfo &
395CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
396 const FunctionType *fnType) {
Mark Lacey23455752013-10-10 20:57:00 +0000397 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1);
John McCalla729c622012-02-17 03:33:10 +0000398}
399
400const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000401CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
402 const CallArgList &args,
403 FunctionType::ExtInfo info,
404 RequiredArgs required) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000405 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000406 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000407 for (const auto &Arg : args)
408 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner4982b822014-01-31 22:54:50 +0000409 return arrangeLLVMFunctionInfo(GetReturnType(resultType), false, argTypes,
410 info, required);
John McCall8dda7b22012-07-07 06:41:13 +0000411}
412
413/// Arrange a call to a C++ method, passing the given arguments.
414const CGFunctionInfo &
415CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
416 const FunctionProtoType *FPT,
417 RequiredArgs required) {
418 // FIXME: Kill copy.
419 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000420 for (const auto &Arg : args)
421 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
John McCall8dda7b22012-07-07 06:41:13 +0000422
423 FunctionType::ExtInfo info = FPT->getExtInfo();
Reid Kleckner4982b822014-01-31 22:54:50 +0000424 return arrangeLLVMFunctionInfo(GetReturnType(FPT->getReturnType()), true,
425 argTypes, info, required);
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000426}
427
Reid Kleckner4982b822014-01-31 22:54:50 +0000428const CGFunctionInfo &CodeGenTypes::arrangeFreeFunctionDeclaration(
429 QualType resultType, const FunctionArgList &args,
430 const FunctionType::ExtInfo &info, bool isVariadic) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000431 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000432 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000433 for (auto Arg : args)
434 argTypes.push_back(Context.getCanonicalParamType(Arg->getType()));
John McCalla729c622012-02-17 03:33:10 +0000435
436 RequiredArgs required =
437 (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
Reid Kleckner4982b822014-01-31 22:54:50 +0000438 return arrangeLLVMFunctionInfo(GetReturnType(resultType), false, argTypes, info,
John McCall8dda7b22012-07-07 06:41:13 +0000439 required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000440}
441
John McCalla729c622012-02-17 03:33:10 +0000442const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Reid Kleckner4982b822014-01-31 22:54:50 +0000443 return arrangeLLVMFunctionInfo(getContext().VoidTy, false, None,
John McCall8dda7b22012-07-07 06:41:13 +0000444 FunctionType::ExtInfo(), RequiredArgs::All);
John McCalla738c252011-03-09 04:27:21 +0000445}
446
John McCalla729c622012-02-17 03:33:10 +0000447/// Arrange the argument and result information for an abstract value
448/// of a given function type. This is the method which all of the
449/// above functions ultimately defer to.
450const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000451CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Reid Kleckner4982b822014-01-31 22:54:50 +0000452 bool IsInstanceMethod,
John McCall8dda7b22012-07-07 06:41:13 +0000453 ArrayRef<CanQualType> argTypes,
454 FunctionType::ExtInfo info,
455 RequiredArgs required) {
John McCall2da83a32010-02-26 00:48:12 +0000456#ifndef NDEBUG
John McCalla729c622012-02-17 03:33:10 +0000457 for (ArrayRef<CanQualType>::const_iterator
458 I = argTypes.begin(), E = argTypes.end(); I != E; ++I)
John McCall2da83a32010-02-26 00:48:12 +0000459 assert(I->isCanonicalAsParam());
460#endif
461
John McCalla729c622012-02-17 03:33:10 +0000462 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
John McCallab26cfa2010-02-05 21:31:56 +0000463
Daniel Dunbare0be8292009-02-03 00:07:12 +0000464 // Lookup or create unique function info.
465 llvm::FoldingSetNodeID ID;
Reid Kleckner4982b822014-01-31 22:54:50 +0000466 CGFunctionInfo::Profile(ID, IsInstanceMethod, info, required, resultType,
467 argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000468
Craig Topper8a13c412014-05-21 05:09:00 +0000469 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000470 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000471 if (FI)
472 return *FI;
473
John McCalla729c622012-02-17 03:33:10 +0000474 // Construct the function info. We co-allocate the ArgInfos.
Reid Kleckner4982b822014-01-31 22:54:50 +0000475 FI = CGFunctionInfo::create(CC, IsInstanceMethod, info, resultType, argTypes,
476 required);
John McCalla729c622012-02-17 03:33:10 +0000477 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000478
John McCalla729c622012-02-17 03:33:10 +0000479 bool inserted = FunctionsBeingProcessed.insert(FI); (void)inserted;
480 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000481
Daniel Dunbar313321e2009-02-03 05:31:23 +0000482 // Compute ABI information.
Chris Lattner22326a12010-07-29 02:31:05 +0000483 getABIInfo().computeInfo(*FI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000484
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000485 // Loop over all of the computed argument and return value info. If any of
486 // them are direct or extend without a specified coerce type, specify the
487 // default now.
John McCalla729c622012-02-17 03:33:10 +0000488 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000489 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000490 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000491
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000492 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000493 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000494 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000495
John McCalla729c622012-02-17 03:33:10 +0000496 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
497 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000498
Daniel Dunbare0be8292009-02-03 00:07:12 +0000499 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000500}
501
John McCalla729c622012-02-17 03:33:10 +0000502CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Reid Kleckner4982b822014-01-31 22:54:50 +0000503 bool IsInstanceMethod,
John McCalla729c622012-02-17 03:33:10 +0000504 const FunctionType::ExtInfo &info,
505 CanQualType resultType,
506 ArrayRef<CanQualType> argTypes,
507 RequiredArgs required) {
508 void *buffer = operator new(sizeof(CGFunctionInfo) +
509 sizeof(ArgInfo) * (argTypes.size() + 1));
510 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
511 FI->CallingConvention = llvmCC;
512 FI->EffectiveCallingConvention = llvmCC;
513 FI->ASTCallingConvention = info.getCC();
Reid Kleckner4982b822014-01-31 22:54:50 +0000514 FI->InstanceMethod = IsInstanceMethod;
John McCalla729c622012-02-17 03:33:10 +0000515 FI->NoReturn = info.getNoReturn();
516 FI->ReturnsRetained = info.getProducesResult();
517 FI->Required = required;
518 FI->HasRegParm = info.getHasRegParm();
519 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000520 FI->ArgStruct = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000521 FI->NumArgs = argTypes.size();
522 FI->getArgsBuffer()[0].type = resultType;
523 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
524 FI->getArgsBuffer()[i + 1].type = argTypes[i];
525 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000526}
527
528/***/
529
John McCall85dd2c52011-05-15 02:19:42 +0000530void CodeGenTypes::GetExpandedTypes(QualType type,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000531 SmallVectorImpl<llvm::Type*> &expandedTypes) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000532 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(type)) {
533 uint64_t NumElts = AT->getSize().getZExtValue();
534 for (uint64_t Elt = 0; Elt < NumElts; ++Elt)
535 GetExpandedTypes(AT->getElementType(), expandedTypes);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000536 } else if (const RecordType *RT = type->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000537 const RecordDecl *RD = RT->getDecl();
538 assert(!RD->hasFlexibleArrayMember() &&
539 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000540 if (RD->isUnion()) {
541 // Unions can be here only in degenerative cases - all the fields are same
542 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000543 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000544 CharUnits UnionSize = CharUnits::Zero();
545
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000546 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000547 assert(!FD->isBitField() &&
548 "Cannot expand structure with bit-field members.");
549 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
550 if (UnionSize < FieldSize) {
551 UnionSize = FieldSize;
552 LargestFD = FD;
553 }
554 }
555 if (LargestFD)
556 GetExpandedTypes(LargestFD->getType(), expandedTypes);
557 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000558 for (const auto *I : RD->fields()) {
559 assert(!I->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000560 "Cannot expand structure with bit-field members.");
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000561 GetExpandedTypes(I->getType(), expandedTypes);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000562 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000563 }
564 } else if (const ComplexType *CT = type->getAs<ComplexType>()) {
565 llvm::Type *EltTy = ConvertType(CT->getElementType());
566 expandedTypes.push_back(EltTy);
567 expandedTypes.push_back(EltTy);
568 } else
569 expandedTypes.push_back(ConvertType(type));
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000570}
571
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000572void CodeGenFunction::ExpandTypeFromArgs(
573 QualType Ty, LValue LV, SmallVectorImpl<llvm::Argument *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000574 assert(LV.isSimple() &&
575 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000576
Bob Wilsone826a2a2011-08-03 05:58:22 +0000577 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
578 unsigned NumElts = AT->getSize().getZExtValue();
579 QualType EltTy = AT->getElementType();
580 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
Eli Friedman7f1ff602012-04-16 03:54:45 +0000581 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, Elt);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000582 LValue LV = MakeAddrLValue(EltAddr, EltTy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000583 ExpandTypeFromArgs(EltTy, LV, AI);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000584 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000585 return;
586 }
587 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000588 RecordDecl *RD = RT->getDecl();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000589 if (RD->isUnion()) {
590 // Unions can be here only in degenerative cases - all the fields are same
591 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000592 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000593 CharUnits UnionSize = CharUnits::Zero();
Bob Wilsone826a2a2011-08-03 05:58:22 +0000594
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000595 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000596 assert(!FD->isBitField() &&
597 "Cannot expand structure with bit-field members.");
598 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
599 if (UnionSize < FieldSize) {
600 UnionSize = FieldSize;
601 LargestFD = FD;
602 }
603 }
604 if (LargestFD) {
605 // FIXME: What are the right qualifiers here?
Eli Friedman7f1ff602012-04-16 03:54:45 +0000606 LValue SubLV = EmitLValueForField(LV, LargestFD);
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000607 ExpandTypeFromArgs(LargestFD->getType(), SubLV, AI);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000608 }
609 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000610 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000611 QualType FT = FD->getType();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000612 // FIXME: What are the right qualifiers here?
Eli Friedman7f1ff602012-04-16 03:54:45 +0000613 LValue SubLV = EmitLValueForField(LV, FD);
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000614 ExpandTypeFromArgs(FT, SubLV, AI);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000615 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000616 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000617 return;
618 }
619 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000620 QualType EltTy = CT->getElementType();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000621 llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real");
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000622 EmitStoreThroughLValue(RValue::get(*AI++), MakeAddrLValue(RealAddr, EltTy));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000623 llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag");
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000624 EmitStoreThroughLValue(RValue::get(*AI++), MakeAddrLValue(ImagAddr, EltTy));
625 return;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000626 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000627 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000628}
629
Chris Lattner895c52b2010-06-27 06:04:18 +0000630/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +0000631/// accessing some number of bytes out of it, try to gep into the struct to get
632/// at its inner goodness. Dive as deep as possible without entering an element
633/// with an in-memory size smaller than DstSize.
634static llvm::Value *
Chris Lattner895c52b2010-06-27 06:04:18 +0000635EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000636 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +0000637 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +0000638 // We can't dive into a zero-element struct.
639 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000640
Chris Lattner2192fe52011-07-18 04:24:23 +0000641 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000642
Chris Lattner1cd66982010-06-27 05:56:15 +0000643 // If the first elt is at least as large as what we're looking for, or if the
James Molloy90d61012014-08-29 10:17:52 +0000644 // first element is the same size as the whole struct, we can enter it. The
645 // comparison must be made on the store size and not the alloca size. Using
646 // the alloca size may overstate the size of the load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000647 uint64_t FirstEltSize =
James Molloy90d61012014-08-29 10:17:52 +0000648 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000649 if (FirstEltSize < DstSize &&
James Molloy90d61012014-08-29 10:17:52 +0000650 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +0000651 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000652
Chris Lattner1cd66982010-06-27 05:56:15 +0000653 // GEP into the first element.
654 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000655
Chris Lattner1cd66982010-06-27 05:56:15 +0000656 // If the first element is a struct, recurse.
Chris Lattner2192fe52011-07-18 04:24:23 +0000657 llvm::Type *SrcTy =
Chris Lattner1cd66982010-06-27 05:56:15 +0000658 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000659 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +0000660 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000661
662 return SrcPtr;
663}
664
Chris Lattner055097f2010-06-27 06:26:04 +0000665/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
666/// are either integers or pointers. This does a truncation of the value if it
667/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000668///
669/// This behaves as if the value were coerced through memory, so on big-endian
670/// targets the high bits are preserved in a truncation, while little-endian
671/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +0000672static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +0000673 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +0000674 CodeGenFunction &CGF) {
675 if (Val->getType() == Ty)
676 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000677
Chris Lattner055097f2010-06-27 06:26:04 +0000678 if (isa<llvm::PointerType>(Val->getType())) {
679 // If this is Pointer->Pointer avoid conversion to and from int.
680 if (isa<llvm::PointerType>(Ty))
681 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000682
Chris Lattner055097f2010-06-27 06:26:04 +0000683 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +0000684 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +0000685 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000686
Chris Lattner2192fe52011-07-18 04:24:23 +0000687 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +0000688 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +0000689 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000690
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000691 if (Val->getType() != DestIntTy) {
692 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
693 if (DL.isBigEndian()) {
694 // Preserve the high bits on big-endian targets.
695 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +0000696 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
697 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
698
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000699 if (SrcSize > DstSize) {
700 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
701 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
702 } else {
703 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
704 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
705 }
706 } else {
707 // Little-endian targets preserve the low bits. No shifts required.
708 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
709 }
710 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000711
Chris Lattner055097f2010-06-27 06:26:04 +0000712 if (isa<llvm::PointerType>(Ty))
713 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
714 return Val;
715}
716
Chris Lattner1cd66982010-06-27 05:56:15 +0000717
718
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000719/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
720/// a pointer to an object of type \arg Ty.
721///
722/// This safely handles the case when the src type is smaller than the
723/// destination type; in this situation the values of bits which not
724/// present in the src are undefined.
725static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000726 llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000727 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000728 llvm::Type *SrcTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000729 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000730
Chris Lattnerd200eda2010-06-28 22:51:39 +0000731 // If SrcTy and Ty are the same, just do a load.
732 if (SrcTy == Ty)
733 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000734
Micah Villmowdd31ca12012-10-08 16:25:52 +0000735 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000736
Chris Lattner2192fe52011-07-18 04:24:23 +0000737 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000738 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000739 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
740 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000741
Micah Villmowdd31ca12012-10-08 16:25:52 +0000742 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000743
Chris Lattner055097f2010-06-27 06:26:04 +0000744 // If the source and destination are integer or pointer types, just do an
745 // extension or truncation to the desired type.
746 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
747 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
748 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
749 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
750 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000751
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000752 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000753 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +0000754 // Generally SrcSize is never greater than DstSize, since this means we are
755 // losing bits. However, this can happen in cases where the structure has
756 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000757 //
Mike Stump18bb9282009-05-16 07:57:57 +0000758 // FIXME: Assert that we aren't truncating non-padding bits when have access
759 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000760 llvm::Value *Casted =
761 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000762 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
763 // FIXME: Use better alignment / avoid requiring aligned load.
764 Load->setAlignment(1);
765 return Load;
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000766 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000767
Chris Lattner3fcc7902010-06-27 01:06:27 +0000768 // Otherwise do coercion through memory. This is stupid, but
769 // simple.
770 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
Manman Ren84b921f2012-11-28 22:08:52 +0000771 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
772 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
773 llvm::Value *SrcCasted = CGF.Builder.CreateBitCast(SrcPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000774 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000775 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
776 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
777 1, false);
Chris Lattner3fcc7902010-06-27 01:06:27 +0000778 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000779}
780
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000781// Function to store a first-class aggregate into memory. We prefer to
782// store the elements rather than the aggregate to be more friendly to
783// fast-isel.
784// FIXME: Do we need to recurse here?
785static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
786 llvm::Value *DestPtr, bool DestIsVolatile,
787 bool LowAlignment) {
788 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +0000789 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000790 dyn_cast<llvm::StructType>(Val->getType())) {
791 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
792 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
793 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
794 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
795 DestIsVolatile);
796 if (LowAlignment)
797 SI->setAlignment(1);
798 }
799 } else {
Bill Wendlingf6af30f2012-03-16 21:45:12 +0000800 llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
801 if (LowAlignment)
802 SI->setAlignment(1);
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000803 }
804}
805
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000806/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
807/// where the source and destination may have different types.
808///
809/// This safely handles the case when the src type is larger than the
810/// destination type; the upper bits of the src will be lost.
811static void CreateCoercedStore(llvm::Value *Src,
812 llvm::Value *DstPtr,
Anders Carlsson17490832009-12-24 20:40:36 +0000813 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000814 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000815 llvm::Type *SrcTy = Src->getType();
816 llvm::Type *DstTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000817 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +0000818 if (SrcTy == DstTy) {
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 SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000824
Chris Lattner2192fe52011-07-18 04:24:23 +0000825 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000826 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
827 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
828 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000829
Chris Lattner055097f2010-06-27 06:26:04 +0000830 // If the source and destination are integer or pointer types, just do an
831 // extension or truncation to the desired type.
832 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
833 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
834 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
835 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
836 return;
837 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000838
Micah Villmowdd31ca12012-10-08 16:25:52 +0000839 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000840
Daniel Dunbar313321e2009-02-03 05:31:23 +0000841 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000842 if (SrcSize <= DstSize) {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000843 llvm::Value *Casted =
844 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000845 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000846 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000847 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000848 // Otherwise do coercion through memory. This is stupid, but
849 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000850
851 // Generally SrcSize is never greater than DstSize, since this means we are
852 // losing bits. However, this can happen in cases where the structure has
853 // additional padding, for example due to a user specified alignment.
854 //
855 // FIXME: Assert that we aren't truncating non-padding bits when have access
856 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000857 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
858 CGF.Builder.CreateStore(Src, Tmp);
Manman Ren84b921f2012-11-28 22:08:52 +0000859 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
860 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
861 llvm::Value *DstCasted = CGF.Builder.CreateBitCast(DstPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000862 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000863 CGF.Builder.CreateMemCpy(DstCasted, Casted,
864 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
865 1, false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000866 }
867}
868
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000869/***/
870
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000871bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000872 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +0000873}
874
Tim Northovere77cc392014-03-29 13:28:05 +0000875bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
876 return ReturnTypeUsesSRet(FI) &&
877 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
878}
879
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000880bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
881 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
882 switch (BT->getKind()) {
883 default:
884 return false;
885 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +0000886 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000887 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +0000888 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000889 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +0000890 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000891 }
892 }
893
894 return false;
895}
896
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000897bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
898 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
899 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
900 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +0000901 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000902 }
903 }
904
905 return false;
906}
907
Chris Lattnera5f58b02011-07-09 17:41:47 +0000908llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +0000909 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
910 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +0000911}
912
Chris Lattnera5f58b02011-07-09 17:41:47 +0000913llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +0000914CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000915
916 bool Inserted = FunctionsBeingProcessed.insert(&FI); (void)Inserted;
917 assert(Inserted && "Recursively being processed?");
918
Reid Kleckner37abaca2014-05-09 22:46:15 +0000919 bool SwapThisWithSRet = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000920 SmallVector<llvm::Type*, 8> argTypes;
Craig Topper8a13c412014-05-21 05:09:00 +0000921 llvm::Type *resultType = nullptr;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000922
John McCall85dd2c52011-05-15 02:19:42 +0000923 const ABIArgInfo &retAI = FI.getReturnInfo();
924 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +0000925 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +0000926 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +0000927
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000928 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +0000929 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +0000930 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +0000931 break;
932
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000933 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +0000934 if (retAI.getInAllocaSRet()) {
935 // sret things on win32 aren't void, they return the sret pointer.
936 QualType ret = FI.getReturnType();
937 llvm::Type *ty = ConvertType(ret);
938 unsigned addressSpace = Context.getTargetAddressSpace(ret);
939 resultType = llvm::PointerType::get(ty, addressSpace);
940 } else {
941 resultType = llvm::Type::getVoidTy(getLLVMContext());
942 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000943 break;
944
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000945 case ABIArgInfo::Indirect: {
John McCall85dd2c52011-05-15 02:19:42 +0000946 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
947 resultType = llvm::Type::getVoidTy(getLLVMContext());
948
949 QualType ret = FI.getReturnType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000950 llvm::Type *ty = ConvertType(ret);
John McCall85dd2c52011-05-15 02:19:42 +0000951 unsigned addressSpace = Context.getTargetAddressSpace(ret);
952 argTypes.push_back(llvm::PointerType::get(ty, addressSpace));
Reid Kleckner37abaca2014-05-09 22:46:15 +0000953
954 SwapThisWithSRet = retAI.isSRetAfterThis();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000955 break;
956 }
957
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000958 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +0000959 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000960 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000961 }
Mike Stump11289f42009-09-09 15:08:12 +0000962
John McCallc818bbb2012-12-07 07:03:17 +0000963 // Add in all of the required arguments.
964 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), ie;
965 if (FI.isVariadic()) {
966 ie = it + FI.getRequiredArgs().getNumRequiredArgs();
967 } else {
968 ie = FI.arg_end();
969 }
970 for (; it != ie; ++it) {
John McCall85dd2c52011-05-15 02:19:42 +0000971 const ABIArgInfo &argAI = it->info;
Mike Stump11289f42009-09-09 15:08:12 +0000972
Rafael Espindolafad28de2012-10-24 01:59:00 +0000973 // Insert a padding type to ensure proper alignment.
974 if (llvm::Type *PaddingType = argAI.getPaddingType())
975 argTypes.push_back(PaddingType);
976
John McCall85dd2c52011-05-15 02:19:42 +0000977 switch (argAI.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000978 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000979 case ABIArgInfo::InAlloca:
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000980 break;
981
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000982 case ABIArgInfo::Indirect: {
983 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +0000984 llvm::Type *LTy = ConvertTypeForMem(it->type);
John McCall85dd2c52011-05-15 02:19:42 +0000985 argTypes.push_back(LTy->getPointerTo());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000986 break;
987 }
988
989 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +0000990 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +0000991 // Fast-isel and the optimizer generally like scalar values better than
992 // FCAs, so we flatten them if this is safe to do for this argument.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000993 llvm::Type *argType = argAI.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +0000994 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +0000995 if (st && argAI.isDirect() && argAI.getCanBeFlattened()) {
John McCall85dd2c52011-05-15 02:19:42 +0000996 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
997 argTypes.push_back(st->getElementType(i));
Chris Lattner3dd716c2010-06-28 23:44:11 +0000998 } else {
John McCall85dd2c52011-05-15 02:19:42 +0000999 argTypes.push_back(argType);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001000 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001001 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001002 }
Mike Stump11289f42009-09-09 15:08:12 +00001003
Daniel Dunbard3674e62008-09-11 01:48:57 +00001004 case ABIArgInfo::Expand:
Chris Lattnera5f58b02011-07-09 17:41:47 +00001005 GetExpandedTypes(it->type, argTypes);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001006 break;
1007 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001008 }
1009
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001010 // Add the inalloca struct as the last parameter type.
1011 if (llvm::StructType *ArgStruct = FI.getArgStruct())
1012 argTypes.push_back(ArgStruct->getPointerTo());
1013
Reid Kleckner37abaca2014-05-09 22:46:15 +00001014 if (SwapThisWithSRet)
1015 std::swap(argTypes[0], argTypes[1]);
1016
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001017 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1018 assert(Erased && "Not in set?");
1019
John McCalla729c622012-02-17 03:33:10 +00001020 return llvm::FunctionType::get(resultType, argTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001021}
1022
Chris Lattner2192fe52011-07-18 04:24:23 +00001023llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001024 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001025 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001026
Chris Lattner8806e322011-07-10 00:18:59 +00001027 if (!isFuncTypeConvertible(FPT))
1028 return llvm::StructType::get(getLLVMContext());
1029
1030 const CGFunctionInfo *Info;
1031 if (isa<CXXDestructorDecl>(MD))
John McCalla729c622012-02-17 03:33:10 +00001032 Info = &arrangeCXXDestructor(cast<CXXDestructorDecl>(MD), GD.getDtorType());
Chris Lattner8806e322011-07-10 00:18:59 +00001033 else
John McCalla729c622012-02-17 03:33:10 +00001034 Info = &arrangeCXXMethodDeclaration(MD);
1035 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001036}
1037
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001038namespace {
1039
1040/// Encapsulates information about the way function arguments from
1041/// CGFunctionInfo should be passed to actual LLVM IR function.
1042class ClangToLLVMArgMapping {
1043 static const unsigned InvalidIndex = ~0U;
1044 unsigned InallocaArgNo;
1045 unsigned SRetArgNo;
1046 unsigned TotalIRArgs;
1047
1048 /// Arguments of LLVM IR function corresponding to single Clang argument.
1049 struct IRArgs {
1050 unsigned PaddingArgIndex;
1051 // Argument is expanded to IR arguments at positions
1052 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1053 unsigned FirstArgIndex;
1054 unsigned NumberOfArgs;
1055
1056 IRArgs()
1057 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1058 NumberOfArgs(0) {}
1059 };
1060
1061 SmallVector<IRArgs, 8> ArgInfo;
1062
1063public:
1064 ClangToLLVMArgMapping(CodeGenModule &CGM, const CGFunctionInfo &FI)
1065 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1066 ArgInfo(FI.arg_size()) {
1067 construct(CGM, FI);
1068 }
1069
1070 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1071 unsigned getInallocaArgNo() const {
1072 assert(hasInallocaArg());
1073 return InallocaArgNo;
1074 }
1075
1076 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1077 unsigned getSRetArgNo() const {
1078 assert(hasSRetArg());
1079 return SRetArgNo;
1080 }
1081
1082 unsigned totalIRArgs() const { return TotalIRArgs; }
1083
1084 bool hasPaddingArg(unsigned ArgNo) const {
1085 assert(ArgNo < ArgInfo.size());
1086 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1087 }
1088 unsigned getPaddingArgNo(unsigned ArgNo) const {
1089 assert(hasPaddingArg(ArgNo));
1090 return ArgInfo[ArgNo].PaddingArgIndex;
1091 }
1092
1093 /// Returns index of first IR argument corresponding to ArgNo, and their
1094 /// quantity.
1095 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1096 assert(ArgNo < ArgInfo.size());
1097 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1098 ArgInfo[ArgNo].NumberOfArgs);
1099 }
1100
1101private:
1102 void construct(CodeGenModule &CGM, const CGFunctionInfo &FI);
1103};
1104
1105void ClangToLLVMArgMapping::construct(CodeGenModule &CGM,
1106 const CGFunctionInfo &FI) {
1107 unsigned IRArgNo = 0;
1108 bool SwapThisWithSRet = false;
1109 const ABIArgInfo &RetAI = FI.getReturnInfo();
1110
1111 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1112 SwapThisWithSRet = RetAI.isSRetAfterThis();
1113 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1114 }
1115
1116 unsigned ArgNo = 0;
1117 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1118 E = FI.arg_end();
1119 I != E; ++I, ++ArgNo) {
1120 QualType ArgType = I->type;
1121 const ABIArgInfo &AI = I->info;
1122 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1123 auto &IRArgs = ArgInfo[ArgNo];
1124
1125 if (AI.getPaddingType())
1126 IRArgs.PaddingArgIndex = IRArgNo++;
1127
1128 switch (AI.getKind()) {
1129 case ABIArgInfo::Extend:
1130 case ABIArgInfo::Direct: {
1131 // FIXME: handle sseregparm someday...
1132 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001133 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001134 IRArgs.NumberOfArgs = STy->getNumElements();
1135 } else {
1136 IRArgs.NumberOfArgs = 1;
1137 }
1138 break;
1139 }
1140 case ABIArgInfo::Indirect:
1141 IRArgs.NumberOfArgs = 1;
1142 break;
1143 case ABIArgInfo::Ignore:
1144 case ABIArgInfo::InAlloca:
1145 // ignore and inalloca doesn't have matching LLVM parameters.
1146 IRArgs.NumberOfArgs = 0;
1147 break;
1148 case ABIArgInfo::Expand: {
1149 SmallVector<llvm::Type*, 8> Types;
1150 // FIXME: This is rather inefficient. Do we ever actually need to do
1151 // anything here? The result should be just reconstructed on the other
1152 // side, so extension should be a non-issue.
1153 CGM.getTypes().GetExpandedTypes(ArgType, Types);
1154 IRArgs.NumberOfArgs = Types.size();
1155 break;
1156 }
1157 }
1158
1159 if (IRArgs.NumberOfArgs > 0) {
1160 IRArgs.FirstArgIndex = IRArgNo;
1161 IRArgNo += IRArgs.NumberOfArgs;
1162 }
1163
1164 // Skip over the sret parameter when it comes second. We already handled it
1165 // above.
1166 if (IRArgNo == 1 && SwapThisWithSRet)
1167 IRArgNo++;
1168 }
1169 assert(ArgNo == FI.arg_size());
1170
1171 if (FI.usesInAlloca())
1172 InallocaArgNo = IRArgNo++;
1173
1174 TotalIRArgs = IRArgNo;
1175}
1176} // namespace
1177
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001178void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbard931a872009-02-02 22:03:45 +00001179 const Decl *TargetDecl,
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001180 AttributeListType &PAL,
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00001181 unsigned &CallingConv,
1182 bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001183 llvm::AttrBuilder FuncAttrs;
1184 llvm::AttrBuilder RetAttrs;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001185
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001186 CallingConv = FI.getEffectiveCallingConvention();
1187
John McCallab26cfa2010-02-05 21:31:56 +00001188 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001189 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001190
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001191 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001192 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001193 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001194 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001195 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001196 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001197 if (TargetDecl->hasAttr<NoReturnAttr>())
1198 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001199 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1200 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smithdebc59d2013-01-30 05:45:05 +00001201
1202 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
John McCallbe349de2010-07-08 06:48:12 +00001203 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl31ad7542011-03-13 17:09:40 +00001204 if (FPT && FPT->isNothrow(getContext()))
Bill Wendling207f0532012-12-20 19:27:06 +00001205 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith49af6292013-03-05 08:30:04 +00001206 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1207 // These attributes are not inherited by overloads.
1208 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1209 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001210 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001211 }
1212
Eric Christopherbf005ec2011-08-15 22:38:22 +00001213 // 'const' and 'pure' attribute functions are also nounwind.
1214 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001215 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1216 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001217 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001218 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1219 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001220 }
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001221 if (TargetDecl->hasAttr<MallocAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001222 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001223 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1224 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001225 }
1226
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001227 if (CodeGenOpts.OptimizeSize)
Bill Wendling207f0532012-12-20 19:27:06 +00001228 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
Quentin Colombet5ee5ca12012-10-26 00:29:48 +00001229 if (CodeGenOpts.OptimizeSize == 2)
Bill Wendling207f0532012-12-20 19:27:06 +00001230 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001231 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001232 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001233 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001234 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001235 if (CodeGenOpts.EnableSegmentedStacks &&
1236 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001237 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001238
Bill Wendling2f81db62013-02-22 20:53:29 +00001239 if (AttrOnCallSite) {
1240 // Attributes that should go on the call site only.
1241 if (!CodeGenOpts.SimplifyLibCalls)
1242 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Bill Wendling706469b2013-02-28 22:49:57 +00001243 } else {
1244 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001245 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001246 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001247 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001248 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001249 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001250 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001251 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001252 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001253 }
1254
Bill Wendlingdabafea2013-03-13 22:24:33 +00001255 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001256 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001257 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001258 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001259 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001260 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001261 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001262 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001263 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001264 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001265 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001266 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001267
Bill Wendlingd8f49502013-08-01 21:41:02 +00001268 if (!CodeGenOpts.StackRealignment)
1269 FuncAttrs.addAttribute("no-realign-stack");
Bill Wendling985d1c52013-02-15 21:30:01 +00001270 }
1271
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001272 ClangToLLVMArgMapping IRFunctionArgs(*this, FI);
1273
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001274 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001275 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001276 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001277 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001278 if (RetTy->hasSignedIntegerRepresentation())
1279 RetAttrs.addAttribute(llvm::Attribute::SExt);
1280 else if (RetTy->hasUnsignedIntegerRepresentation())
1281 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001282 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001283 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001284 if (RetAI.getInReg())
1285 RetAttrs.addAttribute(llvm::Attribute::InReg);
1286 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001287 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001288 break;
1289
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001290 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001291 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001292 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001293 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1294 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001295 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001296 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001297
Daniel Dunbard3674e62008-09-11 01:48:57 +00001298 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001299 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001300 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001301
Hal Finkela2347ba2014-07-18 15:52:10 +00001302 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1303 QualType PTy = RefTy->getPointeeType();
1304 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1305 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1306 .getQuantity());
1307 else if (getContext().getTargetAddressSpace(PTy) == 0)
1308 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1309 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001310
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001311 // Attach return attributes.
1312 if (RetAttrs.hasAttributes()) {
1313 PAL.push_back(llvm::AttributeSet::get(
1314 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1315 }
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001316
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001317 // Attach attributes to sret.
1318 if (IRFunctionArgs.hasSRetArg()) {
1319 llvm::AttrBuilder SRETAttrs;
1320 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
1321 if (RetAI.getInReg())
1322 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1323 PAL.push_back(llvm::AttributeSet::get(
1324 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1325 }
1326
1327 // Attach attributes to inalloca argument.
1328 if (IRFunctionArgs.hasInallocaArg()) {
1329 llvm::AttrBuilder Attrs;
1330 Attrs.addAttribute(llvm::Attribute::InAlloca);
1331 PAL.push_back(llvm::AttributeSet::get(
1332 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1333 }
1334
1335
1336 unsigned ArgNo = 0;
1337 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1338 E = FI.arg_end();
1339 I != E; ++I, ++ArgNo) {
1340 QualType ParamType = I->type;
1341 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001342 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001343
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001344 // Add attribute for padding argument, if necessary.
1345 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendling290d9522013-01-27 02:46:53 +00001346 if (AI.getPaddingInReg())
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001347 PAL.push_back(llvm::AttributeSet::get(
1348 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1349 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001350 }
1351
John McCall39ec71f2010-03-27 00:47:27 +00001352 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1353 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001354 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001355 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001356 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001357 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001358 Attrs.addAttribute(llvm::Attribute::SExt);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001359 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001360 Attrs.addAttribute(llvm::Attribute::ZExt);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001361 // FALL THROUGH
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001362 case ABIArgInfo::Direct:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001363 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001364 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001365 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001366
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001367 case ABIArgInfo::Indirect:
Rafael Espindola703c47f2012-10-19 05:04:37 +00001368 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001369 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001370
Anders Carlsson20759ad2009-09-16 15:53:40 +00001371 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001372 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001373
Bill Wendlinga7912f82012-10-10 07:36:56 +00001374 Attrs.addAlignmentAttr(AI.getIndirectAlign());
1375
Daniel Dunbarc2304432009-03-18 19:51:01 +00001376 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001377 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1378 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001379 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001380
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001381 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001382 case ABIArgInfo::Expand:
Mike Stump11289f42009-09-09 15:08:12 +00001383 continue;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001384
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001385 case ABIArgInfo::InAlloca:
1386 // inalloca disables readnone and readonly.
1387 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1388 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001389 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001390 }
Mike Stump11289f42009-09-09 15:08:12 +00001391
Hal Finkela2347ba2014-07-18 15:52:10 +00001392 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1393 QualType PTy = RefTy->getPointeeType();
1394 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1395 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1396 .getQuantity());
1397 else if (getContext().getTargetAddressSpace(PTy) == 0)
1398 Attrs.addAttribute(llvm::Attribute::NonNull);
1399 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001400
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001401 if (Attrs.hasAttributes()) {
1402 unsigned FirstIRArg, NumIRArgs;
1403 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1404 for (unsigned i = 0; i < NumIRArgs; i++)
1405 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
1406 FirstIRArg + i + 1, Attrs));
1407 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001408 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001409 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001410
Bill Wendlinga7912f82012-10-10 07:36:56 +00001411 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001412 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001413 AttributeSet::get(getLLVMContext(),
1414 llvm::AttributeSet::FunctionIndex,
1415 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001416}
1417
John McCalla738c252011-03-09 04:27:21 +00001418/// An argument came in as a promoted argument; demote it back to its
1419/// declared type.
1420static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1421 const VarDecl *var,
1422 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001423 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001424
1425 // This can happen with promotions that actually don't change the
1426 // underlying type, like the enum promotions.
1427 if (value->getType() == varType) return value;
1428
1429 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1430 && "unexpected promotion type");
1431
1432 if (isa<llvm::IntegerType>(varType))
1433 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1434
1435 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1436}
1437
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001438static bool shouldAddNonNullAttr(const Decl *FD, const ParmVarDecl *PVD) {
1439 // FIXME: __attribute__((nonnull)) can also be applied to:
1440 // - references to pointers, where the pointee is known to be
1441 // nonnull (apparently a Clang extension)
1442 // - transparent unions containing pointers
1443 // In the former case, LLVM IR cannot represent the constraint. In
1444 // the latter case, we have no guarantee that the transparent union
1445 // is in fact passed as a pointer.
1446 if (!PVD->getType()->isAnyPointerType() &&
1447 !PVD->getType()->isBlockPointerType())
1448 return false;
1449 // First, check attribute on parameter itself.
1450 if (PVD->hasAttr<NonNullAttr>())
1451 return true;
1452 // Check function attributes.
1453 if (!FD)
1454 return false;
1455 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
1456 if (NNAttr->isNonNull(PVD->getFunctionScopeIndex()))
1457 return true;
1458 }
1459 return false;
1460}
1461
Daniel Dunbard931a872009-02-02 22:03:45 +00001462void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1463 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00001464 const FunctionArgList &Args) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00001465 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
1466 // Naked functions don't have prologues.
1467 return;
1468
John McCallcaa19452009-07-28 01:00:58 +00001469 // If this is an implicit-return-zero function, go ahead and
1470 // initialize the return value. TODO: it might be nice to have
1471 // a more general mechanism for this that didn't require synthesized
1472 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00001473 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00001474 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00001475 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001476 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00001477 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00001478 Builder.CreateStore(Zero, ReturnValue);
1479 }
1480 }
1481
Mike Stump18bb9282009-05-16 07:57:57 +00001482 // FIXME: We no longer need the types from FunctionArgList; lift up and
1483 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00001484
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001485 ClangToLLVMArgMapping IRFunctionArgs(CGM, FI);
1486 // Flattened function arguments.
1487 SmallVector<llvm::Argument *, 16> FnArgs;
1488 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
1489 for (auto &Arg : Fn->args()) {
1490 FnArgs.push_back(&Arg);
1491 }
1492 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00001493
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001494 // If we're using inalloca, all the memory arguments are GEPs off of the last
1495 // parameter, which is a pointer to the complete memory area.
Craig Topper8a13c412014-05-21 05:09:00 +00001496 llvm::Value *ArgStruct = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001497 if (IRFunctionArgs.hasInallocaArg()) {
1498 ArgStruct = FnArgs[IRFunctionArgs.getInallocaArgNo()];
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001499 assert(ArgStruct->getType() == FI.getArgStruct()->getPointerTo());
1500 }
1501
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001502 // Name the struct return parameter.
1503 if (IRFunctionArgs.hasSRetArg()) {
1504 auto AI = FnArgs[IRFunctionArgs.getSRetArgNo()];
Daniel Dunbar613855c2008-09-09 23:27:19 +00001505 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00001506 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001507 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00001508 }
Mike Stump11289f42009-09-09 15:08:12 +00001509
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001510 // Track if we received the parameter as a pointer (indirect, byval, or
1511 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
1512 // into a local alloca for us.
1513 enum ValOrPointer { HaveValue = 0, HavePointer = 1 };
Reid Kleckner8ae16272014-02-01 00:23:22 +00001514 typedef llvm::PointerIntPair<llvm::Value *, 1> ValueAndIsPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001515 SmallVector<ValueAndIsPtr, 16> ArgVals;
1516 ArgVals.reserve(Args.size());
1517
Reid Kleckner739756c2013-12-04 19:23:12 +00001518 // Create a pointer value for every parameter declaration. This usually
1519 // entails copying one or more LLVM IR arguments into an alloca. Don't push
1520 // any cleanups or do anything that might unwind. We do that separately, so
1521 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00001522 assert(FI.arg_size() == Args.size() &&
1523 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001524 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001525 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001526 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00001527 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00001528 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001529 QualType Ty = info_it->type;
1530 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001531
John McCalla738c252011-03-09 04:27:21 +00001532 bool isPromoted =
1533 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1534
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001535 unsigned FirstIRArg, NumIRArgs;
1536 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00001537
Daniel Dunbard3674e62008-09-11 01:48:57 +00001538 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001539 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001540 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001541 llvm::Value *V = Builder.CreateStructGEP(
1542 ArgStruct, ArgI.getInAllocaFieldIndex(), Arg->getName());
1543 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001544 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001545 }
1546
Daniel Dunbar747865a2009-02-05 09:16:39 +00001547 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001548 assert(NumIRArgs == 1);
1549 llvm::Value *V = FnArgs[FirstIRArg];
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001550
John McCall47fb9502013-03-07 21:37:08 +00001551 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001552 // Aggregates and complex variables are accessed by reference. All we
1553 // need to do is realign the value, if requested
1554 if (ArgI.getIndirectRealign()) {
1555 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1556
1557 // Copy from the incoming argument pointer to the temporary with the
1558 // appropriate alignment.
1559 //
1560 // FIXME: We should have a common utility for generating an aggregate
1561 // copy.
Chris Lattner2192fe52011-07-18 04:24:23 +00001562 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyck705ba072011-01-19 01:58:38 +00001563 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumidd634362011-03-10 14:02:21 +00001564 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1565 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1566 Builder.CreateMemCpy(Dst,
1567 Src,
Ken Dyck705ba072011-01-19 01:58:38 +00001568 llvm::ConstantInt::get(IntPtrTy,
1569 Size.getQuantity()),
Benjamin Krameracc6b4e2010-12-30 00:13:21 +00001570 ArgI.getIndirectAlign(),
1571 false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001572 V = AlignedTemp;
1573 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001574 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001575 } else {
1576 // Load scalar value from indirect argument.
Ken Dyck705ba072011-01-19 01:58:38 +00001577 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
Nick Lewycky2d84e842013-10-02 02:29:49 +00001578 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty,
1579 Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001580
1581 if (isPromoted)
1582 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001583 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001584 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00001585 break;
1586 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001587
1588 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001589 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00001590
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001591 // If we have the trivial case, handle it with no muss and fuss.
1592 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001593 ArgI.getCoerceToType() == ConvertType(Ty) &&
1594 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001595 assert(NumIRArgs == 1);
1596 auto AI = FnArgs[FirstIRArg];
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001597 llvm::Value *V = AI;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001598
Hal Finkel48d53e22014-07-19 01:41:07 +00001599 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001600 if (shouldAddNonNullAttr(CurCodeDecl, PVD))
Hal Finkel82504f02014-07-11 17:35:21 +00001601 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1602 AI->getArgNo() + 1,
1603 llvm::Attribute::NonNull));
1604
Hal Finkel48d53e22014-07-19 01:41:07 +00001605 QualType OTy = PVD->getOriginalType();
1606 if (const auto *ArrTy =
1607 getContext().getAsConstantArrayType(OTy)) {
1608 // A C99 array parameter declaration with the static keyword also
1609 // indicates dereferenceability, and if the size is constant we can
1610 // use the dereferenceable attribute (which requires the size in
1611 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00001612 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00001613 QualType ETy = ArrTy->getElementType();
1614 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
1615 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
1616 ArrSize) {
1617 llvm::AttrBuilder Attrs;
1618 Attrs.addDereferenceableAttr(
1619 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
1620 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1621 AI->getArgNo() + 1, Attrs));
1622 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
1623 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1624 AI->getArgNo() + 1,
1625 llvm::Attribute::NonNull));
1626 }
1627 }
1628 } else if (const auto *ArrTy =
1629 getContext().getAsVariableArrayType(OTy)) {
1630 // For C99 VLAs with the static keyword, we don't know the size so
1631 // we can't use the dereferenceable attribute, but in addrspace(0)
1632 // we know that it must be nonnull.
1633 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
1634 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
1635 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1636 AI->getArgNo() + 1,
1637 llvm::Attribute::NonNull));
1638 }
1639 }
1640
Bill Wendling507c3512012-10-16 05:23:44 +00001641 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001642 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1643 AI->getArgNo() + 1,
1644 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00001645
Chris Lattner7369c142011-07-20 06:29:00 +00001646 // Ensure the argument is the correct type.
1647 if (V->getType() != ArgI.getCoerceToType())
1648 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1649
John McCalla738c252011-03-09 04:27:21 +00001650 if (isPromoted)
1651 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00001652
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001653 if (const CXXMethodDecl *MD =
1654 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001655 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001656 V = CGM.getCXXABI().
1657 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001658 }
1659
Rafael Espindola8778c282012-11-29 16:09:03 +00001660 // Because of merging of function types from multiple decls it is
1661 // possible for the type of an argument to not match the corresponding
1662 // type in the function type. Since we are codegening the callee
1663 // in here, add a cast to the argument type.
1664 llvm::Type *LTy = ConvertType(Arg->getType());
1665 if (V->getType() != LTy)
1666 V = Builder.CreateBitCast(V, LTy);
1667
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001668 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001669 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00001670 }
Mike Stump11289f42009-09-09 15:08:12 +00001671
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001672 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001673
Chris Lattnerff941a62010-07-28 18:24:28 +00001674 // The alignment we need to use is the max of the requested alignment for
1675 // the argument plus the alignment required by our access code below.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001676 unsigned AlignmentToUse =
Micah Villmowdd31ca12012-10-08 16:25:52 +00001677 CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerff941a62010-07-28 18:24:28 +00001678 AlignmentToUse = std::max(AlignmentToUse,
1679 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001680
Chris Lattnerff941a62010-07-28 18:24:28 +00001681 Alloca->setAlignment(AlignmentToUse);
Chris Lattnerc401de92010-07-05 20:21:00 +00001682 llvm::Value *V = Alloca;
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001683 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001684
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001685 // If the value is offset in memory, apply the offset now.
1686 if (unsigned Offs = ArgI.getDirectOffset()) {
1687 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1688 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001689 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001690 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1691 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001692
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001693 // Fast-isel and the optimizer generally like scalar values better than
1694 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001695 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001696 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
1697 STy->getNumElements() > 1) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001698 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001699 llvm::Type *DstTy =
1700 cast<llvm::PointerType>(Ptr->getType())->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00001701 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001702
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001703 if (SrcSize <= DstSize) {
1704 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1705
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001706 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001707 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001708 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001709 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1710 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001711 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001712 }
1713 } else {
1714 llvm::AllocaInst *TempAlloca =
1715 CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1716 TempAlloca->setAlignment(AlignmentToUse);
1717 llvm::Value *TempV = TempAlloca;
1718
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001719 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001720 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001721 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001722 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1723 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(TempV, 0, i);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001724 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001725 }
1726
1727 Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
Chris Lattner15ec3612010-06-29 00:06:42 +00001728 }
1729 } else {
1730 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001731 assert(NumIRArgs == 1);
1732 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00001733 AI->setName(Arg->getName() + ".coerce");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001734 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00001735 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001736
1737
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001738 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00001739 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001740 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001741 if (isPromoted)
1742 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001743 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
1744 } else {
1745 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00001746 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001747 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001748 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001749
1750 case ABIArgInfo::Expand: {
1751 // If this structure was expanded into multiple arguments then
1752 // we need to create a temporary and reconstruct it from the
1753 // arguments.
Eli Friedman3d9f47f2011-11-03 21:39:02 +00001754 llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
Eli Friedmana0544d62011-12-03 04:14:32 +00001755 CharUnits Align = getContext().getDeclAlign(Arg);
1756 Alloca->setAlignment(Align.getQuantity());
1757 LValue LV = MakeAddrLValue(Alloca, Ty, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001758 ArgVals.push_back(ValueAndIsPtr(Alloca, HavePointer));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001759
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001760 auto FnArgIter = FnArgs.begin() + FirstIRArg;
1761 ExpandTypeFromArgs(Ty, LV, FnArgIter);
1762 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
1763 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
1764 auto AI = FnArgs[FirstIRArg + i];
1765 AI->setName(Arg->getName() + "." + Twine(i));
1766 }
1767 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001768 }
1769
1770 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001771 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001772 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001773 if (!hasScalarEvaluationKind(Ty)) {
1774 ArgVals.push_back(ValueAndIsPtr(CreateMemTemp(Ty), HavePointer));
1775 } else {
1776 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
1777 ArgVals.push_back(ValueAndIsPtr(U, HaveValue));
1778 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001779 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001780 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00001781 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001782
Reid Kleckner739756c2013-12-04 19:23:12 +00001783 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1784 for (int I = Args.size() - 1; I >= 0; --I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001785 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1786 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00001787 } else {
1788 for (unsigned I = 0, E = Args.size(); I != E; ++I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001789 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1790 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00001791 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00001792}
1793
John McCallffa2c1a2012-01-29 07:46:59 +00001794static void eraseUnusedBitCasts(llvm::Instruction *insn) {
1795 while (insn->use_empty()) {
1796 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
1797 if (!bitcast) return;
1798
1799 // This is "safe" because we would have used a ConstantExpr otherwise.
1800 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
1801 bitcast->eraseFromParent();
1802 }
1803}
1804
John McCall31168b02011-06-15 23:02:42 +00001805/// Try to emit a fused autorelease of a return result.
1806static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
1807 llvm::Value *result) {
1808 // We must be immediately followed the cast.
1809 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00001810 if (BB->empty()) return nullptr;
1811 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001812
Chris Lattner2192fe52011-07-18 04:24:23 +00001813 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00001814
1815 // result is in a BasicBlock and is therefore an Instruction.
1816 llvm::Instruction *generator = cast<llvm::Instruction>(result);
1817
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001818 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00001819
1820 // Look for:
1821 // %generator = bitcast %type1* %generator2 to %type2*
1822 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
1823 // We would have emitted this as a constant if the operand weren't
1824 // an Instruction.
1825 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
1826
1827 // Require the generator to be immediately followed by the cast.
1828 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00001829 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001830
1831 insnsToKill.push_back(bitcast);
1832 }
1833
1834 // Look for:
1835 // %generator = call i8* @objc_retain(i8* %originalResult)
1836 // or
1837 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
1838 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00001839 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001840
1841 bool doRetainAutorelease;
1842
1843 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
1844 doRetainAutorelease = true;
1845 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
1846 .objc_retainAutoreleasedReturnValue) {
1847 doRetainAutorelease = false;
1848
John McCallcfa4e9b2012-09-07 23:30:50 +00001849 // If we emitted an assembly marker for this call (and the
1850 // ARCEntrypoints field should have been set if so), go looking
1851 // for that call. If we can't find it, we can't do this
1852 // optimization. But it should always be the immediately previous
1853 // instruction, unless we needed bitcasts around the call.
1854 if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
1855 llvm::Instruction *prev = call->getPrevNode();
1856 assert(prev);
1857 if (isa<llvm::BitCastInst>(prev)) {
1858 prev = prev->getPrevNode();
1859 assert(prev);
1860 }
1861 assert(isa<llvm::CallInst>(prev));
1862 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
1863 CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
1864 insnsToKill.push_back(prev);
1865 }
John McCall31168b02011-06-15 23:02:42 +00001866 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00001867 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001868 }
1869
1870 result = call->getArgOperand(0);
1871 insnsToKill.push_back(call);
1872
1873 // Keep killing bitcasts, for sanity. Note that we no longer care
1874 // about precise ordering as long as there's exactly one use.
1875 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
1876 if (!bitcast->hasOneUse()) break;
1877 insnsToKill.push_back(bitcast);
1878 result = bitcast->getOperand(0);
1879 }
1880
1881 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001882 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00001883 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
1884 (*i)->eraseFromParent();
1885
1886 // Do the fused retain/autorelease if we were asked to.
1887 if (doRetainAutorelease)
1888 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
1889
1890 // Cast back to the result type.
1891 return CGF.Builder.CreateBitCast(result, resultType);
1892}
1893
John McCallffa2c1a2012-01-29 07:46:59 +00001894/// If this is a +1 of the value of an immutable 'self', remove it.
1895static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
1896 llvm::Value *result) {
1897 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00001898 const ObjCMethodDecl *method =
1899 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00001900 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00001901 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00001902 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00001903
1904 // Look for a retain call.
1905 llvm::CallInst *retainCall =
1906 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
1907 if (!retainCall ||
1908 retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00001909 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00001910
1911 // Look for an ordinary load of 'self'.
1912 llvm::Value *retainedValue = retainCall->getArgOperand(0);
1913 llvm::LoadInst *load =
1914 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
1915 if (!load || load->isAtomic() || load->isVolatile() ||
1916 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
Craig Topper8a13c412014-05-21 05:09:00 +00001917 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00001918
1919 // Okay! Burn it all down. This relies for correctness on the
1920 // assumption that the retain is emitted as part of the return and
1921 // that thereafter everything is used "linearly".
1922 llvm::Type *resultType = result->getType();
1923 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
1924 assert(retainCall->use_empty());
1925 retainCall->eraseFromParent();
1926 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
1927
1928 return CGF.Builder.CreateBitCast(load, resultType);
1929}
1930
John McCall31168b02011-06-15 23:02:42 +00001931/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00001932///
1933/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00001934static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
1935 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00001936 // If we're returning 'self', kill the initial retain. This is a
1937 // heuristic attempt to "encourage correctness" in the really unfortunate
1938 // case where we have a return of self during a dealloc and we desperately
1939 // need to avoid the possible autorelease.
1940 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
1941 return self;
1942
John McCall31168b02011-06-15 23:02:42 +00001943 // At -O0, try to emit a fused retain/autorelease.
1944 if (CGF.shouldUseFusedARCCalls())
1945 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
1946 return fused;
1947
1948 return CGF.EmitARCAutoreleaseReturnValue(result);
1949}
1950
John McCall6e1c0122012-01-29 02:35:02 +00001951/// Heuristically search for a dominating store to the return-value slot.
1952static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
1953 // If there are multiple uses of the return-value slot, just check
1954 // for something immediately preceding the IP. Sometimes this can
1955 // happen with how we generate implicit-returns; it can also happen
1956 // with noreturn cleanups.
1957 if (!CGF.ReturnValue->hasOneUse()) {
1958 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00001959 if (IP->empty()) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00001960 llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back());
Craig Topper8a13c412014-05-21 05:09:00 +00001961 if (!store) return nullptr;
1962 if (store->getPointerOperand() != CGF.ReturnValue) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00001963 assert(!store->isAtomic() && !store->isVolatile()); // see below
1964 return store;
1965 }
1966
1967 llvm::StoreInst *store =
Chandler Carruth4d01fff2014-03-09 03:16:50 +00001968 dyn_cast<llvm::StoreInst>(CGF.ReturnValue->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00001969 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00001970
1971 // These aren't actually possible for non-coerced returns, and we
1972 // only care about non-coerced returns on this code path.
1973 assert(!store->isAtomic() && !store->isVolatile());
1974
1975 // Now do a first-and-dirty dominance check: just walk up the
1976 // single-predecessors chain from the current insertion point.
1977 llvm::BasicBlock *StoreBB = store->getParent();
1978 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
1979 while (IP != StoreBB) {
1980 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00001981 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00001982 }
1983
1984 // Okay, the store's basic block dominates the insertion point; we
1985 // can do our thing.
1986 return store;
1987}
1988
Adrian Prantl3be10542013-05-02 17:30:20 +00001989void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001990 bool EmitRetDbgLoc,
1991 SourceLocation EndLoc) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00001992 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
1993 // Naked functions don't have epilogues.
1994 Builder.CreateUnreachable();
1995 return;
1996 }
1997
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001998 // Functions with no result always return void.
Craig Topper8a13c412014-05-21 05:09:00 +00001999 if (!ReturnValue) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002000 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00002001 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002002 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00002003
Dan Gohman481e40c2010-07-20 20:13:52 +00002004 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00002005 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00002006 QualType RetTy = FI.getReturnType();
2007 const ABIArgInfo &RetAI = FI.getReturnInfo();
2008
2009 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002010 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00002011 // Aggregrates get evaluated directly into the destination. Sometimes we
2012 // need to return the sret value in a register, though.
2013 assert(hasAggregateEvaluationKind(RetTy));
2014 if (RetAI.getInAllocaSRet()) {
2015 llvm::Function::arg_iterator EI = CurFn->arg_end();
2016 --EI;
2017 llvm::Value *ArgStruct = EI;
2018 llvm::Value *SRet =
2019 Builder.CreateStructGEP(ArgStruct, RetAI.getInAllocaFieldIndex());
2020 RV = Builder.CreateLoad(SRet, "sret");
2021 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002022 break;
2023
Daniel Dunbar03816342010-08-21 02:24:36 +00002024 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002025 auto AI = CurFn->arg_begin();
2026 if (RetAI.isSRetAfterThis())
2027 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002028 switch (getEvaluationKind(RetTy)) {
2029 case TEK_Complex: {
2030 ComplexPairTy RT =
Nick Lewycky2d84e842013-10-02 02:29:49 +00002031 EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
2032 EndLoc);
Reid Kleckner37abaca2014-05-09 22:46:15 +00002033 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002034 /*isInit*/ true);
2035 break;
2036 }
2037 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002038 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002039 break;
2040 case TEK_Scalar:
2041 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Reid Kleckner37abaca2014-05-09 22:46:15 +00002042 MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002043 /*isInit*/ true);
2044 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002045 }
2046 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002047 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002048
2049 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002050 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002051 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2052 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002053 // The internal return value temp always will have pointer-to-return-type
2054 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002055
John McCall6e1c0122012-01-29 02:35:02 +00002056 // If there is a dominating store to ReturnValue, we can elide
2057 // the load, zap the store, and usually zap the alloca.
2058 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002059 // Reuse the debug location from the store unless there is
2060 // cleanup code to be emitted between the store and return
2061 // instruction.
2062 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002063 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002064 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002065 RV = SI->getValueOperand();
2066 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002067
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002068 // If that was the only use of the return value, nuke it as well now.
2069 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
2070 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00002071 ReturnValue = nullptr;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002072 }
John McCall6e1c0122012-01-29 02:35:02 +00002073
2074 // Otherwise, we have to do a simple load.
2075 } else {
2076 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002077 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002078 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002079 llvm::Value *V = ReturnValue;
2080 // If the value is offset in memory, apply the offset now.
2081 if (unsigned Offs = RetAI.getDirectOffset()) {
2082 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
2083 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002084 V = Builder.CreateBitCast(V,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002085 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
2086 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002087
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002088 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002089 }
John McCall31168b02011-06-15 23:02:42 +00002090
2091 // In ARC, end functions that return a retainable type with a call
2092 // to objc_autoreleaseReturnValue.
2093 if (AutoreleaseResult) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002094 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002095 !FI.isReturnsRetained() &&
2096 RetTy->isObjCRetainableType());
2097 RV = emitAutoreleaseOfResult(*this, RV);
2098 }
2099
Chris Lattner726b3d02010-06-26 23:13:19 +00002100 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002101
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002102 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002103 break;
2104
2105 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002106 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002107 }
2108
Alexey Samsonovde443c52014-08-13 00:26:40 +00002109 llvm::Instruction *Ret;
2110 if (RV) {
2111 if (SanOpts->ReturnsNonnullAttribute &&
2112 CurGD.getDecl()->hasAttr<ReturnsNonNullAttr>()) {
2113 SanitizerScope SanScope(this);
2114 llvm::Value *Cond =
2115 Builder.CreateICmpNE(RV, llvm::Constant::getNullValue(RV->getType()));
2116 llvm::Constant *StaticData[] = {
2117 EmitCheckSourceLocation(EndLoc)
2118 };
Craig Topper5fc8fc22014-08-27 06:28:36 +00002119 EmitCheck(Cond, "nonnull_return", StaticData, None, CRK_Recoverable);
Alexey Samsonovde443c52014-08-13 00:26:40 +00002120 }
2121 Ret = Builder.CreateRet(RV);
2122 } else {
2123 Ret = Builder.CreateRetVoid();
2124 }
2125
Devang Patel65497582010-07-21 18:08:50 +00002126 if (!RetDbgLoc.isUnknown())
2127 Ret->setDebugLoc(RetDbgLoc);
Daniel Dunbar613855c2008-09-09 23:27:19 +00002128}
2129
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002130static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2131 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2132 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2133}
2134
2135static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty) {
2136 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2137 // placeholders.
2138 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2139 llvm::Value *Placeholder =
2140 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2141 Placeholder = CGF.Builder.CreateLoad(Placeholder);
2142 return AggValueSlot::forAddr(Placeholder, CharUnits::Zero(),
2143 Ty.getQualifiers(),
2144 AggValueSlot::IsNotDestructed,
2145 AggValueSlot::DoesNotNeedGCBarriers,
2146 AggValueSlot::IsNotAliased);
2147}
2148
John McCall32ea9692011-03-11 20:59:21 +00002149void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002150 const VarDecl *param,
2151 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002152 // StartFunction converted the ABI-lowered parameter(s) into a
2153 // local alloca. We need to turn that into an r-value suitable
2154 // for EmitCall.
John McCall32ea9692011-03-11 20:59:21 +00002155 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002156
John McCall32ea9692011-03-11 20:59:21 +00002157 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002158
John McCall23f66262010-05-26 22:34:26 +00002159 // For the most part, we just need to load the alloca, except:
2160 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall47fb9502013-03-07 21:37:08 +00002161 // 2) references to non-scalars are pointers directly to the aggregate.
2162 // I don't know why references to scalars are different here.
John McCall32ea9692011-03-11 20:59:21 +00002163 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall47fb9502013-03-07 21:37:08 +00002164 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall32ea9692011-03-11 20:59:21 +00002165 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00002166
2167 // Locals which are references to scalars are represented
2168 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00002169 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00002170 }
2171
Reid Klecknerab2090d2014-07-26 01:34:32 +00002172 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2173 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002174
Nick Lewycky2d84e842013-10-02 02:29:49 +00002175 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00002176}
2177
John McCall31168b02011-06-15 23:02:42 +00002178static bool isProvablyNull(llvm::Value *addr) {
2179 return isa<llvm::ConstantPointerNull>(addr);
2180}
2181
2182static bool isProvablyNonNull(llvm::Value *addr) {
2183 return isa<llvm::AllocaInst>(addr);
2184}
2185
2186/// Emit the actual writing-back of a writeback.
2187static void emitWriteback(CodeGenFunction &CGF,
2188 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002189 const LValue &srcLV = writeback.Source;
2190 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002191 assert(!isProvablyNull(srcAddr) &&
2192 "shouldn't have writeback for provably null argument");
2193
Craig Topper8a13c412014-05-21 05:09:00 +00002194 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002195
2196 // If the argument wasn't provably non-null, we need to null check
2197 // before doing the store.
2198 bool provablyNonNull = isProvablyNonNull(srcAddr);
2199 if (!provablyNonNull) {
2200 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2201 contBB = CGF.createBasicBlock("icr.done");
2202
2203 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2204 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2205 CGF.EmitBlock(writebackBB);
2206 }
2207
2208 // Load the value to writeback.
2209 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2210
2211 // Cast it back, in case we're writing an id to a Foo* or something.
2212 value = CGF.Builder.CreateBitCast(value,
2213 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
2214 "icr.writeback-cast");
2215
2216 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00002217
2218 // If we have a "to use" value, it's something we need to emit a use
2219 // of. This has to be carefully threaded in: if it's done after the
2220 // release it's potentially undefined behavior (and the optimizer
2221 // will ignore it), and if it happens before the retain then the
2222 // optimizer could move the release there.
2223 if (writeback.ToUse) {
2224 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2225
2226 // Retain the new value. No need to block-copy here: the block's
2227 // being passed up the stack.
2228 value = CGF.EmitARCRetainNonBlock(value);
2229
2230 // Emit the intrinsic use here.
2231 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2232
2233 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00002234 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00002235
2236 // Put the new value in place (primitively).
2237 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2238
2239 // Release the old value.
2240 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2241
2242 // Otherwise, we can just do a normal lvalue store.
2243 } else {
2244 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2245 }
John McCall31168b02011-06-15 23:02:42 +00002246
2247 // Jump to the continuation block.
2248 if (!provablyNonNull)
2249 CGF.EmitBlock(contBB);
2250}
2251
2252static void emitWritebacks(CodeGenFunction &CGF,
2253 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00002254 for (const auto &I : args.writebacks())
2255 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00002256}
2257
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002258static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2259 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002260 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002261 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2262 CallArgs.getCleanupsToDeactivate();
2263 // Iterate in reverse to increase the likelihood of popping the cleanup.
2264 for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
2265 I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
2266 CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
2267 I->IsActiveIP->eraseFromParent();
2268 }
2269}
2270
John McCalleff18842013-03-23 02:35:54 +00002271static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2272 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2273 if (uop->getOpcode() == UO_AddrOf)
2274 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002275 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00002276}
2277
John McCall31168b02011-06-15 23:02:42 +00002278/// Emit an argument that's being passed call-by-writeback. That is,
2279/// we are passing the address of
2280static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2281 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00002282 LValue srcLV;
2283
2284 // Make an optimistic effort to emit the address as an l-value.
2285 // This can fail if the the argument expression is more complicated.
2286 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2287 srcLV = CGF.EmitLValue(lvExpr);
2288
2289 // Otherwise, just emit it as a scalar.
2290 } else {
2291 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
2292
2293 QualType srcAddrType =
2294 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
2295 srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
2296 }
2297 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002298
2299 // The dest and src types don't necessarily match in LLVM terms
2300 // because of the crazy ObjC compatibility rules.
2301
Chris Lattner2192fe52011-07-18 04:24:23 +00002302 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00002303 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
2304
2305 // If the address is a constant null, just pass the appropriate null.
2306 if (isProvablyNull(srcAddr)) {
2307 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
2308 CRE->getType());
2309 return;
2310 }
2311
John McCall31168b02011-06-15 23:02:42 +00002312 // Create the temporary.
2313 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
2314 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002315 // Loading an l-value can introduce a cleanup if the l-value is __weak,
2316 // and that cleanup will be conditional if we can't prove that the l-value
2317 // isn't null, so we need to register a dominating point so that the cleanups
2318 // system will make valid IR.
2319 CodeGenFunction::ConditionalEvaluation condEval(CGF);
2320
John McCall31168b02011-06-15 23:02:42 +00002321 // Zero-initialize it if we're not doing a copy-initialization.
2322 bool shouldCopy = CRE->shouldCopy();
2323 if (!shouldCopy) {
2324 llvm::Value *null =
2325 llvm::ConstantPointerNull::get(
2326 cast<llvm::PointerType>(destType->getElementType()));
2327 CGF.Builder.CreateStore(null, temp);
2328 }
Craig Topper8a13c412014-05-21 05:09:00 +00002329
2330 llvm::BasicBlock *contBB = nullptr;
2331 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002332
2333 // If the address is *not* known to be non-null, we need to switch.
2334 llvm::Value *finalArgument;
2335
2336 bool provablyNonNull = isProvablyNonNull(srcAddr);
2337 if (provablyNonNull) {
2338 finalArgument = temp;
2339 } else {
2340 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2341
2342 finalArgument = CGF.Builder.CreateSelect(isNull,
2343 llvm::ConstantPointerNull::get(destType),
2344 temp, "icr.argument");
2345
2346 // If we need to copy, then the load has to be conditional, which
2347 // means we need control flow.
2348 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00002349 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002350 contBB = CGF.createBasicBlock("icr.cont");
2351 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
2352 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
2353 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002354 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00002355 }
2356 }
2357
Craig Topper8a13c412014-05-21 05:09:00 +00002358 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00002359
John McCall31168b02011-06-15 23:02:42 +00002360 // Perform a copy if necessary.
2361 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002362 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002363 assert(srcRV.isScalar());
2364
2365 llvm::Value *src = srcRV.getScalarVal();
2366 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
2367 "icr.cast");
2368
2369 // Use an ordinary store, not a store-to-lvalue.
2370 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00002371
2372 // If optimization is enabled, and the value was held in a
2373 // __strong variable, we need to tell the optimizer that this
2374 // value has to stay alive until we're doing the store back.
2375 // This is because the temporary is effectively unretained,
2376 // and so otherwise we can violate the high-level semantics.
2377 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2378 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
2379 valueToUse = src;
2380 }
John McCall31168b02011-06-15 23:02:42 +00002381 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002382
John McCall31168b02011-06-15 23:02:42 +00002383 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002384 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00002385 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002386 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00002387
2388 // Make a phi for the value to intrinsically use.
2389 if (valueToUse) {
2390 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2391 "icr.to-use");
2392 phiToUse->addIncoming(valueToUse, copyBB);
2393 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2394 originBB);
2395 valueToUse = phiToUse;
2396 }
2397
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002398 condEval.end(CGF);
2399 }
John McCall31168b02011-06-15 23:02:42 +00002400
John McCalleff18842013-03-23 02:35:54 +00002401 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00002402 args.add(RValue::get(finalArgument), CRE->getType());
2403}
2404
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002405void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
2406 assert(!StackBase && !StackCleanup.isValid());
2407
2408 // Save the stack.
2409 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
2410 StackBase = CGF.Builder.CreateCall(F, "inalloca.save");
2411
2412 // Control gets really tied up in landing pads, so we have to spill the
2413 // stacksave to an alloca to avoid violating SSA form.
2414 // TODO: This is dead if we never emit the cleanup. We should create the
2415 // alloca and store lazily on the first cleanup emission.
2416 StackBaseMem = CGF.CreateTempAlloca(CGF.Int8PtrTy, "inalloca.spmem");
2417 CGF.Builder.CreateStore(StackBase, StackBaseMem);
2418 CGF.pushStackRestore(EHCleanup, StackBaseMem);
2419 StackCleanup = CGF.EHStack.getInnermostEHScope();
2420 assert(StackCleanup.isValid());
2421}
2422
2423void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
2424 if (StackBase) {
2425 CGF.DeactivateCleanupBlock(StackCleanup, StackBase);
2426 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
2427 // We could load StackBase from StackBaseMem, but in the non-exceptional
2428 // case we can skip it.
2429 CGF.Builder.CreateCall(F, StackBase);
2430 }
2431}
2432
Reid Kleckner739756c2013-12-04 19:23:12 +00002433void CodeGenFunction::EmitCallArgs(CallArgList &Args,
2434 ArrayRef<QualType> ArgTypes,
2435 CallExpr::const_arg_iterator ArgBeg,
2436 CallExpr::const_arg_iterator ArgEnd,
2437 bool ForceColumnInfo) {
2438 CGDebugInfo *DI = getDebugInfo();
2439 SourceLocation CallLoc;
2440 if (DI) CallLoc = DI->getLocation();
2441
2442 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
2443 // because arguments are destroyed left to right in the callee.
2444 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002445 // Insert a stack save if we're going to need any inalloca args.
2446 bool HasInAllocaArgs = false;
2447 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
2448 I != E && !HasInAllocaArgs; ++I)
2449 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
2450 if (HasInAllocaArgs) {
2451 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2452 Args.allocateArgumentMemory(*this);
2453 }
2454
2455 // Evaluate each argument.
Reid Kleckner739756c2013-12-04 19:23:12 +00002456 size_t CallArgsStart = Args.size();
2457 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
2458 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2459 EmitCallArg(Args, *Arg, ArgTypes[I]);
2460 // Restore the debug location.
2461 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2462 }
2463
2464 // Un-reverse the arguments we just evaluated so they match up with the LLVM
2465 // IR function.
2466 std::reverse(Args.begin() + CallArgsStart, Args.end());
2467 return;
2468 }
2469
2470 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
2471 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2472 assert(Arg != ArgEnd);
2473 EmitCallArg(Args, *Arg, ArgTypes[I]);
2474 // Restore the debug location.
2475 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2476 }
2477}
2478
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002479namespace {
2480
2481struct DestroyUnpassedArg : EHScopeStack::Cleanup {
2482 DestroyUnpassedArg(llvm::Value *Addr, QualType Ty)
2483 : Addr(Addr), Ty(Ty) {}
2484
2485 llvm::Value *Addr;
2486 QualType Ty;
2487
Craig Topper4f12f102014-03-12 06:41:41 +00002488 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002489 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
2490 assert(!Dtor->isTrivial());
2491 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
2492 /*Delegating=*/false, Addr);
2493 }
2494};
2495
2496}
2497
John McCall32ea9692011-03-11 20:59:21 +00002498void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2499 QualType type) {
John McCall31168b02011-06-15 23:02:42 +00002500 if (const ObjCIndirectCopyRestoreExpr *CRE
2501 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002502 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00002503 assert(getContext().hasSameType(E->getType(), type));
2504 return emitWritebackArg(*this, args, CRE);
2505 }
2506
John McCall0a76c0c2011-08-26 18:42:59 +00002507 assert(type->isReferenceType() == E->isGLValue() &&
2508 "reference binding to unmaterialized r-value!");
2509
John McCall17054bd62011-08-26 21:08:13 +00002510 if (E->isGLValue()) {
2511 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00002512 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00002513 }
Mike Stump11289f42009-09-09 15:08:12 +00002514
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002515 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2516
2517 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2518 // However, we still have to push an EH-only cleanup in case we unwind before
2519 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00002520 if (HasAggregateEvalKind &&
2521 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2522 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00002523 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00002524 AggValueSlot Slot;
2525 if (args.isUsingInAlloca())
2526 Slot = createPlaceholderSlot(*this, type);
2527 else
2528 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00002529
2530 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2531 bool DestroyedInCallee =
2532 RD && RD->hasNonTrivialDestructor() &&
2533 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
2534 if (DestroyedInCallee)
2535 Slot.setExternallyDestructed();
2536
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002537 EmitAggExpr(E, Slot);
2538 RValue RV = Slot.asRValue();
2539 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002540
Reid Klecknere39ee212014-05-03 00:33:28 +00002541 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002542 // Create a no-op GEP between the placeholder and the cleanup so we can
2543 // RAUW it successfully. It also serves as a marker of the first
2544 // instruction where the cleanup is active.
2545 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddr(), type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002546 // This unreachable is a temporary marker which will be removed later.
2547 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2548 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002549 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002550 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002551 }
2552
2553 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00002554 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2555 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2556 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00002557 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2558 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2559 } else {
2560 // We can't represent a misaligned lvalue in the CallArgList, so copy
2561 // to an aligned temporary now.
2562 llvm::Value *tmp = CreateMemTemp(type);
2563 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2564 L.getAlignment());
2565 args.add(RValue::getAggregate(tmp), type);
2566 }
Eli Friedmandf968192011-05-26 00:10:27 +00002567 return;
2568 }
2569
John McCall32ea9692011-03-11 20:59:21 +00002570 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00002571}
2572
Dan Gohman515a60d2012-02-16 00:57:37 +00002573// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2574// optimizer it can aggressively ignore unwind edges.
2575void
2576CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2577 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2578 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2579 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2580 CGM.getNoObjCARCExceptionsMetadata());
2581}
2582
John McCall882987f2013-02-28 19:01:20 +00002583/// Emits a call to the given no-arguments nounwind runtime function.
2584llvm::CallInst *
2585CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2586 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002587 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002588}
2589
2590/// Emits a call to the given nounwind runtime function.
2591llvm::CallInst *
2592CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2593 ArrayRef<llvm::Value*> args,
2594 const llvm::Twine &name) {
2595 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2596 call->setDoesNotThrow();
2597 return call;
2598}
2599
2600/// Emits a simple call (never an invoke) to the given no-arguments
2601/// runtime function.
2602llvm::CallInst *
2603CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2604 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002605 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002606}
2607
2608/// Emits a simple call (never an invoke) to the given runtime
2609/// function.
2610llvm::CallInst *
2611CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2612 ArrayRef<llvm::Value*> args,
2613 const llvm::Twine &name) {
2614 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2615 call->setCallingConv(getRuntimeCC());
2616 return call;
2617}
2618
2619/// Emits a call or invoke to the given noreturn runtime function.
2620void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2621 ArrayRef<llvm::Value*> args) {
2622 if (getInvokeDest()) {
2623 llvm::InvokeInst *invoke =
2624 Builder.CreateInvoke(callee,
2625 getUnreachableBlock(),
2626 getInvokeDest(),
2627 args);
2628 invoke->setDoesNotReturn();
2629 invoke->setCallingConv(getRuntimeCC());
2630 } else {
2631 llvm::CallInst *call = Builder.CreateCall(callee, args);
2632 call->setDoesNotReturn();
2633 call->setCallingConv(getRuntimeCC());
2634 Builder.CreateUnreachable();
2635 }
Justin Bogner06bd6d02014-01-13 21:24:18 +00002636 PGO.setCurrentRegionUnreachable();
John McCall882987f2013-02-28 19:01:20 +00002637}
2638
2639/// Emits a call or invoke instruction to the given nullary runtime
2640/// function.
2641llvm::CallSite
2642CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2643 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002644 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002645}
2646
2647/// Emits a call or invoke instruction to the given runtime function.
2648llvm::CallSite
2649CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2650 ArrayRef<llvm::Value*> args,
2651 const Twine &name) {
2652 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2653 callSite.setCallingConv(getRuntimeCC());
2654 return callSite;
2655}
2656
2657llvm::CallSite
2658CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2659 const Twine &Name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002660 return EmitCallOrInvoke(Callee, None, Name);
John McCall882987f2013-02-28 19:01:20 +00002661}
2662
John McCallbd309292010-07-06 01:34:17 +00002663/// Emits a call or invoke instruction to the given function, depending
2664/// on the current state of the EH stack.
2665llvm::CallSite
2666CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00002667 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002668 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00002669 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00002670
Dan Gohman515a60d2012-02-16 00:57:37 +00002671 llvm::Instruction *Inst;
2672 if (!InvokeDest)
2673 Inst = Builder.CreateCall(Callee, Args, Name);
2674 else {
2675 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
2676 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
2677 EmitBlock(ContBB);
2678 }
2679
2680 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2681 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002682 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00002683 AddObjCARCExceptionMetadata(Inst);
2684
2685 return Inst;
John McCallbd309292010-07-06 01:34:17 +00002686}
2687
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002688void CodeGenFunction::ExpandTypeToArgs(
2689 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
2690 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002691 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2692 unsigned NumElts = AT->getSize().getZExtValue();
2693 QualType EltTy = AT->getElementType();
2694 llvm::Value *Addr = RV.getAggregateAddr();
2695 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
2696 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, Elt);
Nick Lewycky2d84e842013-10-02 02:29:49 +00002697 RValue EltRV = convertTempToRValue(EltAddr, EltTy, SourceLocation());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002698 ExpandTypeToArgs(EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
Chris Lattnerd59d8672011-07-12 06:29:11 +00002699 }
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002700 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002701 RecordDecl *RD = RT->getDecl();
2702 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
Eli Friedman7f1ff602012-04-16 03:54:45 +00002703 LValue LV = MakeAddrLValue(RV.getAggregateAddr(), Ty);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002704
2705 if (RD->isUnion()) {
Craig Topper8a13c412014-05-21 05:09:00 +00002706 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002707 CharUnits UnionSize = CharUnits::Zero();
2708
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002709 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002710 assert(!FD->isBitField() &&
2711 "Cannot expand structure with bit-field members.");
2712 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
2713 if (UnionSize < FieldSize) {
2714 UnionSize = FieldSize;
2715 LargestFD = FD;
2716 }
2717 }
2718 if (LargestFD) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002719 RValue FldRV = EmitRValueForField(LV, LargestFD, SourceLocation());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002720 ExpandTypeToArgs(LargestFD->getType(), FldRV, IRFuncTy, IRCallArgs,
2721 IRCallArgPos);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002722 }
2723 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002724 for (const auto *FD : RD->fields()) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002725 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002726 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs, IRCallArgPos);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002727 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00002728 }
Eli Friedman95ff7002011-11-15 02:46:03 +00002729 } else if (Ty->isAnyComplexType()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002730 ComplexPairTy CV = RV.getComplexVal();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002731 IRCallArgs[IRCallArgPos++] = CV.first;
2732 IRCallArgs[IRCallArgPos++] = CV.second;
Bob Wilsone826a2a2011-08-03 05:58:22 +00002733 } else {
Chris Lattnerd59d8672011-07-12 06:29:11 +00002734 assert(RV.isScalar() &&
2735 "Unexpected non-scalar rvalue during struct expansion.");
2736
2737 // Insert a bitcast as needed.
2738 llvm::Value *V = RV.getScalarVal();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002739 if (IRCallArgPos < IRFuncTy->getNumParams() &&
2740 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
2741 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
Chris Lattnerd59d8672011-07-12 06:29:11 +00002742
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002743 IRCallArgs[IRCallArgPos++] = V;
Chris Lattnerd59d8672011-07-12 06:29:11 +00002744 }
2745}
2746
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002747/// \brief Store a non-aggregate value to an address to initialize it. For
2748/// initialization, a non-atomic store will be used.
2749static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
2750 LValue Dst) {
2751 if (Src.isScalar())
2752 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
2753 else
2754 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
2755}
2756
2757void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
2758 llvm::Value *New) {
2759 DeferredReplacements.push_back(std::make_pair(Old, New));
2760}
Chris Lattnerd59d8672011-07-12 06:29:11 +00002761
Daniel Dunbard931a872009-02-02 22:03:45 +00002762RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00002763 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00002764 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002765 const CallArgList &CallArgs,
David Chisnall9eecafa2010-05-01 11:15:56 +00002766 const Decl *TargetDecl,
David Chisnallff5f88c2010-05-02 13:41:58 +00002767 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00002768 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00002769
2770 // Handle struct-return functions by passing a pointer to the
2771 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00002772 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002773 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002774
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002775 llvm::FunctionType *IRFuncTy =
2776 cast<llvm::FunctionType>(
2777 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00002778
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002779 // If we're using inalloca, insert the allocation after the stack save.
2780 // FIXME: Do this earlier rather than hacking it in here!
Craig Topper8a13c412014-05-21 05:09:00 +00002781 llvm::Value *ArgMemory = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002782 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
Reid Kleckner9df1d972014-04-10 01:40:15 +00002783 llvm::Instruction *IP = CallArgs.getStackBase();
2784 llvm::AllocaInst *AI;
2785 if (IP) {
2786 IP = IP->getNextNode();
2787 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
2788 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00002789 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00002790 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002791 AI->setUsedWithInAlloca(true);
2792 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
2793 ArgMemory = AI;
2794 }
2795
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002796 ClangToLLVMArgMapping IRFunctionArgs(CGM, CallInfo);
2797 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
2798
Chris Lattner4ca97c32009-06-13 00:26:38 +00002799 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00002800 // alloca to hold the result, unless one is given to us.
Craig Topper8a13c412014-05-21 05:09:00 +00002801 llvm::Value *SRetPtr = nullptr;
Reid Kleckner37abaca2014-05-09 22:46:15 +00002802 if (RetAI.isIndirect() || RetAI.isInAlloca()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002803 SRetPtr = ReturnValue.getValue();
2804 if (!SRetPtr)
2805 SRetPtr = CreateMemTemp(RetTy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002806 if (IRFunctionArgs.hasSRetArg()) {
2807 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002808 } else {
2809 llvm::Value *Addr =
2810 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
2811 Builder.CreateStore(SRetPtr, Addr);
2812 }
Anders Carlsson17490832009-12-24 20:40:36 +00002813 }
Mike Stump11289f42009-09-09 15:08:12 +00002814
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002815 assert(CallInfo.arg_size() == CallArgs.size() &&
2816 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002817 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002818 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002819 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002820 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002821 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00002822 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002823
John McCall47fb9502013-03-07 21:37:08 +00002824 CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002825
2826 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002827 if (IRFunctionArgs.hasPaddingArg(ArgNo))
2828 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
2829 llvm::UndefValue::get(ArgInfo.getPaddingType());
2830
2831 unsigned FirstIRArg, NumIRArgs;
2832 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002833
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002834 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002835 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002836 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002837 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2838 if (RV.isAggregate()) {
2839 // Replace the placeholder with the appropriate argument slot GEP.
2840 llvm::Instruction *Placeholder =
2841 cast<llvm::Instruction>(RV.getAggregateAddr());
2842 CGBuilderTy::InsertPoint IP = Builder.saveIP();
2843 Builder.SetInsertPoint(Placeholder);
2844 llvm::Value *Addr = Builder.CreateStructGEP(
2845 ArgMemory, ArgInfo.getInAllocaFieldIndex());
2846 Builder.restoreIP(IP);
2847 deferPlaceholderReplacement(Placeholder, Addr);
2848 } else {
2849 // Store the RValue into the argument struct.
2850 llvm::Value *Addr =
2851 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
David Majnemer32b57b02014-03-31 16:12:47 +00002852 unsigned AS = Addr->getType()->getPointerAddressSpace();
2853 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
2854 // There are some cases where a trivial bitcast is not avoidable. The
2855 // definition of a type later in a translation unit may change it's type
2856 // from {}* to (%struct.foo*)*.
2857 if (Addr->getType() != MemType)
2858 Addr = Builder.CreateBitCast(Addr, MemType);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002859 LValue argLV = MakeAddrLValue(Addr, I->Ty, TypeAlign);
2860 EmitInitStoreOfNonAggregate(*this, RV, argLV);
2861 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002862 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002863 }
2864
Daniel Dunbar03816342010-08-21 02:24:36 +00002865 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002866 assert(NumIRArgs == 1);
Daniel Dunbar747865a2009-02-05 09:16:39 +00002867 if (RV.isScalar() || RV.isComplex()) {
2868 // Make a temporary alloca to pass the argument.
Eli Friedman7e68c882011-06-15 18:26:32 +00002869 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2870 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
2871 AI->setAlignment(ArgInfo.getIndirectAlign());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002872 IRCallArgs[FirstIRArg] = AI;
John McCall47fb9502013-03-07 21:37:08 +00002873
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002874 LValue argLV = MakeAddrLValue(AI, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002875 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar747865a2009-02-05 09:16:39 +00002876 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002877 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00002878 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002879 // 1. If the argument is not byval, and we are required to copy the
2880 // source. (This case doesn't occur on any common architecture.)
2881 // 2. If the argument is byval, RV is not sufficiently aligned, and
2882 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00002883 // 3. If the argument is byval, but RV is located in an address space
2884 // different than that of the argument (0).
Eli Friedmanf7456192011-06-15 22:09:18 +00002885 llvm::Value *Addr = RV.getAggregateAddr();
2886 unsigned Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002887 const llvm::DataLayout *TD = &CGM.getDataLayout();
Guy Benyei3832bfd2013-03-10 12:59:00 +00002888 const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002889 const unsigned ArgAddrSpace =
2890 (FirstIRArg < IRFuncTy->getNumParams()
2891 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
2892 : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00002893 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall47fb9502013-03-07 21:37:08 +00002894 (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
Guy Benyei3832bfd2013-03-10 12:59:00 +00002895 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align) ||
2896 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002897 // Create an aligned temporary, and copy to it.
Eli Friedmanf7456192011-06-15 22:09:18 +00002898 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2899 if (Align > AI->getAlignment())
2900 AI->setAlignment(Align);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002901 IRCallArgs[FirstIRArg] = AI;
Chad Rosier615ed1a2012-03-29 17:37:10 +00002902 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002903 } else {
2904 // Skip the extra memcpy call.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002905 IRCallArgs[FirstIRArg] = Addr;
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002906 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002907 }
2908 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002909 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002910
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002911 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002912 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002913 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002914
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002915 case ABIArgInfo::Extend:
2916 case ABIArgInfo::Direct: {
2917 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002918 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
2919 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002920 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002921 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002922 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002923 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002924 else
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002925 V = Builder.CreateLoad(RV.getAggregateAddr());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002926
Chris Lattner3ce86682011-07-12 04:53:39 +00002927 // If the argument doesn't match, perform a bitcast to coerce it. This
2928 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002929 if (FirstIRArg < IRFuncTy->getNumParams() &&
2930 V->getType() != IRFuncTy->getParamType(FirstIRArg))
2931 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
2932 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002933 break;
2934 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002935
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002936 // FIXME: Avoid the conversion through memory if possible.
2937 llvm::Value *SrcPtr;
John McCall47fb9502013-03-07 21:37:08 +00002938 if (RV.isScalar() || RV.isComplex()) {
Eli Friedmanf4258eb2011-05-02 18:05:27 +00002939 SrcPtr = CreateMemTemp(I->Ty, "coerce");
John McCall47fb9502013-03-07 21:37:08 +00002940 LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002941 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Mike Stump11289f42009-09-09 15:08:12 +00002942 } else
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002943 SrcPtr = RV.getAggregateAddr();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002944
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002945 // If the value is offset in memory, apply the offset now.
2946 if (unsigned Offs = ArgInfo.getDirectOffset()) {
2947 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
2948 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002949 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002950 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
2951
2952 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002953
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002954 // Fast-isel and the optimizer generally like scalar values better than
2955 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00002956 llvm::StructType *STy =
2957 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002958 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
Chandler Carrutha6399a52012-10-10 11:29:08 +00002959 llvm::Type *SrcTy =
2960 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
2961 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
2962 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
2963
2964 // If the source type is smaller than the destination type of the
2965 // coerce-to logic, copy the source value into a temp alloca the size
2966 // of the destination type to allow loading all of it. The bits past
2967 // the source value are left undef.
2968 if (SrcSize < DstSize) {
2969 llvm::AllocaInst *TempAlloca
2970 = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
2971 Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
2972 SrcPtr = TempAlloca;
2973 } else {
2974 SrcPtr = Builder.CreateBitCast(SrcPtr,
2975 llvm::PointerType::getUnqual(STy));
2976 }
2977
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002978 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00002979 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2980 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerff941a62010-07-28 18:24:28 +00002981 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
2982 // We don't know what we're loading from.
2983 LI->setAlignment(1);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002984 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00002985 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00002986 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00002987 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002988 assert(NumIRArgs == 1);
2989 IRCallArgs[FirstIRArg] =
2990 CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00002991 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002992
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002993 break;
2994 }
2995
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002996 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002997 unsigned IRArgPos = FirstIRArg;
2998 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
2999 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003000 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003001 }
3002 }
Mike Stump11289f42009-09-09 15:08:12 +00003003
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003004 if (ArgMemory) {
3005 llvm::Value *Arg = ArgMemory;
Reid Klecknerafba553e2014-07-08 02:24:27 +00003006 if (CallInfo.isVariadic()) {
3007 // When passing non-POD arguments by value to variadic functions, we will
3008 // end up with a variadic prototype and an inalloca call site. In such
3009 // cases, we can't do any parameter mismatch checks. Give up and bitcast
3010 // the callee.
3011 unsigned CalleeAS =
3012 cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
3013 Callee = Builder.CreateBitCast(
3014 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
3015 } else {
3016 llvm::Type *LastParamTy =
3017 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
3018 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003019#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00003020 // Assert that these structs have equivalent element types.
3021 llvm::StructType *FullTy = CallInfo.getArgStruct();
3022 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3023 cast<llvm::PointerType>(LastParamTy)->getElementType());
3024 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3025 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3026 DE = DeclaredTy->element_end(),
3027 FI = FullTy->element_begin();
3028 DI != DE; ++DI, ++FI)
3029 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003030#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00003031 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3032 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003033 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003034 assert(IRFunctionArgs.hasInallocaArg());
3035 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003036 }
3037
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003038 if (!CallArgs.getCleanupsToDeactivate().empty())
3039 deactivateArgCleanupsBeforeCall(*this, CallArgs);
3040
Chris Lattner4ca97c32009-06-13 00:26:38 +00003041 // If the callee is a bitcast of a function to a varargs pointer to function
3042 // type, check to see if we can remove the bitcast. This handles some cases
3043 // with unprototyped functions.
3044 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
3045 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003046 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
3047 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00003048 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00003049 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00003050
Chris Lattner4ca97c32009-06-13 00:26:38 +00003051 if (CE->getOpcode() == llvm::Instruction::BitCast &&
3052 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00003053 ActualFT->getNumParams() == CurFT->getNumParams() &&
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003054 ActualFT->getNumParams() == IRCallArgs.size() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00003055 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00003056 bool ArgsMatch = true;
3057 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
3058 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
3059 ArgsMatch = false;
3060 break;
3061 }
Mike Stump11289f42009-09-09 15:08:12 +00003062
Chris Lattner4ca97c32009-06-13 00:26:38 +00003063 // Strip the cast if we can get away with it. This is a nice cleanup,
3064 // but also allows us to inline the function at -O0 if it is marked
3065 // always_inline.
3066 if (ArgsMatch)
3067 Callee = CalleeF;
3068 }
3069 }
Mike Stump11289f42009-09-09 15:08:12 +00003070
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003071 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
3072 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
3073 // Inalloca argument can have different type.
3074 if (IRFunctionArgs.hasInallocaArg() &&
3075 i == IRFunctionArgs.getInallocaArgNo())
3076 continue;
3077 if (i < IRFuncTy->getNumParams())
3078 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
3079 }
3080
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003081 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00003082 CodeGen::AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003083 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
3084 CallingConv, true);
Bill Wendling3087d022012-12-07 23:17:26 +00003085 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003086 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00003087
Craig Topper8a13c412014-05-21 05:09:00 +00003088 llvm::BasicBlock *InvokeDest = nullptr;
Bill Wendling5e85be42012-12-30 10:32:17 +00003089 if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
3090 llvm::Attribute::NoUnwind))
John McCallbd309292010-07-06 01:34:17 +00003091 InvokeDest = getInvokeDest();
3092
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003093 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00003094 if (!InvokeDest) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003095 CS = Builder.CreateCall(Callee, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003096 } else {
3097 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003098 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003099 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003100 }
Chris Lattnere70a0072010-06-29 16:40:28 +00003101 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00003102 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003103
Peter Collingbourne41af7c22014-05-20 17:12:51 +00003104 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
3105 !CS.hasFnAttr(llvm::Attribute::NoInline))
3106 Attrs =
3107 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3108 llvm::Attribute::AlwaysInline);
3109
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003110 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003111 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003112
Dan Gohman515a60d2012-02-16 00:57:37 +00003113 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3114 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003115 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003116 AddObjCARCExceptionMetadata(CS.getInstruction());
3117
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003118 // If the call doesn't return, finish the basic block and clear the
3119 // insertion point; this allows the rest of IRgen to discard
3120 // unreachable code.
3121 if (CS.doesNotReturn()) {
3122 Builder.CreateUnreachable();
3123 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003124
Mike Stump18bb9282009-05-16 07:57:57 +00003125 // FIXME: For now, emit a dummy basic block because expr emitters in
3126 // generally are not ready to handle emitting expressions at unreachable
3127 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003128 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003129
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003130 // Return a reasonable RValue.
3131 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00003132 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003133
3134 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00003135 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00003136 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003137
John McCall31168b02011-06-15 23:02:42 +00003138 // Emit any writebacks immediately. Arguably this should happen
3139 // after any return-value munging.
3140 if (CallArgs.hasWritebacks())
3141 emitWritebacks(*this, CallArgs);
3142
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003143 // The stack cleanup for inalloca arguments has to run out of the normal
3144 // lexical order, so deactivate it and run it manually here.
3145 CallArgs.freeArgumentMemory(*this);
3146
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003147 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003148 case ABIArgInfo::InAlloca:
John McCall47fb9502013-03-07 21:37:08 +00003149 case ABIArgInfo::Indirect:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003150 return convertTempToRValue(SRetPtr, RetTy, SourceLocation());
Daniel Dunbard3674e62008-09-11 01:48:57 +00003151
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003152 case ABIArgInfo::Ignore:
Daniel Dunbar01362822009-02-03 06:30:17 +00003153 // If we are ignoring an argument that had a result, make sure to
3154 // construct the appropriate return value for our caller.
Daniel Dunbarc79407f2009-02-05 07:09:07 +00003155 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003156
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003157 case ABIArgInfo::Extend:
3158 case ABIArgInfo::Direct: {
Chris Lattner3517f142011-07-13 03:59:32 +00003159 llvm::Type *RetIRTy = ConvertType(RetTy);
3160 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
John McCall47fb9502013-03-07 21:37:08 +00003161 switch (getEvaluationKind(RetTy)) {
3162 case TEK_Complex: {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003163 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
3164 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
3165 return RValue::getComplex(std::make_pair(Real, Imag));
3166 }
John McCall47fb9502013-03-07 21:37:08 +00003167 case TEK_Aggregate: {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003168 llvm::Value *DestPtr = ReturnValue.getValue();
3169 bool DestIsVolatile = ReturnValue.isVolatile();
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003170
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003171 if (!DestPtr) {
3172 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
3173 DestIsVolatile = false;
3174 }
Eli Friedmanaf9b3252011-05-17 21:08:01 +00003175 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003176 return RValue::getAggregate(DestPtr);
3177 }
John McCall47fb9502013-03-07 21:37:08 +00003178 case TEK_Scalar: {
3179 // If the argument doesn't match, perform a bitcast to coerce it. This
3180 // can happen due to trivial type mismatches.
3181 llvm::Value *V = CI;
3182 if (V->getType() != RetIRTy)
3183 V = Builder.CreateBitCast(V, RetIRTy);
3184 return RValue::get(V);
3185 }
3186 }
3187 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003188 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003189
Anders Carlsson17490832009-12-24 20:40:36 +00003190 llvm::Value *DestPtr = ReturnValue.getValue();
3191 bool DestIsVolatile = ReturnValue.isVolatile();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003192
Anders Carlsson17490832009-12-24 20:40:36 +00003193 if (!DestPtr) {
Daniel Dunbara7566f12010-02-09 02:48:28 +00003194 DestPtr = CreateMemTemp(RetTy, "coerce");
Anders Carlsson17490832009-12-24 20:40:36 +00003195 DestIsVolatile = false;
3196 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003197
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003198 // If the value is offset in memory, apply the offset now.
3199 llvm::Value *StorePtr = DestPtr;
3200 if (unsigned Offs = RetAI.getDirectOffset()) {
3201 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
3202 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003203 StorePtr = Builder.CreateBitCast(StorePtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003204 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
3205 }
3206 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003207
Nick Lewycky2d84e842013-10-02 02:29:49 +00003208 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Daniel Dunbar573884e2008-09-10 07:04:09 +00003209 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00003210
Daniel Dunbard3674e62008-09-11 01:48:57 +00003211 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00003212 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar613855c2008-09-09 23:27:19 +00003213 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003214
David Blaikie83d382b2011-09-23 05:06:16 +00003215 llvm_unreachable("Unhandled ABIArgInfo::Kind");
Daniel Dunbar613855c2008-09-09 23:27:19 +00003216}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00003217
3218/* VarArg handling */
3219
3220llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
3221 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
3222}