blob: 0f640ac24cd7b92d382abddc6bf5395d69f9e6bc [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 +0000184const CGFunctionInfo &
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000185CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
186 StructorType Type) {
187
John McCalla729c622012-02-17 03:33:10 +0000188 SmallVector<CanQualType, 16> argTypes;
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000189 argTypes.push_back(GetThisType(Context, MD->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000190
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000191 GlobalDecl GD;
192 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
193 GD = GlobalDecl(CD, toCXXCtorType(Type));
194 } else {
195 auto *DD = dyn_cast<CXXDestructorDecl>(MD);
196 GD = GlobalDecl(DD, toCXXDtorType(Type));
197 }
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000198
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000199 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
John McCall5d865c322010-08-31 07:33:07 +0000200
201 // Add the formal parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000202 for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
203 argTypes.push_back(FTP->getParamType(i));
John McCall5d865c322010-08-31 07:33:07 +0000204
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000205 TheCXXABI.buildStructorSignature(MD, Type, argTypes);
Reid Kleckner89077a12013-12-17 19:46:40 +0000206
207 RequiredArgs required =
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000208 (MD->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All);
Reid Kleckner89077a12013-12-17 19:46:40 +0000209
John McCall8dda7b22012-07-07 06:41:13 +0000210 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000211 CanQualType resultType =
212 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
Reid Kleckner4982b822014-01-31 22:54:50 +0000213 return arrangeLLVMFunctionInfo(resultType, true, argTypes, extInfo, required);
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000214}
215
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000216/// Arrange a call to a C++ method, passing the given arguments.
217const CGFunctionInfo &
218CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
219 const CXXConstructorDecl *D,
220 CXXCtorType CtorKind,
221 unsigned ExtraArgs) {
222 // FIXME: Kill copy.
223 SmallVector<CanQualType, 16> ArgTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000224 for (const auto &Arg : args)
225 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000226
227 CanQual<FunctionProtoType> FPT = GetFormalType(D);
228 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs);
229 GlobalDecl GD(D, CtorKind);
230 CanQualType ResultType =
231 TheCXXABI.HasThisReturn(GD) ? ArgTypes.front() : Context.VoidTy;
232
233 FunctionType::ExtInfo Info = FPT->getExtInfo();
234 return arrangeLLVMFunctionInfo(ResultType, true, ArgTypes, Info, Required);
235}
236
John McCalla729c622012-02-17 03:33:10 +0000237/// Arrange the argument and result information for the declaration or
238/// definition of the given function.
239const CGFunctionInfo &
240CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000241 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000242 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000243 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000244
John McCall2da83a32010-02-26 00:48:12 +0000245 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000246
John McCall2da83a32010-02-26 00:48:12 +0000247 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000248
249 // When declaring a function without a prototype, always use a
250 // non-variadic type.
251 if (isa<FunctionNoProtoType>(FTy)) {
252 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Reid Kleckner4982b822014-01-31 22:54:50 +0000253 return arrangeLLVMFunctionInfo(noProto->getReturnType(), false, None,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000254 noProto->getExtInfo(), RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000255 }
256
John McCall2da83a32010-02-26 00:48:12 +0000257 assert(isa<FunctionProtoType>(FTy));
John McCall8dda7b22012-07-07 06:41:13 +0000258 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>());
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000259}
260
John McCalla729c622012-02-17 03:33:10 +0000261/// Arrange the argument and result information for the declaration or
262/// definition of an Objective-C method.
263const CGFunctionInfo &
264CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
265 // It happens that this is the same as a call with no optional
266 // arguments, except also using the formal 'self' type.
267 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
268}
269
270/// Arrange the argument and result information for the function type
271/// through which to perform a send to the given Objective-C method,
272/// using the given receiver type. The receiver type is not always
273/// the 'self' type of the method or even an Objective-C pointer type.
274/// This is *not* the right method for actually performing such a
275/// message send, due to the possibility of optional arguments.
276const CGFunctionInfo &
277CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
278 QualType receiverType) {
279 SmallVector<CanQualType, 16> argTys;
280 argTys.push_back(Context.getCanonicalParamType(receiverType));
281 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000282 // FIXME: Kill copy?
Aaron Ballman43b68be2014-03-07 17:50:17 +0000283 for (const auto *I : MD->params()) {
284 argTys.push_back(Context.getCanonicalParamType(I->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000285 }
John McCall31168b02011-06-15 23:02:42 +0000286
287 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000288 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
289 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000290
David Blaikiebbafb8a2012-03-11 07:00:24 +0000291 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000292 MD->hasAttr<NSReturnsRetainedAttr>())
293 einfo = einfo.withProducesResult(true);
294
John McCalla729c622012-02-17 03:33:10 +0000295 RequiredArgs required =
296 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
297
Reid Kleckner4982b822014-01-31 22:54:50 +0000298 return arrangeLLVMFunctionInfo(GetReturnType(MD->getReturnType()), false,
299 argTys, einfo, required);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000300}
301
John McCalla729c622012-02-17 03:33:10 +0000302const CGFunctionInfo &
303CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000304 // FIXME: Do we need to handle ObjCMethodDecl?
305 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000306
Anders Carlsson6710c532010-02-06 02:44:09 +0000307 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000308 return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
Anders Carlsson6710c532010-02-06 02:44:09 +0000309
310 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000311 return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000312
John McCalla729c622012-02-17 03:33:10 +0000313 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000314}
315
Reid Klecknerc3473512014-08-29 21:43:29 +0000316/// Arrange a thunk that takes 'this' as the first parameter followed by
317/// varargs. Return a void pointer, regardless of the actual return type.
318/// The body of the thunk will end in a musttail call to a function of the
319/// correct type, and the caller will bitcast the function to the correct
320/// prototype.
321const CGFunctionInfo &
322CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) {
323 assert(MD->isVirtual() && "only virtual memptrs have thunks");
324 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
325 CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
326 return arrangeLLVMFunctionInfo(Context.VoidTy, false, ArgTys,
327 FTP->getExtInfo(), RequiredArgs(1));
328}
329
John McCallc818bbb2012-12-07 07:03:17 +0000330/// Arrange a call as unto a free function, except possibly with an
331/// additional number of formal parameters considered required.
332static const CGFunctionInfo &
333arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000334 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000335 const CallArgList &args,
336 const FunctionType *fnType,
337 unsigned numExtraRequiredArgs) {
338 assert(args.size() >= numExtraRequiredArgs);
339
340 // In most cases, there are no optional arguments.
341 RequiredArgs required = RequiredArgs::All;
342
343 // If we have a variadic prototype, the required arguments are the
344 // extra prefix plus the arguments in the prototype.
345 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
346 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000347 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000348
349 // If we don't have a prototype at all, but we're supposed to
350 // explicitly use the variadic convention for unprototyped calls,
351 // treat all of the arguments as required but preserve the nominal
352 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000353 } else if (CGM.getTargetCodeGenInfo()
354 .isNoProtoCallVariadic(args,
355 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000356 required = RequiredArgs(args.size());
357 }
358
Alp Toker314cc812014-01-25 16:55:45 +0000359 return CGT.arrangeFreeFunctionCall(fnType->getReturnType(), args,
John McCallc818bbb2012-12-07 07:03:17 +0000360 fnType->getExtInfo(), required);
361}
362
John McCalla729c622012-02-17 03:33:10 +0000363/// Figure out the rules for calling a function with the given formal
364/// type using the given arguments. The arguments are necessary
365/// because the function might be unprototyped, in which case it's
366/// target-dependent in crazy ways.
367const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000368CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
369 const FunctionType *fnType) {
Mark Lacey23455752013-10-10 20:57:00 +0000370 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 0);
John McCallc818bbb2012-12-07 07:03:17 +0000371}
John McCalla729c622012-02-17 03:33:10 +0000372
John McCallc818bbb2012-12-07 07:03:17 +0000373/// A block function call is essentially a free-function call with an
374/// extra implicit argument.
375const CGFunctionInfo &
376CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
377 const FunctionType *fnType) {
Mark Lacey23455752013-10-10 20:57:00 +0000378 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1);
John McCalla729c622012-02-17 03:33:10 +0000379}
380
381const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000382CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
383 const CallArgList &args,
384 FunctionType::ExtInfo info,
385 RequiredArgs required) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000386 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000387 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000388 for (const auto &Arg : args)
389 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner4982b822014-01-31 22:54:50 +0000390 return arrangeLLVMFunctionInfo(GetReturnType(resultType), false, argTypes,
391 info, required);
John McCall8dda7b22012-07-07 06:41:13 +0000392}
393
394/// Arrange a call to a C++ method, passing the given arguments.
395const CGFunctionInfo &
396CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
397 const FunctionProtoType *FPT,
398 RequiredArgs required) {
399 // FIXME: Kill copy.
400 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000401 for (const auto &Arg : args)
402 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
John McCall8dda7b22012-07-07 06:41:13 +0000403
404 FunctionType::ExtInfo info = FPT->getExtInfo();
Reid Kleckner4982b822014-01-31 22:54:50 +0000405 return arrangeLLVMFunctionInfo(GetReturnType(FPT->getReturnType()), true,
406 argTypes, info, required);
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000407}
408
Reid Kleckner4982b822014-01-31 22:54:50 +0000409const CGFunctionInfo &CodeGenTypes::arrangeFreeFunctionDeclaration(
410 QualType resultType, const FunctionArgList &args,
411 const FunctionType::ExtInfo &info, bool isVariadic) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000412 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000413 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000414 for (auto Arg : args)
415 argTypes.push_back(Context.getCanonicalParamType(Arg->getType()));
John McCalla729c622012-02-17 03:33:10 +0000416
417 RequiredArgs required =
418 (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
Reid Kleckner4982b822014-01-31 22:54:50 +0000419 return arrangeLLVMFunctionInfo(GetReturnType(resultType), false, argTypes, info,
John McCall8dda7b22012-07-07 06:41:13 +0000420 required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000421}
422
John McCalla729c622012-02-17 03:33:10 +0000423const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Reid Kleckner4982b822014-01-31 22:54:50 +0000424 return arrangeLLVMFunctionInfo(getContext().VoidTy, false, None,
John McCall8dda7b22012-07-07 06:41:13 +0000425 FunctionType::ExtInfo(), RequiredArgs::All);
John McCalla738c252011-03-09 04:27:21 +0000426}
427
John McCalla729c622012-02-17 03:33:10 +0000428/// Arrange the argument and result information for an abstract value
429/// of a given function type. This is the method which all of the
430/// above functions ultimately defer to.
431const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000432CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Reid Kleckner4982b822014-01-31 22:54:50 +0000433 bool IsInstanceMethod,
John McCall8dda7b22012-07-07 06:41:13 +0000434 ArrayRef<CanQualType> argTypes,
435 FunctionType::ExtInfo info,
436 RequiredArgs required) {
John McCall2da83a32010-02-26 00:48:12 +0000437#ifndef NDEBUG
John McCalla729c622012-02-17 03:33:10 +0000438 for (ArrayRef<CanQualType>::const_iterator
439 I = argTypes.begin(), E = argTypes.end(); I != E; ++I)
John McCall2da83a32010-02-26 00:48:12 +0000440 assert(I->isCanonicalAsParam());
441#endif
442
John McCalla729c622012-02-17 03:33:10 +0000443 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
John McCallab26cfa2010-02-05 21:31:56 +0000444
Daniel Dunbare0be8292009-02-03 00:07:12 +0000445 // Lookup or create unique function info.
446 llvm::FoldingSetNodeID ID;
Reid Kleckner4982b822014-01-31 22:54:50 +0000447 CGFunctionInfo::Profile(ID, IsInstanceMethod, info, required, resultType,
448 argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000449
Craig Topper8a13c412014-05-21 05:09:00 +0000450 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000451 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000452 if (FI)
453 return *FI;
454
John McCalla729c622012-02-17 03:33:10 +0000455 // Construct the function info. We co-allocate the ArgInfos.
Reid Kleckner4982b822014-01-31 22:54:50 +0000456 FI = CGFunctionInfo::create(CC, IsInstanceMethod, info, resultType, argTypes,
457 required);
John McCalla729c622012-02-17 03:33:10 +0000458 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000459
John McCalla729c622012-02-17 03:33:10 +0000460 bool inserted = FunctionsBeingProcessed.insert(FI); (void)inserted;
461 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000462
Daniel Dunbar313321e2009-02-03 05:31:23 +0000463 // Compute ABI information.
Chris Lattner22326a12010-07-29 02:31:05 +0000464 getABIInfo().computeInfo(*FI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000465
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000466 // Loop over all of the computed argument and return value info. If any of
467 // them are direct or extend without a specified coerce type, specify the
468 // default now.
John McCalla729c622012-02-17 03:33:10 +0000469 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000470 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000471 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000472
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000473 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000474 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000475 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000476
John McCalla729c622012-02-17 03:33:10 +0000477 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
478 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000479
Daniel Dunbare0be8292009-02-03 00:07:12 +0000480 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000481}
482
John McCalla729c622012-02-17 03:33:10 +0000483CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Reid Kleckner4982b822014-01-31 22:54:50 +0000484 bool IsInstanceMethod,
John McCalla729c622012-02-17 03:33:10 +0000485 const FunctionType::ExtInfo &info,
486 CanQualType resultType,
487 ArrayRef<CanQualType> argTypes,
488 RequiredArgs required) {
489 void *buffer = operator new(sizeof(CGFunctionInfo) +
490 sizeof(ArgInfo) * (argTypes.size() + 1));
491 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
492 FI->CallingConvention = llvmCC;
493 FI->EffectiveCallingConvention = llvmCC;
494 FI->ASTCallingConvention = info.getCC();
Reid Kleckner4982b822014-01-31 22:54:50 +0000495 FI->InstanceMethod = IsInstanceMethod;
John McCalla729c622012-02-17 03:33:10 +0000496 FI->NoReturn = info.getNoReturn();
497 FI->ReturnsRetained = info.getProducesResult();
498 FI->Required = required;
499 FI->HasRegParm = info.getHasRegParm();
500 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000501 FI->ArgStruct = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000502 FI->NumArgs = argTypes.size();
503 FI->getArgsBuffer()[0].type = resultType;
504 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
505 FI->getArgsBuffer()[i + 1].type = argTypes[i];
506 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000507}
508
509/***/
510
John McCall85dd2c52011-05-15 02:19:42 +0000511void CodeGenTypes::GetExpandedTypes(QualType type,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000512 SmallVectorImpl<llvm::Type*> &expandedTypes) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000513 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(type)) {
514 uint64_t NumElts = AT->getSize().getZExtValue();
515 for (uint64_t Elt = 0; Elt < NumElts; ++Elt)
516 GetExpandedTypes(AT->getElementType(), expandedTypes);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000517 } else if (const RecordType *RT = type->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000518 const RecordDecl *RD = RT->getDecl();
519 assert(!RD->hasFlexibleArrayMember() &&
520 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000521 if (RD->isUnion()) {
522 // Unions can be here only in degenerative cases - all the fields are same
523 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000524 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000525 CharUnits UnionSize = CharUnits::Zero();
526
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000527 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000528 assert(!FD->isBitField() &&
529 "Cannot expand structure with bit-field members.");
530 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
531 if (UnionSize < FieldSize) {
532 UnionSize = FieldSize;
533 LargestFD = FD;
534 }
535 }
536 if (LargestFD)
537 GetExpandedTypes(LargestFD->getType(), expandedTypes);
538 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000539 for (const auto *I : RD->fields()) {
540 assert(!I->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000541 "Cannot expand structure with bit-field members.");
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000542 GetExpandedTypes(I->getType(), expandedTypes);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000543 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000544 }
545 } else if (const ComplexType *CT = type->getAs<ComplexType>()) {
546 llvm::Type *EltTy = ConvertType(CT->getElementType());
547 expandedTypes.push_back(EltTy);
548 expandedTypes.push_back(EltTy);
549 } else
550 expandedTypes.push_back(ConvertType(type));
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000551}
552
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000553void CodeGenFunction::ExpandTypeFromArgs(
554 QualType Ty, LValue LV, SmallVectorImpl<llvm::Argument *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000555 assert(LV.isSimple() &&
556 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000557
Bob Wilsone826a2a2011-08-03 05:58:22 +0000558 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
559 unsigned NumElts = AT->getSize().getZExtValue();
560 QualType EltTy = AT->getElementType();
561 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
Eli Friedman7f1ff602012-04-16 03:54:45 +0000562 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, Elt);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000563 LValue LV = MakeAddrLValue(EltAddr, EltTy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000564 ExpandTypeFromArgs(EltTy, LV, AI);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000565 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000566 return;
567 }
568 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000569 RecordDecl *RD = RT->getDecl();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000570 if (RD->isUnion()) {
571 // Unions can be here only in degenerative cases - all the fields are same
572 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000573 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000574 CharUnits UnionSize = CharUnits::Zero();
Bob Wilsone826a2a2011-08-03 05:58:22 +0000575
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000576 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000577 assert(!FD->isBitField() &&
578 "Cannot expand structure with bit-field members.");
579 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
580 if (UnionSize < FieldSize) {
581 UnionSize = FieldSize;
582 LargestFD = FD;
583 }
584 }
585 if (LargestFD) {
586 // FIXME: What are the right qualifiers here?
Eli Friedman7f1ff602012-04-16 03:54:45 +0000587 LValue SubLV = EmitLValueForField(LV, LargestFD);
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000588 ExpandTypeFromArgs(LargestFD->getType(), SubLV, AI);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000589 }
590 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000591 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000592 QualType FT = FD->getType();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000593 // FIXME: What are the right qualifiers here?
Eli Friedman7f1ff602012-04-16 03:54:45 +0000594 LValue SubLV = EmitLValueForField(LV, FD);
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000595 ExpandTypeFromArgs(FT, SubLV, AI);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000596 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000597 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000598 return;
599 }
600 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000601 QualType EltTy = CT->getElementType();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000602 llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real");
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000603 EmitStoreThroughLValue(RValue::get(*AI++), MakeAddrLValue(RealAddr, EltTy));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000604 llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag");
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000605 EmitStoreThroughLValue(RValue::get(*AI++), MakeAddrLValue(ImagAddr, EltTy));
606 return;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000607 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000608 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000609}
610
Chris Lattner895c52b2010-06-27 06:04:18 +0000611/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +0000612/// accessing some number of bytes out of it, try to gep into the struct to get
613/// at its inner goodness. Dive as deep as possible without entering an element
614/// with an in-memory size smaller than DstSize.
615static llvm::Value *
Chris Lattner895c52b2010-06-27 06:04:18 +0000616EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000617 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +0000618 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +0000619 // We can't dive into a zero-element struct.
620 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000621
Chris Lattner2192fe52011-07-18 04:24:23 +0000622 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000623
Chris Lattner1cd66982010-06-27 05:56:15 +0000624 // 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 +0000625 // first element is the same size as the whole struct, we can enter it. The
626 // comparison must be made on the store size and not the alloca size. Using
627 // the alloca size may overstate the size of the load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000628 uint64_t FirstEltSize =
James Molloy90d61012014-08-29 10:17:52 +0000629 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000630 if (FirstEltSize < DstSize &&
James Molloy90d61012014-08-29 10:17:52 +0000631 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +0000632 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000633
Chris Lattner1cd66982010-06-27 05:56:15 +0000634 // GEP into the first element.
635 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000636
Chris Lattner1cd66982010-06-27 05:56:15 +0000637 // If the first element is a struct, recurse.
Chris Lattner2192fe52011-07-18 04:24:23 +0000638 llvm::Type *SrcTy =
Chris Lattner1cd66982010-06-27 05:56:15 +0000639 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000640 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +0000641 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000642
643 return SrcPtr;
644}
645
Chris Lattner055097f2010-06-27 06:26:04 +0000646/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
647/// are either integers or pointers. This does a truncation of the value if it
648/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000649///
650/// This behaves as if the value were coerced through memory, so on big-endian
651/// targets the high bits are preserved in a truncation, while little-endian
652/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +0000653static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +0000654 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +0000655 CodeGenFunction &CGF) {
656 if (Val->getType() == Ty)
657 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000658
Chris Lattner055097f2010-06-27 06:26:04 +0000659 if (isa<llvm::PointerType>(Val->getType())) {
660 // If this is Pointer->Pointer avoid conversion to and from int.
661 if (isa<llvm::PointerType>(Ty))
662 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000663
Chris Lattner055097f2010-06-27 06:26:04 +0000664 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +0000665 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +0000666 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000667
Chris Lattner2192fe52011-07-18 04:24:23 +0000668 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +0000669 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +0000670 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000671
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000672 if (Val->getType() != DestIntTy) {
673 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
674 if (DL.isBigEndian()) {
675 // Preserve the high bits on big-endian targets.
676 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +0000677 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
678 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
679
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000680 if (SrcSize > DstSize) {
681 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
682 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
683 } else {
684 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
685 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
686 }
687 } else {
688 // Little-endian targets preserve the low bits. No shifts required.
689 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
690 }
691 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000692
Chris Lattner055097f2010-06-27 06:26:04 +0000693 if (isa<llvm::PointerType>(Ty))
694 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
695 return Val;
696}
697
Chris Lattner1cd66982010-06-27 05:56:15 +0000698
699
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000700/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
701/// a pointer to an object of type \arg Ty.
702///
703/// This safely handles the case when the src type is smaller than the
704/// destination type; in this situation the values of bits which not
705/// present in the src are undefined.
706static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000707 llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000708 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000709 llvm::Type *SrcTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000710 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000711
Chris Lattnerd200eda2010-06-28 22:51:39 +0000712 // If SrcTy and Ty are the same, just do a load.
713 if (SrcTy == Ty)
714 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000715
Micah Villmowdd31ca12012-10-08 16:25:52 +0000716 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000717
Chris Lattner2192fe52011-07-18 04:24:23 +0000718 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000719 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000720 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
721 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000722
Micah Villmowdd31ca12012-10-08 16:25:52 +0000723 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000724
Chris Lattner055097f2010-06-27 06:26:04 +0000725 // If the source and destination are integer or pointer types, just do an
726 // extension or truncation to the desired type.
727 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
728 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
729 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
730 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
731 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000732
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000733 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000734 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +0000735 // Generally SrcSize is never greater than DstSize, since this means we are
736 // losing bits. However, this can happen in cases where the structure has
737 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000738 //
Mike Stump18bb9282009-05-16 07:57:57 +0000739 // FIXME: Assert that we aren't truncating non-padding bits when have access
740 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000741 llvm::Value *Casted =
742 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000743 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
744 // FIXME: Use better alignment / avoid requiring aligned load.
745 Load->setAlignment(1);
746 return Load;
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000747 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000748
Chris Lattner3fcc7902010-06-27 01:06:27 +0000749 // Otherwise do coercion through memory. This is stupid, but
750 // simple.
751 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
Manman Ren84b921f2012-11-28 22:08:52 +0000752 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
753 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
754 llvm::Value *SrcCasted = CGF.Builder.CreateBitCast(SrcPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000755 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000756 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
757 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
758 1, false);
Chris Lattner3fcc7902010-06-27 01:06:27 +0000759 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000760}
761
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000762// Function to store a first-class aggregate into memory. We prefer to
763// store the elements rather than the aggregate to be more friendly to
764// fast-isel.
765// FIXME: Do we need to recurse here?
766static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
767 llvm::Value *DestPtr, bool DestIsVolatile,
768 bool LowAlignment) {
769 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +0000770 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000771 dyn_cast<llvm::StructType>(Val->getType())) {
772 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
773 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
774 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
775 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
776 DestIsVolatile);
777 if (LowAlignment)
778 SI->setAlignment(1);
779 }
780 } else {
Bill Wendlingf6af30f2012-03-16 21:45:12 +0000781 llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
782 if (LowAlignment)
783 SI->setAlignment(1);
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000784 }
785}
786
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000787/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
788/// where the source and destination may have different types.
789///
790/// This safely handles the case when the src type is larger than the
791/// destination type; the upper bits of the src will be lost.
792static void CreateCoercedStore(llvm::Value *Src,
793 llvm::Value *DstPtr,
Anders Carlsson17490832009-12-24 20:40:36 +0000794 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000795 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000796 llvm::Type *SrcTy = Src->getType();
797 llvm::Type *DstTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000798 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +0000799 if (SrcTy == DstTy) {
800 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
801 return;
802 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000803
Micah Villmowdd31ca12012-10-08 16:25:52 +0000804 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000805
Chris Lattner2192fe52011-07-18 04:24:23 +0000806 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000807 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
808 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
809 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000810
Chris Lattner055097f2010-06-27 06:26:04 +0000811 // If the source and destination are integer or pointer types, just do an
812 // extension or truncation to the desired type.
813 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
814 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
815 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
816 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
817 return;
818 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000819
Micah Villmowdd31ca12012-10-08 16:25:52 +0000820 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000821
Daniel Dunbar313321e2009-02-03 05:31:23 +0000822 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000823 if (SrcSize <= DstSize) {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000824 llvm::Value *Casted =
825 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000826 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000827 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000828 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000829 // Otherwise do coercion through memory. This is stupid, but
830 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000831
832 // Generally SrcSize is never greater than DstSize, since this means we are
833 // losing bits. However, this can happen in cases where the structure has
834 // additional padding, for example due to a user specified alignment.
835 //
836 // FIXME: Assert that we aren't truncating non-padding bits when have access
837 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000838 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
839 CGF.Builder.CreateStore(Src, Tmp);
Manman Ren84b921f2012-11-28 22:08:52 +0000840 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
841 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
842 llvm::Value *DstCasted = CGF.Builder.CreateBitCast(DstPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000843 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000844 CGF.Builder.CreateMemCpy(DstCasted, Casted,
845 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
846 1, false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000847 }
848}
849
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000850/***/
851
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000852bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000853 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +0000854}
855
Tim Northovere77cc392014-03-29 13:28:05 +0000856bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
857 return ReturnTypeUsesSRet(FI) &&
858 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
859}
860
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000861bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
862 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
863 switch (BT->getKind()) {
864 default:
865 return false;
866 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +0000867 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000868 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +0000869 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000870 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +0000871 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000872 }
873 }
874
875 return false;
876}
877
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000878bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
879 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
880 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
881 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +0000882 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000883 }
884 }
885
886 return false;
887}
888
Chris Lattnera5f58b02011-07-09 17:41:47 +0000889llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +0000890 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
891 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +0000892}
893
Chris Lattnera5f58b02011-07-09 17:41:47 +0000894llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +0000895CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000896
897 bool Inserted = FunctionsBeingProcessed.insert(&FI); (void)Inserted;
898 assert(Inserted && "Recursively being processed?");
899
Reid Kleckner37abaca2014-05-09 22:46:15 +0000900 bool SwapThisWithSRet = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000901 SmallVector<llvm::Type*, 8> argTypes;
Craig Topper8a13c412014-05-21 05:09:00 +0000902 llvm::Type *resultType = nullptr;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000903
John McCall85dd2c52011-05-15 02:19:42 +0000904 const ABIArgInfo &retAI = FI.getReturnInfo();
905 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +0000906 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +0000907 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +0000908
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000909 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +0000910 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +0000911 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +0000912 break;
913
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000914 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +0000915 if (retAI.getInAllocaSRet()) {
916 // sret things on win32 aren't void, they return the sret pointer.
917 QualType ret = FI.getReturnType();
918 llvm::Type *ty = ConvertType(ret);
919 unsigned addressSpace = Context.getTargetAddressSpace(ret);
920 resultType = llvm::PointerType::get(ty, addressSpace);
921 } else {
922 resultType = llvm::Type::getVoidTy(getLLVMContext());
923 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000924 break;
925
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000926 case ABIArgInfo::Indirect: {
John McCall85dd2c52011-05-15 02:19:42 +0000927 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
928 resultType = llvm::Type::getVoidTy(getLLVMContext());
929
930 QualType ret = FI.getReturnType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000931 llvm::Type *ty = ConvertType(ret);
John McCall85dd2c52011-05-15 02:19:42 +0000932 unsigned addressSpace = Context.getTargetAddressSpace(ret);
933 argTypes.push_back(llvm::PointerType::get(ty, addressSpace));
Reid Kleckner37abaca2014-05-09 22:46:15 +0000934
935 SwapThisWithSRet = retAI.isSRetAfterThis();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000936 break;
937 }
938
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000939 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +0000940 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000941 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000942 }
Mike Stump11289f42009-09-09 15:08:12 +0000943
John McCallc818bbb2012-12-07 07:03:17 +0000944 // Add in all of the required arguments.
945 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), ie;
946 if (FI.isVariadic()) {
947 ie = it + FI.getRequiredArgs().getNumRequiredArgs();
948 } else {
949 ie = FI.arg_end();
950 }
951 for (; it != ie; ++it) {
John McCall85dd2c52011-05-15 02:19:42 +0000952 const ABIArgInfo &argAI = it->info;
Mike Stump11289f42009-09-09 15:08:12 +0000953
Rafael Espindolafad28de2012-10-24 01:59:00 +0000954 // Insert a padding type to ensure proper alignment.
955 if (llvm::Type *PaddingType = argAI.getPaddingType())
956 argTypes.push_back(PaddingType);
957
John McCall85dd2c52011-05-15 02:19:42 +0000958 switch (argAI.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000959 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000960 case ABIArgInfo::InAlloca:
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000961 break;
962
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000963 case ABIArgInfo::Indirect: {
964 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +0000965 llvm::Type *LTy = ConvertTypeForMem(it->type);
John McCall85dd2c52011-05-15 02:19:42 +0000966 argTypes.push_back(LTy->getPointerTo());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000967 break;
968 }
969
970 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +0000971 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +0000972 // Fast-isel and the optimizer generally like scalar values better than
973 // FCAs, so we flatten them if this is safe to do for this argument.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000974 llvm::Type *argType = argAI.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +0000975 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +0000976 if (st && argAI.isDirect() && argAI.getCanBeFlattened()) {
John McCall85dd2c52011-05-15 02:19:42 +0000977 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
978 argTypes.push_back(st->getElementType(i));
Chris Lattner3dd716c2010-06-28 23:44:11 +0000979 } else {
John McCall85dd2c52011-05-15 02:19:42 +0000980 argTypes.push_back(argType);
Chris Lattner3dd716c2010-06-28 23:44:11 +0000981 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +0000982 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +0000983 }
Mike Stump11289f42009-09-09 15:08:12 +0000984
Daniel Dunbard3674e62008-09-11 01:48:57 +0000985 case ABIArgInfo::Expand:
Chris Lattnera5f58b02011-07-09 17:41:47 +0000986 GetExpandedTypes(it->type, argTypes);
Daniel Dunbard3674e62008-09-11 01:48:57 +0000987 break;
988 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000989 }
990
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000991 // Add the inalloca struct as the last parameter type.
992 if (llvm::StructType *ArgStruct = FI.getArgStruct())
993 argTypes.push_back(ArgStruct->getPointerTo());
994
Reid Kleckner37abaca2014-05-09 22:46:15 +0000995 if (SwapThisWithSRet)
996 std::swap(argTypes[0], argTypes[1]);
997
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000998 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
999 assert(Erased && "Not in set?");
1000
John McCalla729c622012-02-17 03:33:10 +00001001 return llvm::FunctionType::get(resultType, argTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001002}
1003
Chris Lattner2192fe52011-07-18 04:24:23 +00001004llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001005 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001006 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001007
Chris Lattner8806e322011-07-10 00:18:59 +00001008 if (!isFuncTypeConvertible(FPT))
1009 return llvm::StructType::get(getLLVMContext());
1010
1011 const CGFunctionInfo *Info;
1012 if (isa<CXXDestructorDecl>(MD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001013 Info =
1014 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
Chris Lattner8806e322011-07-10 00:18:59 +00001015 else
John McCalla729c622012-02-17 03:33:10 +00001016 Info = &arrangeCXXMethodDeclaration(MD);
1017 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001018}
1019
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001020namespace {
1021
1022/// Encapsulates information about the way function arguments from
1023/// CGFunctionInfo should be passed to actual LLVM IR function.
1024class ClangToLLVMArgMapping {
1025 static const unsigned InvalidIndex = ~0U;
1026 unsigned InallocaArgNo;
1027 unsigned SRetArgNo;
1028 unsigned TotalIRArgs;
1029
1030 /// Arguments of LLVM IR function corresponding to single Clang argument.
1031 struct IRArgs {
1032 unsigned PaddingArgIndex;
1033 // Argument is expanded to IR arguments at positions
1034 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1035 unsigned FirstArgIndex;
1036 unsigned NumberOfArgs;
1037
1038 IRArgs()
1039 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1040 NumberOfArgs(0) {}
1041 };
1042
1043 SmallVector<IRArgs, 8> ArgInfo;
1044
1045public:
1046 ClangToLLVMArgMapping(CodeGenModule &CGM, const CGFunctionInfo &FI)
1047 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1048 ArgInfo(FI.arg_size()) {
1049 construct(CGM, FI);
1050 }
1051
1052 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1053 unsigned getInallocaArgNo() const {
1054 assert(hasInallocaArg());
1055 return InallocaArgNo;
1056 }
1057
1058 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1059 unsigned getSRetArgNo() const {
1060 assert(hasSRetArg());
1061 return SRetArgNo;
1062 }
1063
1064 unsigned totalIRArgs() const { return TotalIRArgs; }
1065
1066 bool hasPaddingArg(unsigned ArgNo) const {
1067 assert(ArgNo < ArgInfo.size());
1068 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1069 }
1070 unsigned getPaddingArgNo(unsigned ArgNo) const {
1071 assert(hasPaddingArg(ArgNo));
1072 return ArgInfo[ArgNo].PaddingArgIndex;
1073 }
1074
1075 /// Returns index of first IR argument corresponding to ArgNo, and their
1076 /// quantity.
1077 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1078 assert(ArgNo < ArgInfo.size());
1079 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1080 ArgInfo[ArgNo].NumberOfArgs);
1081 }
1082
1083private:
1084 void construct(CodeGenModule &CGM, const CGFunctionInfo &FI);
1085};
1086
1087void ClangToLLVMArgMapping::construct(CodeGenModule &CGM,
1088 const CGFunctionInfo &FI) {
1089 unsigned IRArgNo = 0;
1090 bool SwapThisWithSRet = false;
1091 const ABIArgInfo &RetAI = FI.getReturnInfo();
1092
1093 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1094 SwapThisWithSRet = RetAI.isSRetAfterThis();
1095 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1096 }
1097
1098 unsigned ArgNo = 0;
1099 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1100 E = FI.arg_end();
1101 I != E; ++I, ++ArgNo) {
1102 QualType ArgType = I->type;
1103 const ABIArgInfo &AI = I->info;
1104 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1105 auto &IRArgs = ArgInfo[ArgNo];
1106
1107 if (AI.getPaddingType())
1108 IRArgs.PaddingArgIndex = IRArgNo++;
1109
1110 switch (AI.getKind()) {
1111 case ABIArgInfo::Extend:
1112 case ABIArgInfo::Direct: {
1113 // FIXME: handle sseregparm someday...
1114 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001115 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001116 IRArgs.NumberOfArgs = STy->getNumElements();
1117 } else {
1118 IRArgs.NumberOfArgs = 1;
1119 }
1120 break;
1121 }
1122 case ABIArgInfo::Indirect:
1123 IRArgs.NumberOfArgs = 1;
1124 break;
1125 case ABIArgInfo::Ignore:
1126 case ABIArgInfo::InAlloca:
1127 // ignore and inalloca doesn't have matching LLVM parameters.
1128 IRArgs.NumberOfArgs = 0;
1129 break;
1130 case ABIArgInfo::Expand: {
1131 SmallVector<llvm::Type*, 8> Types;
1132 // FIXME: This is rather inefficient. Do we ever actually need to do
1133 // anything here? The result should be just reconstructed on the other
1134 // side, so extension should be a non-issue.
1135 CGM.getTypes().GetExpandedTypes(ArgType, Types);
1136 IRArgs.NumberOfArgs = Types.size();
1137 break;
1138 }
1139 }
1140
1141 if (IRArgs.NumberOfArgs > 0) {
1142 IRArgs.FirstArgIndex = IRArgNo;
1143 IRArgNo += IRArgs.NumberOfArgs;
1144 }
1145
1146 // Skip over the sret parameter when it comes second. We already handled it
1147 // above.
1148 if (IRArgNo == 1 && SwapThisWithSRet)
1149 IRArgNo++;
1150 }
1151 assert(ArgNo == FI.arg_size());
1152
1153 if (FI.usesInAlloca())
1154 InallocaArgNo = IRArgNo++;
1155
1156 TotalIRArgs = IRArgNo;
1157}
1158} // namespace
1159
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001160void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbard931a872009-02-02 22:03:45 +00001161 const Decl *TargetDecl,
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001162 AttributeListType &PAL,
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00001163 unsigned &CallingConv,
1164 bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001165 llvm::AttrBuilder FuncAttrs;
1166 llvm::AttrBuilder RetAttrs;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001167
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001168 CallingConv = FI.getEffectiveCallingConvention();
1169
John McCallab26cfa2010-02-05 21:31:56 +00001170 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001171 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001172
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001173 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001174 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001175 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001176 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001177 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001178 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001179 if (TargetDecl->hasAttr<NoReturnAttr>())
1180 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001181 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1182 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smithdebc59d2013-01-30 05:45:05 +00001183
1184 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
John McCallbe349de2010-07-08 06:48:12 +00001185 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl31ad7542011-03-13 17:09:40 +00001186 if (FPT && FPT->isNothrow(getContext()))
Bill Wendling207f0532012-12-20 19:27:06 +00001187 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith49af6292013-03-05 08:30:04 +00001188 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1189 // These attributes are not inherited by overloads.
1190 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1191 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001192 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001193 }
1194
Eric Christopherbf005ec2011-08-15 22:38:22 +00001195 // 'const' and 'pure' attribute functions are also nounwind.
1196 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001197 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1198 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001199 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001200 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1201 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001202 }
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001203 if (TargetDecl->hasAttr<MallocAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001204 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001205 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1206 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001207 }
1208
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001209 if (CodeGenOpts.OptimizeSize)
Bill Wendling207f0532012-12-20 19:27:06 +00001210 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
Quentin Colombet5ee5ca12012-10-26 00:29:48 +00001211 if (CodeGenOpts.OptimizeSize == 2)
Bill Wendling207f0532012-12-20 19:27:06 +00001212 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001213 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001214 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001215 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001216 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001217 if (CodeGenOpts.EnableSegmentedStacks &&
1218 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001219 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001220
Bill Wendling2f81db62013-02-22 20:53:29 +00001221 if (AttrOnCallSite) {
1222 // Attributes that should go on the call site only.
1223 if (!CodeGenOpts.SimplifyLibCalls)
1224 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Bill Wendling706469b2013-02-28 22:49:57 +00001225 } else {
1226 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001227 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001228 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001229 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001230 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001231 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001232 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001233 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001234 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001235 }
1236
Bill Wendlingdabafea2013-03-13 22:24:33 +00001237 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001238 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001239 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001240 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001241 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001242 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001243 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001244 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001245 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001246 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001247 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001248 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001249
Bill Wendlingd8f49502013-08-01 21:41:02 +00001250 if (!CodeGenOpts.StackRealignment)
1251 FuncAttrs.addAttribute("no-realign-stack");
Bill Wendling985d1c52013-02-15 21:30:01 +00001252 }
1253
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001254 ClangToLLVMArgMapping IRFunctionArgs(*this, FI);
1255
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001256 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001257 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001258 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001259 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001260 if (RetTy->hasSignedIntegerRepresentation())
1261 RetAttrs.addAttribute(llvm::Attribute::SExt);
1262 else if (RetTy->hasUnsignedIntegerRepresentation())
1263 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001264 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001265 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001266 if (RetAI.getInReg())
1267 RetAttrs.addAttribute(llvm::Attribute::InReg);
1268 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001269 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001270 break;
1271
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001272 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001273 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001274 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001275 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1276 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001277 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001278 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001279
Daniel Dunbard3674e62008-09-11 01:48:57 +00001280 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001281 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001282 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001283
Hal Finkela2347ba2014-07-18 15:52:10 +00001284 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1285 QualType PTy = RefTy->getPointeeType();
1286 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1287 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1288 .getQuantity());
1289 else if (getContext().getTargetAddressSpace(PTy) == 0)
1290 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1291 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001292
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001293 // Attach return attributes.
1294 if (RetAttrs.hasAttributes()) {
1295 PAL.push_back(llvm::AttributeSet::get(
1296 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1297 }
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001298
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001299 // Attach attributes to sret.
1300 if (IRFunctionArgs.hasSRetArg()) {
1301 llvm::AttrBuilder SRETAttrs;
1302 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
1303 if (RetAI.getInReg())
1304 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1305 PAL.push_back(llvm::AttributeSet::get(
1306 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1307 }
1308
1309 // Attach attributes to inalloca argument.
1310 if (IRFunctionArgs.hasInallocaArg()) {
1311 llvm::AttrBuilder Attrs;
1312 Attrs.addAttribute(llvm::Attribute::InAlloca);
1313 PAL.push_back(llvm::AttributeSet::get(
1314 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1315 }
1316
1317
1318 unsigned ArgNo = 0;
1319 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1320 E = FI.arg_end();
1321 I != E; ++I, ++ArgNo) {
1322 QualType ParamType = I->type;
1323 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001324 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001325
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001326 // Add attribute for padding argument, if necessary.
1327 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendling290d9522013-01-27 02:46:53 +00001328 if (AI.getPaddingInReg())
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001329 PAL.push_back(llvm::AttributeSet::get(
1330 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1331 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001332 }
1333
John McCall39ec71f2010-03-27 00:47:27 +00001334 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1335 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001336 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001337 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001338 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001339 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001340 Attrs.addAttribute(llvm::Attribute::SExt);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001341 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001342 Attrs.addAttribute(llvm::Attribute::ZExt);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001343 // FALL THROUGH
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001344 case ABIArgInfo::Direct:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001345 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001346 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001347 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001348
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001349 case ABIArgInfo::Indirect:
Rafael Espindola703c47f2012-10-19 05:04:37 +00001350 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001351 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001352
Anders Carlsson20759ad2009-09-16 15:53:40 +00001353 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001354 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001355
Bill Wendlinga7912f82012-10-10 07:36:56 +00001356 Attrs.addAlignmentAttr(AI.getIndirectAlign());
1357
Daniel Dunbarc2304432009-03-18 19:51:01 +00001358 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001359 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1360 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001361 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001362
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001363 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001364 case ABIArgInfo::Expand:
Mike Stump11289f42009-09-09 15:08:12 +00001365 continue;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001366
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001367 case ABIArgInfo::InAlloca:
1368 // inalloca disables readnone and readonly.
1369 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1370 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001371 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001372 }
Mike Stump11289f42009-09-09 15:08:12 +00001373
Hal Finkela2347ba2014-07-18 15:52:10 +00001374 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1375 QualType PTy = RefTy->getPointeeType();
1376 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1377 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1378 .getQuantity());
1379 else if (getContext().getTargetAddressSpace(PTy) == 0)
1380 Attrs.addAttribute(llvm::Attribute::NonNull);
1381 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001382
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001383 if (Attrs.hasAttributes()) {
1384 unsigned FirstIRArg, NumIRArgs;
1385 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1386 for (unsigned i = 0; i < NumIRArgs; i++)
1387 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
1388 FirstIRArg + i + 1, Attrs));
1389 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001390 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001391 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001392
Bill Wendlinga7912f82012-10-10 07:36:56 +00001393 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001394 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001395 AttributeSet::get(getLLVMContext(),
1396 llvm::AttributeSet::FunctionIndex,
1397 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001398}
1399
John McCalla738c252011-03-09 04:27:21 +00001400/// An argument came in as a promoted argument; demote it back to its
1401/// declared type.
1402static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1403 const VarDecl *var,
1404 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001405 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001406
1407 // This can happen with promotions that actually don't change the
1408 // underlying type, like the enum promotions.
1409 if (value->getType() == varType) return value;
1410
1411 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1412 && "unexpected promotion type");
1413
1414 if (isa<llvm::IntegerType>(varType))
1415 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1416
1417 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1418}
1419
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001420/// Returns the attribute (either parameter attribute, or function
1421/// attribute), which declares argument ArgNo to be non-null.
1422static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
1423 QualType ArgType, unsigned ArgNo) {
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001424 // FIXME: __attribute__((nonnull)) can also be applied to:
1425 // - references to pointers, where the pointee is known to be
1426 // nonnull (apparently a Clang extension)
1427 // - transparent unions containing pointers
1428 // In the former case, LLVM IR cannot represent the constraint. In
1429 // the latter case, we have no guarantee that the transparent union
1430 // is in fact passed as a pointer.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001431 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
1432 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001433 // First, check attribute on parameter itself.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001434 if (PVD) {
1435 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
1436 return ParmNNAttr;
1437 }
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001438 // Check function attributes.
1439 if (!FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001440 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001441 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001442 if (NNAttr->isNonNull(ArgNo))
1443 return NNAttr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001444 }
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001445 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001446}
1447
Daniel Dunbard931a872009-02-02 22:03:45 +00001448void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1449 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00001450 const FunctionArgList &Args) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00001451 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
1452 // Naked functions don't have prologues.
1453 return;
1454
John McCallcaa19452009-07-28 01:00:58 +00001455 // If this is an implicit-return-zero function, go ahead and
1456 // initialize the return value. TODO: it might be nice to have
1457 // a more general mechanism for this that didn't require synthesized
1458 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00001459 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00001460 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00001461 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001462 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00001463 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00001464 Builder.CreateStore(Zero, ReturnValue);
1465 }
1466 }
1467
Mike Stump18bb9282009-05-16 07:57:57 +00001468 // FIXME: We no longer need the types from FunctionArgList; lift up and
1469 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00001470
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001471 ClangToLLVMArgMapping IRFunctionArgs(CGM, FI);
1472 // Flattened function arguments.
1473 SmallVector<llvm::Argument *, 16> FnArgs;
1474 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
1475 for (auto &Arg : Fn->args()) {
1476 FnArgs.push_back(&Arg);
1477 }
1478 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00001479
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001480 // If we're using inalloca, all the memory arguments are GEPs off of the last
1481 // parameter, which is a pointer to the complete memory area.
Craig Topper8a13c412014-05-21 05:09:00 +00001482 llvm::Value *ArgStruct = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001483 if (IRFunctionArgs.hasInallocaArg()) {
1484 ArgStruct = FnArgs[IRFunctionArgs.getInallocaArgNo()];
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001485 assert(ArgStruct->getType() == FI.getArgStruct()->getPointerTo());
1486 }
1487
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001488 // Name the struct return parameter.
1489 if (IRFunctionArgs.hasSRetArg()) {
1490 auto AI = FnArgs[IRFunctionArgs.getSRetArgNo()];
Daniel Dunbar613855c2008-09-09 23:27:19 +00001491 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00001492 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001493 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00001494 }
Mike Stump11289f42009-09-09 15:08:12 +00001495
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001496 // Track if we received the parameter as a pointer (indirect, byval, or
1497 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
1498 // into a local alloca for us.
1499 enum ValOrPointer { HaveValue = 0, HavePointer = 1 };
Reid Kleckner8ae16272014-02-01 00:23:22 +00001500 typedef llvm::PointerIntPair<llvm::Value *, 1> ValueAndIsPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001501 SmallVector<ValueAndIsPtr, 16> ArgVals;
1502 ArgVals.reserve(Args.size());
1503
Reid Kleckner739756c2013-12-04 19:23:12 +00001504 // Create a pointer value for every parameter declaration. This usually
1505 // entails copying one or more LLVM IR arguments into an alloca. Don't push
1506 // any cleanups or do anything that might unwind. We do that separately, so
1507 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00001508 assert(FI.arg_size() == Args.size() &&
1509 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001510 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001511 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001512 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00001513 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00001514 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001515 QualType Ty = info_it->type;
1516 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001517
John McCalla738c252011-03-09 04:27:21 +00001518 bool isPromoted =
1519 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1520
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001521 unsigned FirstIRArg, NumIRArgs;
1522 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00001523
Daniel Dunbard3674e62008-09-11 01:48:57 +00001524 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001525 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001526 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001527 llvm::Value *V = Builder.CreateStructGEP(
1528 ArgStruct, ArgI.getInAllocaFieldIndex(), Arg->getName());
1529 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001530 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001531 }
1532
Daniel Dunbar747865a2009-02-05 09:16:39 +00001533 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001534 assert(NumIRArgs == 1);
1535 llvm::Value *V = FnArgs[FirstIRArg];
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001536
John McCall47fb9502013-03-07 21:37:08 +00001537 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001538 // Aggregates and complex variables are accessed by reference. All we
1539 // need to do is realign the value, if requested
1540 if (ArgI.getIndirectRealign()) {
1541 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1542
1543 // Copy from the incoming argument pointer to the temporary with the
1544 // appropriate alignment.
1545 //
1546 // FIXME: We should have a common utility for generating an aggregate
1547 // copy.
Chris Lattner2192fe52011-07-18 04:24:23 +00001548 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyck705ba072011-01-19 01:58:38 +00001549 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumidd634362011-03-10 14:02:21 +00001550 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1551 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1552 Builder.CreateMemCpy(Dst,
1553 Src,
Ken Dyck705ba072011-01-19 01:58:38 +00001554 llvm::ConstantInt::get(IntPtrTy,
1555 Size.getQuantity()),
Benjamin Krameracc6b4e2010-12-30 00:13:21 +00001556 ArgI.getIndirectAlign(),
1557 false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001558 V = AlignedTemp;
1559 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001560 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001561 } else {
1562 // Load scalar value from indirect argument.
Ken Dyck705ba072011-01-19 01:58:38 +00001563 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
Nick Lewycky2d84e842013-10-02 02:29:49 +00001564 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty,
1565 Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001566
1567 if (isPromoted)
1568 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001569 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001570 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00001571 break;
1572 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001573
1574 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001575 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00001576
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001577 // If we have the trivial case, handle it with no muss and fuss.
1578 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001579 ArgI.getCoerceToType() == ConvertType(Ty) &&
1580 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001581 assert(NumIRArgs == 1);
1582 auto AI = FnArgs[FirstIRArg];
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001583 llvm::Value *V = AI;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001584
Hal Finkel48d53e22014-07-19 01:41:07 +00001585 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001586 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
1587 PVD->getFunctionScopeIndex()))
Hal Finkel82504f02014-07-11 17:35:21 +00001588 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1589 AI->getArgNo() + 1,
1590 llvm::Attribute::NonNull));
1591
Hal Finkel48d53e22014-07-19 01:41:07 +00001592 QualType OTy = PVD->getOriginalType();
1593 if (const auto *ArrTy =
1594 getContext().getAsConstantArrayType(OTy)) {
1595 // A C99 array parameter declaration with the static keyword also
1596 // indicates dereferenceability, and if the size is constant we can
1597 // use the dereferenceable attribute (which requires the size in
1598 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00001599 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00001600 QualType ETy = ArrTy->getElementType();
1601 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
1602 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
1603 ArrSize) {
1604 llvm::AttrBuilder Attrs;
1605 Attrs.addDereferenceableAttr(
1606 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
1607 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1608 AI->getArgNo() + 1, Attrs));
1609 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
1610 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1611 AI->getArgNo() + 1,
1612 llvm::Attribute::NonNull));
1613 }
1614 }
1615 } else if (const auto *ArrTy =
1616 getContext().getAsVariableArrayType(OTy)) {
1617 // For C99 VLAs with the static keyword, we don't know the size so
1618 // we can't use the dereferenceable attribute, but in addrspace(0)
1619 // we know that it must be nonnull.
1620 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
1621 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
1622 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1623 AI->getArgNo() + 1,
1624 llvm::Attribute::NonNull));
1625 }
1626 }
1627
Bill Wendling507c3512012-10-16 05:23:44 +00001628 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001629 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1630 AI->getArgNo() + 1,
1631 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00001632
Chris Lattner7369c142011-07-20 06:29:00 +00001633 // Ensure the argument is the correct type.
1634 if (V->getType() != ArgI.getCoerceToType())
1635 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1636
John McCalla738c252011-03-09 04:27:21 +00001637 if (isPromoted)
1638 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00001639
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001640 if (const CXXMethodDecl *MD =
1641 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001642 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001643 V = CGM.getCXXABI().
1644 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001645 }
1646
Rafael Espindola8778c282012-11-29 16:09:03 +00001647 // Because of merging of function types from multiple decls it is
1648 // possible for the type of an argument to not match the corresponding
1649 // type in the function type. Since we are codegening the callee
1650 // in here, add a cast to the argument type.
1651 llvm::Type *LTy = ConvertType(Arg->getType());
1652 if (V->getType() != LTy)
1653 V = Builder.CreateBitCast(V, LTy);
1654
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001655 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001656 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00001657 }
Mike Stump11289f42009-09-09 15:08:12 +00001658
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001659 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001660
Chris Lattnerff941a62010-07-28 18:24:28 +00001661 // The alignment we need to use is the max of the requested alignment for
1662 // the argument plus the alignment required by our access code below.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001663 unsigned AlignmentToUse =
Micah Villmowdd31ca12012-10-08 16:25:52 +00001664 CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerff941a62010-07-28 18:24:28 +00001665 AlignmentToUse = std::max(AlignmentToUse,
1666 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001667
Chris Lattnerff941a62010-07-28 18:24:28 +00001668 Alloca->setAlignment(AlignmentToUse);
Chris Lattnerc401de92010-07-05 20:21:00 +00001669 llvm::Value *V = Alloca;
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001670 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001671
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001672 // If the value is offset in memory, apply the offset now.
1673 if (unsigned Offs = ArgI.getDirectOffset()) {
1674 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1675 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001676 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001677 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1678 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001679
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001680 // Fast-isel and the optimizer generally like scalar values better than
1681 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001682 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001683 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
1684 STy->getNumElements() > 1) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001685 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001686 llvm::Type *DstTy =
1687 cast<llvm::PointerType>(Ptr->getType())->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00001688 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001689
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001690 if (SrcSize <= DstSize) {
1691 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1692
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001693 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001694 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001695 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001696 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1697 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001698 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001699 }
1700 } else {
1701 llvm::AllocaInst *TempAlloca =
1702 CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1703 TempAlloca->setAlignment(AlignmentToUse);
1704 llvm::Value *TempV = TempAlloca;
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(TempV, 0, i);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001711 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001712 }
1713
1714 Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
Chris Lattner15ec3612010-06-29 00:06:42 +00001715 }
1716 } else {
1717 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001718 assert(NumIRArgs == 1);
1719 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00001720 AI->setName(Arg->getName() + ".coerce");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001721 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00001722 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001723
1724
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001725 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00001726 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001727 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001728 if (isPromoted)
1729 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001730 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
1731 } else {
1732 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00001733 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001734 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001735 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001736
1737 case ABIArgInfo::Expand: {
1738 // If this structure was expanded into multiple arguments then
1739 // we need to create a temporary and reconstruct it from the
1740 // arguments.
Eli Friedman3d9f47f2011-11-03 21:39:02 +00001741 llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
Eli Friedmana0544d62011-12-03 04:14:32 +00001742 CharUnits Align = getContext().getDeclAlign(Arg);
1743 Alloca->setAlignment(Align.getQuantity());
1744 LValue LV = MakeAddrLValue(Alloca, Ty, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001745 ArgVals.push_back(ValueAndIsPtr(Alloca, HavePointer));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001746
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001747 auto FnArgIter = FnArgs.begin() + FirstIRArg;
1748 ExpandTypeFromArgs(Ty, LV, FnArgIter);
1749 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
1750 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
1751 auto AI = FnArgs[FirstIRArg + i];
1752 AI->setName(Arg->getName() + "." + Twine(i));
1753 }
1754 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001755 }
1756
1757 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001758 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001759 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001760 if (!hasScalarEvaluationKind(Ty)) {
1761 ArgVals.push_back(ValueAndIsPtr(CreateMemTemp(Ty), HavePointer));
1762 } else {
1763 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
1764 ArgVals.push_back(ValueAndIsPtr(U, HaveValue));
1765 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001766 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001767 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00001768 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001769
Reid Kleckner739756c2013-12-04 19:23:12 +00001770 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1771 for (int I = Args.size() - 1; I >= 0; --I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001772 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1773 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00001774 } else {
1775 for (unsigned I = 0, E = Args.size(); I != E; ++I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001776 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1777 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00001778 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00001779}
1780
John McCallffa2c1a2012-01-29 07:46:59 +00001781static void eraseUnusedBitCasts(llvm::Instruction *insn) {
1782 while (insn->use_empty()) {
1783 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
1784 if (!bitcast) return;
1785
1786 // This is "safe" because we would have used a ConstantExpr otherwise.
1787 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
1788 bitcast->eraseFromParent();
1789 }
1790}
1791
John McCall31168b02011-06-15 23:02:42 +00001792/// Try to emit a fused autorelease of a return result.
1793static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
1794 llvm::Value *result) {
1795 // We must be immediately followed the cast.
1796 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00001797 if (BB->empty()) return nullptr;
1798 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001799
Chris Lattner2192fe52011-07-18 04:24:23 +00001800 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00001801
1802 // result is in a BasicBlock and is therefore an Instruction.
1803 llvm::Instruction *generator = cast<llvm::Instruction>(result);
1804
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001805 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00001806
1807 // Look for:
1808 // %generator = bitcast %type1* %generator2 to %type2*
1809 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
1810 // We would have emitted this as a constant if the operand weren't
1811 // an Instruction.
1812 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
1813
1814 // Require the generator to be immediately followed by the cast.
1815 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00001816 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001817
1818 insnsToKill.push_back(bitcast);
1819 }
1820
1821 // Look for:
1822 // %generator = call i8* @objc_retain(i8* %originalResult)
1823 // or
1824 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
1825 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00001826 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001827
1828 bool doRetainAutorelease;
1829
1830 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
1831 doRetainAutorelease = true;
1832 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
1833 .objc_retainAutoreleasedReturnValue) {
1834 doRetainAutorelease = false;
1835
John McCallcfa4e9b2012-09-07 23:30:50 +00001836 // If we emitted an assembly marker for this call (and the
1837 // ARCEntrypoints field should have been set if so), go looking
1838 // for that call. If we can't find it, we can't do this
1839 // optimization. But it should always be the immediately previous
1840 // instruction, unless we needed bitcasts around the call.
1841 if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
1842 llvm::Instruction *prev = call->getPrevNode();
1843 assert(prev);
1844 if (isa<llvm::BitCastInst>(prev)) {
1845 prev = prev->getPrevNode();
1846 assert(prev);
1847 }
1848 assert(isa<llvm::CallInst>(prev));
1849 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
1850 CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
1851 insnsToKill.push_back(prev);
1852 }
John McCall31168b02011-06-15 23:02:42 +00001853 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00001854 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001855 }
1856
1857 result = call->getArgOperand(0);
1858 insnsToKill.push_back(call);
1859
1860 // Keep killing bitcasts, for sanity. Note that we no longer care
1861 // about precise ordering as long as there's exactly one use.
1862 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
1863 if (!bitcast->hasOneUse()) break;
1864 insnsToKill.push_back(bitcast);
1865 result = bitcast->getOperand(0);
1866 }
1867
1868 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001869 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00001870 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
1871 (*i)->eraseFromParent();
1872
1873 // Do the fused retain/autorelease if we were asked to.
1874 if (doRetainAutorelease)
1875 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
1876
1877 // Cast back to the result type.
1878 return CGF.Builder.CreateBitCast(result, resultType);
1879}
1880
John McCallffa2c1a2012-01-29 07:46:59 +00001881/// If this is a +1 of the value of an immutable 'self', remove it.
1882static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
1883 llvm::Value *result) {
1884 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00001885 const ObjCMethodDecl *method =
1886 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00001887 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00001888 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00001889 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00001890
1891 // Look for a retain call.
1892 llvm::CallInst *retainCall =
1893 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
1894 if (!retainCall ||
1895 retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00001896 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00001897
1898 // Look for an ordinary load of 'self'.
1899 llvm::Value *retainedValue = retainCall->getArgOperand(0);
1900 llvm::LoadInst *load =
1901 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
1902 if (!load || load->isAtomic() || load->isVolatile() ||
1903 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
Craig Topper8a13c412014-05-21 05:09:00 +00001904 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00001905
1906 // Okay! Burn it all down. This relies for correctness on the
1907 // assumption that the retain is emitted as part of the return and
1908 // that thereafter everything is used "linearly".
1909 llvm::Type *resultType = result->getType();
1910 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
1911 assert(retainCall->use_empty());
1912 retainCall->eraseFromParent();
1913 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
1914
1915 return CGF.Builder.CreateBitCast(load, resultType);
1916}
1917
John McCall31168b02011-06-15 23:02:42 +00001918/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00001919///
1920/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00001921static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
1922 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00001923 // If we're returning 'self', kill the initial retain. This is a
1924 // heuristic attempt to "encourage correctness" in the really unfortunate
1925 // case where we have a return of self during a dealloc and we desperately
1926 // need to avoid the possible autorelease.
1927 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
1928 return self;
1929
John McCall31168b02011-06-15 23:02:42 +00001930 // At -O0, try to emit a fused retain/autorelease.
1931 if (CGF.shouldUseFusedARCCalls())
1932 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
1933 return fused;
1934
1935 return CGF.EmitARCAutoreleaseReturnValue(result);
1936}
1937
John McCall6e1c0122012-01-29 02:35:02 +00001938/// Heuristically search for a dominating store to the return-value slot.
1939static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
1940 // If there are multiple uses of the return-value slot, just check
1941 // for something immediately preceding the IP. Sometimes this can
1942 // happen with how we generate implicit-returns; it can also happen
1943 // with noreturn cleanups.
1944 if (!CGF.ReturnValue->hasOneUse()) {
1945 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00001946 if (IP->empty()) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00001947 llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back());
Craig Topper8a13c412014-05-21 05:09:00 +00001948 if (!store) return nullptr;
1949 if (store->getPointerOperand() != CGF.ReturnValue) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00001950 assert(!store->isAtomic() && !store->isVolatile()); // see below
1951 return store;
1952 }
1953
1954 llvm::StoreInst *store =
Chandler Carruth4d01fff2014-03-09 03:16:50 +00001955 dyn_cast<llvm::StoreInst>(CGF.ReturnValue->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00001956 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00001957
1958 // These aren't actually possible for non-coerced returns, and we
1959 // only care about non-coerced returns on this code path.
1960 assert(!store->isAtomic() && !store->isVolatile());
1961
1962 // Now do a first-and-dirty dominance check: just walk up the
1963 // single-predecessors chain from the current insertion point.
1964 llvm::BasicBlock *StoreBB = store->getParent();
1965 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
1966 while (IP != StoreBB) {
1967 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00001968 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00001969 }
1970
1971 // Okay, the store's basic block dominates the insertion point; we
1972 // can do our thing.
1973 return store;
1974}
1975
Adrian Prantl3be10542013-05-02 17:30:20 +00001976void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001977 bool EmitRetDbgLoc,
1978 SourceLocation EndLoc) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00001979 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
1980 // Naked functions don't have epilogues.
1981 Builder.CreateUnreachable();
1982 return;
1983 }
1984
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001985 // Functions with no result always return void.
Craig Topper8a13c412014-05-21 05:09:00 +00001986 if (!ReturnValue) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001987 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00001988 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001989 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00001990
Dan Gohman481e40c2010-07-20 20:13:52 +00001991 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00001992 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00001993 QualType RetTy = FI.getReturnType();
1994 const ABIArgInfo &RetAI = FI.getReturnInfo();
1995
1996 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001997 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001998 // Aggregrates get evaluated directly into the destination. Sometimes we
1999 // need to return the sret value in a register, though.
2000 assert(hasAggregateEvaluationKind(RetTy));
2001 if (RetAI.getInAllocaSRet()) {
2002 llvm::Function::arg_iterator EI = CurFn->arg_end();
2003 --EI;
2004 llvm::Value *ArgStruct = EI;
2005 llvm::Value *SRet =
2006 Builder.CreateStructGEP(ArgStruct, RetAI.getInAllocaFieldIndex());
2007 RV = Builder.CreateLoad(SRet, "sret");
2008 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002009 break;
2010
Daniel Dunbar03816342010-08-21 02:24:36 +00002011 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002012 auto AI = CurFn->arg_begin();
2013 if (RetAI.isSRetAfterThis())
2014 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002015 switch (getEvaluationKind(RetTy)) {
2016 case TEK_Complex: {
2017 ComplexPairTy RT =
Nick Lewycky2d84e842013-10-02 02:29:49 +00002018 EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
2019 EndLoc);
Reid Kleckner37abaca2014-05-09 22:46:15 +00002020 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002021 /*isInit*/ true);
2022 break;
2023 }
2024 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002025 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002026 break;
2027 case TEK_Scalar:
2028 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Reid Kleckner37abaca2014-05-09 22:46:15 +00002029 MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002030 /*isInit*/ true);
2031 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002032 }
2033 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002034 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002035
2036 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002037 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002038 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2039 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002040 // The internal return value temp always will have pointer-to-return-type
2041 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002042
John McCall6e1c0122012-01-29 02:35:02 +00002043 // If there is a dominating store to ReturnValue, we can elide
2044 // the load, zap the store, and usually zap the alloca.
2045 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002046 // Reuse the debug location from the store unless there is
2047 // cleanup code to be emitted between the store and return
2048 // instruction.
2049 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002050 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002051 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002052 RV = SI->getValueOperand();
2053 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002054
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002055 // If that was the only use of the return value, nuke it as well now.
2056 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
2057 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00002058 ReturnValue = nullptr;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002059 }
John McCall6e1c0122012-01-29 02:35:02 +00002060
2061 // Otherwise, we have to do a simple load.
2062 } else {
2063 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002064 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002065 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002066 llvm::Value *V = ReturnValue;
2067 // If the value is offset in memory, apply the offset now.
2068 if (unsigned Offs = RetAI.getDirectOffset()) {
2069 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
2070 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002071 V = Builder.CreateBitCast(V,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002072 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
2073 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002074
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002075 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002076 }
John McCall31168b02011-06-15 23:02:42 +00002077
2078 // In ARC, end functions that return a retainable type with a call
2079 // to objc_autoreleaseReturnValue.
2080 if (AutoreleaseResult) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002081 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002082 !FI.isReturnsRetained() &&
2083 RetTy->isObjCRetainableType());
2084 RV = emitAutoreleaseOfResult(*this, RV);
2085 }
2086
Chris Lattner726b3d02010-06-26 23:13:19 +00002087 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002088
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002089 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002090 break;
2091
2092 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002093 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002094 }
2095
Alexey Samsonovde443c52014-08-13 00:26:40 +00002096 llvm::Instruction *Ret;
2097 if (RV) {
Alexey Samsonov90452df2014-09-08 20:17:19 +00002098 if (SanOpts->ReturnsNonnullAttribute) {
2099 if (auto RetNNAttr = CurGD.getDecl()->getAttr<ReturnsNonNullAttr>()) {
2100 SanitizerScope SanScope(this);
2101 llvm::Value *Cond = Builder.CreateICmpNE(
2102 RV, llvm::Constant::getNullValue(RV->getType()));
2103 llvm::Constant *StaticData[] = {
2104 EmitCheckSourceLocation(EndLoc),
2105 EmitCheckSourceLocation(RetNNAttr->getLocation()),
2106 };
2107 EmitCheck(Cond, "nonnull_return", StaticData, None, CRK_Recoverable);
2108 }
Alexey Samsonovde443c52014-08-13 00:26:40 +00002109 }
2110 Ret = Builder.CreateRet(RV);
2111 } else {
2112 Ret = Builder.CreateRetVoid();
2113 }
2114
Devang Patel65497582010-07-21 18:08:50 +00002115 if (!RetDbgLoc.isUnknown())
2116 Ret->setDebugLoc(RetDbgLoc);
Daniel Dunbar613855c2008-09-09 23:27:19 +00002117}
2118
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002119static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2120 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2121 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2122}
2123
2124static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty) {
2125 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2126 // placeholders.
2127 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2128 llvm::Value *Placeholder =
2129 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2130 Placeholder = CGF.Builder.CreateLoad(Placeholder);
2131 return AggValueSlot::forAddr(Placeholder, CharUnits::Zero(),
2132 Ty.getQualifiers(),
2133 AggValueSlot::IsNotDestructed,
2134 AggValueSlot::DoesNotNeedGCBarriers,
2135 AggValueSlot::IsNotAliased);
2136}
2137
John McCall32ea9692011-03-11 20:59:21 +00002138void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002139 const VarDecl *param,
2140 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002141 // StartFunction converted the ABI-lowered parameter(s) into a
2142 // local alloca. We need to turn that into an r-value suitable
2143 // for EmitCall.
John McCall32ea9692011-03-11 20:59:21 +00002144 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002145
John McCall32ea9692011-03-11 20:59:21 +00002146 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002147
John McCall23f66262010-05-26 22:34:26 +00002148 // For the most part, we just need to load the alloca, except:
2149 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall47fb9502013-03-07 21:37:08 +00002150 // 2) references to non-scalars are pointers directly to the aggregate.
2151 // I don't know why references to scalars are different here.
John McCall32ea9692011-03-11 20:59:21 +00002152 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall47fb9502013-03-07 21:37:08 +00002153 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall32ea9692011-03-11 20:59:21 +00002154 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00002155
2156 // Locals which are references to scalars are represented
2157 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00002158 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00002159 }
2160
Reid Klecknerab2090d2014-07-26 01:34:32 +00002161 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2162 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002163
Nick Lewycky2d84e842013-10-02 02:29:49 +00002164 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00002165}
2166
John McCall31168b02011-06-15 23:02:42 +00002167static bool isProvablyNull(llvm::Value *addr) {
2168 return isa<llvm::ConstantPointerNull>(addr);
2169}
2170
2171static bool isProvablyNonNull(llvm::Value *addr) {
2172 return isa<llvm::AllocaInst>(addr);
2173}
2174
2175/// Emit the actual writing-back of a writeback.
2176static void emitWriteback(CodeGenFunction &CGF,
2177 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002178 const LValue &srcLV = writeback.Source;
2179 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002180 assert(!isProvablyNull(srcAddr) &&
2181 "shouldn't have writeback for provably null argument");
2182
Craig Topper8a13c412014-05-21 05:09:00 +00002183 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002184
2185 // If the argument wasn't provably non-null, we need to null check
2186 // before doing the store.
2187 bool provablyNonNull = isProvablyNonNull(srcAddr);
2188 if (!provablyNonNull) {
2189 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2190 contBB = CGF.createBasicBlock("icr.done");
2191
2192 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2193 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2194 CGF.EmitBlock(writebackBB);
2195 }
2196
2197 // Load the value to writeback.
2198 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2199
2200 // Cast it back, in case we're writing an id to a Foo* or something.
2201 value = CGF.Builder.CreateBitCast(value,
2202 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
2203 "icr.writeback-cast");
2204
2205 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00002206
2207 // If we have a "to use" value, it's something we need to emit a use
2208 // of. This has to be carefully threaded in: if it's done after the
2209 // release it's potentially undefined behavior (and the optimizer
2210 // will ignore it), and if it happens before the retain then the
2211 // optimizer could move the release there.
2212 if (writeback.ToUse) {
2213 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2214
2215 // Retain the new value. No need to block-copy here: the block's
2216 // being passed up the stack.
2217 value = CGF.EmitARCRetainNonBlock(value);
2218
2219 // Emit the intrinsic use here.
2220 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2221
2222 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00002223 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00002224
2225 // Put the new value in place (primitively).
2226 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2227
2228 // Release the old value.
2229 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2230
2231 // Otherwise, we can just do a normal lvalue store.
2232 } else {
2233 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2234 }
John McCall31168b02011-06-15 23:02:42 +00002235
2236 // Jump to the continuation block.
2237 if (!provablyNonNull)
2238 CGF.EmitBlock(contBB);
2239}
2240
2241static void emitWritebacks(CodeGenFunction &CGF,
2242 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00002243 for (const auto &I : args.writebacks())
2244 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00002245}
2246
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002247static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2248 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002249 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002250 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2251 CallArgs.getCleanupsToDeactivate();
2252 // Iterate in reverse to increase the likelihood of popping the cleanup.
2253 for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
2254 I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
2255 CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
2256 I->IsActiveIP->eraseFromParent();
2257 }
2258}
2259
John McCalleff18842013-03-23 02:35:54 +00002260static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2261 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2262 if (uop->getOpcode() == UO_AddrOf)
2263 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002264 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00002265}
2266
John McCall31168b02011-06-15 23:02:42 +00002267/// Emit an argument that's being passed call-by-writeback. That is,
2268/// we are passing the address of
2269static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2270 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00002271 LValue srcLV;
2272
2273 // Make an optimistic effort to emit the address as an l-value.
2274 // This can fail if the the argument expression is more complicated.
2275 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2276 srcLV = CGF.EmitLValue(lvExpr);
2277
2278 // Otherwise, just emit it as a scalar.
2279 } else {
2280 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
2281
2282 QualType srcAddrType =
2283 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
2284 srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
2285 }
2286 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002287
2288 // The dest and src types don't necessarily match in LLVM terms
2289 // because of the crazy ObjC compatibility rules.
2290
Chris Lattner2192fe52011-07-18 04:24:23 +00002291 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00002292 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
2293
2294 // If the address is a constant null, just pass the appropriate null.
2295 if (isProvablyNull(srcAddr)) {
2296 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
2297 CRE->getType());
2298 return;
2299 }
2300
John McCall31168b02011-06-15 23:02:42 +00002301 // Create the temporary.
2302 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
2303 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002304 // Loading an l-value can introduce a cleanup if the l-value is __weak,
2305 // and that cleanup will be conditional if we can't prove that the l-value
2306 // isn't null, so we need to register a dominating point so that the cleanups
2307 // system will make valid IR.
2308 CodeGenFunction::ConditionalEvaluation condEval(CGF);
2309
John McCall31168b02011-06-15 23:02:42 +00002310 // Zero-initialize it if we're not doing a copy-initialization.
2311 bool shouldCopy = CRE->shouldCopy();
2312 if (!shouldCopy) {
2313 llvm::Value *null =
2314 llvm::ConstantPointerNull::get(
2315 cast<llvm::PointerType>(destType->getElementType()));
2316 CGF.Builder.CreateStore(null, temp);
2317 }
Craig Topper8a13c412014-05-21 05:09:00 +00002318
2319 llvm::BasicBlock *contBB = nullptr;
2320 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002321
2322 // If the address is *not* known to be non-null, we need to switch.
2323 llvm::Value *finalArgument;
2324
2325 bool provablyNonNull = isProvablyNonNull(srcAddr);
2326 if (provablyNonNull) {
2327 finalArgument = temp;
2328 } else {
2329 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2330
2331 finalArgument = CGF.Builder.CreateSelect(isNull,
2332 llvm::ConstantPointerNull::get(destType),
2333 temp, "icr.argument");
2334
2335 // If we need to copy, then the load has to be conditional, which
2336 // means we need control flow.
2337 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00002338 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002339 contBB = CGF.createBasicBlock("icr.cont");
2340 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
2341 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
2342 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002343 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00002344 }
2345 }
2346
Craig Topper8a13c412014-05-21 05:09:00 +00002347 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00002348
John McCall31168b02011-06-15 23:02:42 +00002349 // Perform a copy if necessary.
2350 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002351 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002352 assert(srcRV.isScalar());
2353
2354 llvm::Value *src = srcRV.getScalarVal();
2355 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
2356 "icr.cast");
2357
2358 // Use an ordinary store, not a store-to-lvalue.
2359 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00002360
2361 // If optimization is enabled, and the value was held in a
2362 // __strong variable, we need to tell the optimizer that this
2363 // value has to stay alive until we're doing the store back.
2364 // This is because the temporary is effectively unretained,
2365 // and so otherwise we can violate the high-level semantics.
2366 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2367 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
2368 valueToUse = src;
2369 }
John McCall31168b02011-06-15 23:02:42 +00002370 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002371
John McCall31168b02011-06-15 23:02:42 +00002372 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002373 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00002374 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002375 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00002376
2377 // Make a phi for the value to intrinsically use.
2378 if (valueToUse) {
2379 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2380 "icr.to-use");
2381 phiToUse->addIncoming(valueToUse, copyBB);
2382 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2383 originBB);
2384 valueToUse = phiToUse;
2385 }
2386
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002387 condEval.end(CGF);
2388 }
John McCall31168b02011-06-15 23:02:42 +00002389
John McCalleff18842013-03-23 02:35:54 +00002390 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00002391 args.add(RValue::get(finalArgument), CRE->getType());
2392}
2393
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002394void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
2395 assert(!StackBase && !StackCleanup.isValid());
2396
2397 // Save the stack.
2398 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
2399 StackBase = CGF.Builder.CreateCall(F, "inalloca.save");
2400
2401 // Control gets really tied up in landing pads, so we have to spill the
2402 // stacksave to an alloca to avoid violating SSA form.
2403 // TODO: This is dead if we never emit the cleanup. We should create the
2404 // alloca and store lazily on the first cleanup emission.
2405 StackBaseMem = CGF.CreateTempAlloca(CGF.Int8PtrTy, "inalloca.spmem");
2406 CGF.Builder.CreateStore(StackBase, StackBaseMem);
2407 CGF.pushStackRestore(EHCleanup, StackBaseMem);
2408 StackCleanup = CGF.EHStack.getInnermostEHScope();
2409 assert(StackCleanup.isValid());
2410}
2411
2412void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
2413 if (StackBase) {
2414 CGF.DeactivateCleanupBlock(StackCleanup, StackBase);
2415 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
2416 // We could load StackBase from StackBaseMem, but in the non-exceptional
2417 // case we can skip it.
2418 CGF.Builder.CreateCall(F, StackBase);
2419 }
2420}
2421
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002422static void emitNonNullArgCheck(CodeGenFunction &CGF, RValue RV,
2423 QualType ArgType, SourceLocation ArgLoc,
2424 const FunctionDecl *FD, unsigned ParmNum) {
2425 if (!CGF.SanOpts->NonnullAttribute || !FD)
2426 return;
2427 auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
2428 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
2429 auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
2430 if (!NNAttr)
2431 return;
2432 CodeGenFunction::SanitizerScope SanScope(&CGF);
2433 assert(RV.isScalar());
2434 llvm::Value *V = RV.getScalarVal();
2435 llvm::Value *Cond =
2436 CGF.Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
2437 llvm::Constant *StaticData[] = {
2438 CGF.EmitCheckSourceLocation(ArgLoc),
2439 CGF.EmitCheckSourceLocation(NNAttr->getLocation()),
2440 llvm::ConstantInt::get(CGF.Int32Ty, ArgNo + 1),
2441 };
2442 CGF.EmitCheck(Cond, "nonnull_arg", StaticData, None,
2443 CodeGenFunction::CRK_Recoverable);
2444}
2445
Reid Kleckner739756c2013-12-04 19:23:12 +00002446void CodeGenFunction::EmitCallArgs(CallArgList &Args,
2447 ArrayRef<QualType> ArgTypes,
2448 CallExpr::const_arg_iterator ArgBeg,
2449 CallExpr::const_arg_iterator ArgEnd,
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002450 const FunctionDecl *CalleeDecl,
2451 unsigned ParamsToSkip,
Reid Kleckner739756c2013-12-04 19:23:12 +00002452 bool ForceColumnInfo) {
2453 CGDebugInfo *DI = getDebugInfo();
2454 SourceLocation CallLoc;
2455 if (DI) CallLoc = DI->getLocation();
2456
2457 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
2458 // because arguments are destroyed left to right in the callee.
2459 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002460 // Insert a stack save if we're going to need any inalloca args.
2461 bool HasInAllocaArgs = false;
2462 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
2463 I != E && !HasInAllocaArgs; ++I)
2464 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
2465 if (HasInAllocaArgs) {
2466 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2467 Args.allocateArgumentMemory(*this);
2468 }
2469
2470 // Evaluate each argument.
Reid Kleckner739756c2013-12-04 19:23:12 +00002471 size_t CallArgsStart = Args.size();
2472 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
2473 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2474 EmitCallArg(Args, *Arg, ArgTypes[I]);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002475 emitNonNullArgCheck(*this, Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
2476 CalleeDecl, ParamsToSkip + I);
Reid Kleckner739756c2013-12-04 19:23:12 +00002477 // Restore the debug location.
2478 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2479 }
2480
2481 // Un-reverse the arguments we just evaluated so they match up with the LLVM
2482 // IR function.
2483 std::reverse(Args.begin() + CallArgsStart, Args.end());
2484 return;
2485 }
2486
2487 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
2488 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2489 assert(Arg != ArgEnd);
2490 EmitCallArg(Args, *Arg, ArgTypes[I]);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002491 emitNonNullArgCheck(*this, Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
2492 CalleeDecl, ParamsToSkip + I);
Reid Kleckner739756c2013-12-04 19:23:12 +00002493 // Restore the debug location.
2494 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2495 }
2496}
2497
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002498namespace {
2499
2500struct DestroyUnpassedArg : EHScopeStack::Cleanup {
2501 DestroyUnpassedArg(llvm::Value *Addr, QualType Ty)
2502 : Addr(Addr), Ty(Ty) {}
2503
2504 llvm::Value *Addr;
2505 QualType Ty;
2506
Craig Topper4f12f102014-03-12 06:41:41 +00002507 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002508 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
2509 assert(!Dtor->isTrivial());
2510 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
2511 /*Delegating=*/false, Addr);
2512 }
2513};
2514
2515}
2516
John McCall32ea9692011-03-11 20:59:21 +00002517void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2518 QualType type) {
John McCall31168b02011-06-15 23:02:42 +00002519 if (const ObjCIndirectCopyRestoreExpr *CRE
2520 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002521 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00002522 assert(getContext().hasSameType(E->getType(), type));
2523 return emitWritebackArg(*this, args, CRE);
2524 }
2525
John McCall0a76c0c2011-08-26 18:42:59 +00002526 assert(type->isReferenceType() == E->isGLValue() &&
2527 "reference binding to unmaterialized r-value!");
2528
John McCall17054bd62011-08-26 21:08:13 +00002529 if (E->isGLValue()) {
2530 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00002531 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00002532 }
Mike Stump11289f42009-09-09 15:08:12 +00002533
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002534 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2535
2536 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2537 // However, we still have to push an EH-only cleanup in case we unwind before
2538 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00002539 if (HasAggregateEvalKind &&
2540 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2541 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00002542 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00002543 AggValueSlot Slot;
2544 if (args.isUsingInAlloca())
2545 Slot = createPlaceholderSlot(*this, type);
2546 else
2547 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00002548
2549 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2550 bool DestroyedInCallee =
2551 RD && RD->hasNonTrivialDestructor() &&
2552 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
2553 if (DestroyedInCallee)
2554 Slot.setExternallyDestructed();
2555
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002556 EmitAggExpr(E, Slot);
2557 RValue RV = Slot.asRValue();
2558 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002559
Reid Klecknere39ee212014-05-03 00:33:28 +00002560 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002561 // Create a no-op GEP between the placeholder and the cleanup so we can
2562 // RAUW it successfully. It also serves as a marker of the first
2563 // instruction where the cleanup is active.
2564 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddr(), type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002565 // This unreachable is a temporary marker which will be removed later.
2566 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2567 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002568 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002569 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002570 }
2571
2572 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00002573 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2574 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2575 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00002576 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2577 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2578 } else {
2579 // We can't represent a misaligned lvalue in the CallArgList, so copy
2580 // to an aligned temporary now.
2581 llvm::Value *tmp = CreateMemTemp(type);
2582 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2583 L.getAlignment());
2584 args.add(RValue::getAggregate(tmp), type);
2585 }
Eli Friedmandf968192011-05-26 00:10:27 +00002586 return;
2587 }
2588
John McCall32ea9692011-03-11 20:59:21 +00002589 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00002590}
2591
Dan Gohman515a60d2012-02-16 00:57:37 +00002592// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2593// optimizer it can aggressively ignore unwind edges.
2594void
2595CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2596 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2597 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2598 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2599 CGM.getNoObjCARCExceptionsMetadata());
2600}
2601
John McCall882987f2013-02-28 19:01:20 +00002602/// Emits a call to the given no-arguments nounwind runtime function.
2603llvm::CallInst *
2604CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2605 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002606 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002607}
2608
2609/// Emits a call to the given nounwind runtime function.
2610llvm::CallInst *
2611CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2612 ArrayRef<llvm::Value*> args,
2613 const llvm::Twine &name) {
2614 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2615 call->setDoesNotThrow();
2616 return call;
2617}
2618
2619/// Emits a simple call (never an invoke) to the given no-arguments
2620/// runtime function.
2621llvm::CallInst *
2622CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2623 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002624 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002625}
2626
2627/// Emits a simple call (never an invoke) to the given runtime
2628/// function.
2629llvm::CallInst *
2630CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2631 ArrayRef<llvm::Value*> args,
2632 const llvm::Twine &name) {
2633 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2634 call->setCallingConv(getRuntimeCC());
2635 return call;
2636}
2637
2638/// Emits a call or invoke to the given noreturn runtime function.
2639void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2640 ArrayRef<llvm::Value*> args) {
2641 if (getInvokeDest()) {
2642 llvm::InvokeInst *invoke =
2643 Builder.CreateInvoke(callee,
2644 getUnreachableBlock(),
2645 getInvokeDest(),
2646 args);
2647 invoke->setDoesNotReturn();
2648 invoke->setCallingConv(getRuntimeCC());
2649 } else {
2650 llvm::CallInst *call = Builder.CreateCall(callee, args);
2651 call->setDoesNotReturn();
2652 call->setCallingConv(getRuntimeCC());
2653 Builder.CreateUnreachable();
2654 }
Justin Bogner06bd6d02014-01-13 21:24:18 +00002655 PGO.setCurrentRegionUnreachable();
John McCall882987f2013-02-28 19:01:20 +00002656}
2657
2658/// Emits a call or invoke instruction to the given nullary runtime
2659/// function.
2660llvm::CallSite
2661CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2662 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002663 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002664}
2665
2666/// Emits a call or invoke instruction to the given runtime function.
2667llvm::CallSite
2668CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2669 ArrayRef<llvm::Value*> args,
2670 const Twine &name) {
2671 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2672 callSite.setCallingConv(getRuntimeCC());
2673 return callSite;
2674}
2675
2676llvm::CallSite
2677CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2678 const Twine &Name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002679 return EmitCallOrInvoke(Callee, None, Name);
John McCall882987f2013-02-28 19:01:20 +00002680}
2681
John McCallbd309292010-07-06 01:34:17 +00002682/// Emits a call or invoke instruction to the given function, depending
2683/// on the current state of the EH stack.
2684llvm::CallSite
2685CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00002686 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002687 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00002688 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00002689
Dan Gohman515a60d2012-02-16 00:57:37 +00002690 llvm::Instruction *Inst;
2691 if (!InvokeDest)
2692 Inst = Builder.CreateCall(Callee, Args, Name);
2693 else {
2694 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
2695 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
2696 EmitBlock(ContBB);
2697 }
2698
2699 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2700 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002701 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00002702 AddObjCARCExceptionMetadata(Inst);
2703
2704 return Inst;
John McCallbd309292010-07-06 01:34:17 +00002705}
2706
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002707void CodeGenFunction::ExpandTypeToArgs(
2708 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
2709 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002710 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2711 unsigned NumElts = AT->getSize().getZExtValue();
2712 QualType EltTy = AT->getElementType();
2713 llvm::Value *Addr = RV.getAggregateAddr();
2714 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
2715 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, Elt);
Nick Lewycky2d84e842013-10-02 02:29:49 +00002716 RValue EltRV = convertTempToRValue(EltAddr, EltTy, SourceLocation());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002717 ExpandTypeToArgs(EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
Chris Lattnerd59d8672011-07-12 06:29:11 +00002718 }
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002719 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002720 RecordDecl *RD = RT->getDecl();
2721 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
Eli Friedman7f1ff602012-04-16 03:54:45 +00002722 LValue LV = MakeAddrLValue(RV.getAggregateAddr(), Ty);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002723
2724 if (RD->isUnion()) {
Craig Topper8a13c412014-05-21 05:09:00 +00002725 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002726 CharUnits UnionSize = CharUnits::Zero();
2727
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002728 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002729 assert(!FD->isBitField() &&
2730 "Cannot expand structure with bit-field members.");
2731 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
2732 if (UnionSize < FieldSize) {
2733 UnionSize = FieldSize;
2734 LargestFD = FD;
2735 }
2736 }
2737 if (LargestFD) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002738 RValue FldRV = EmitRValueForField(LV, LargestFD, SourceLocation());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002739 ExpandTypeToArgs(LargestFD->getType(), FldRV, IRFuncTy, IRCallArgs,
2740 IRCallArgPos);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002741 }
2742 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002743 for (const auto *FD : RD->fields()) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002744 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002745 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs, IRCallArgPos);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002746 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00002747 }
Eli Friedman95ff7002011-11-15 02:46:03 +00002748 } else if (Ty->isAnyComplexType()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002749 ComplexPairTy CV = RV.getComplexVal();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002750 IRCallArgs[IRCallArgPos++] = CV.first;
2751 IRCallArgs[IRCallArgPos++] = CV.second;
Bob Wilsone826a2a2011-08-03 05:58:22 +00002752 } else {
Chris Lattnerd59d8672011-07-12 06:29:11 +00002753 assert(RV.isScalar() &&
2754 "Unexpected non-scalar rvalue during struct expansion.");
2755
2756 // Insert a bitcast as needed.
2757 llvm::Value *V = RV.getScalarVal();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002758 if (IRCallArgPos < IRFuncTy->getNumParams() &&
2759 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
2760 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
Chris Lattnerd59d8672011-07-12 06:29:11 +00002761
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002762 IRCallArgs[IRCallArgPos++] = V;
Chris Lattnerd59d8672011-07-12 06:29:11 +00002763 }
2764}
2765
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002766/// \brief Store a non-aggregate value to an address to initialize it. For
2767/// initialization, a non-atomic store will be used.
2768static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
2769 LValue Dst) {
2770 if (Src.isScalar())
2771 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
2772 else
2773 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
2774}
2775
2776void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
2777 llvm::Value *New) {
2778 DeferredReplacements.push_back(std::make_pair(Old, New));
2779}
Chris Lattnerd59d8672011-07-12 06:29:11 +00002780
Daniel Dunbard931a872009-02-02 22:03:45 +00002781RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00002782 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00002783 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002784 const CallArgList &CallArgs,
David Chisnall9eecafa2010-05-01 11:15:56 +00002785 const Decl *TargetDecl,
David Chisnallff5f88c2010-05-02 13:41:58 +00002786 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00002787 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00002788
2789 // Handle struct-return functions by passing a pointer to the
2790 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00002791 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002792 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002793
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002794 llvm::FunctionType *IRFuncTy =
2795 cast<llvm::FunctionType>(
2796 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00002797
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002798 // If we're using inalloca, insert the allocation after the stack save.
2799 // FIXME: Do this earlier rather than hacking it in here!
Craig Topper8a13c412014-05-21 05:09:00 +00002800 llvm::Value *ArgMemory = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002801 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
Reid Kleckner9df1d972014-04-10 01:40:15 +00002802 llvm::Instruction *IP = CallArgs.getStackBase();
2803 llvm::AllocaInst *AI;
2804 if (IP) {
2805 IP = IP->getNextNode();
2806 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
2807 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00002808 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00002809 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002810 AI->setUsedWithInAlloca(true);
2811 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
2812 ArgMemory = AI;
2813 }
2814
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002815 ClangToLLVMArgMapping IRFunctionArgs(CGM, CallInfo);
2816 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
2817
Chris Lattner4ca97c32009-06-13 00:26:38 +00002818 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00002819 // alloca to hold the result, unless one is given to us.
Craig Topper8a13c412014-05-21 05:09:00 +00002820 llvm::Value *SRetPtr = nullptr;
Reid Kleckner37abaca2014-05-09 22:46:15 +00002821 if (RetAI.isIndirect() || RetAI.isInAlloca()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002822 SRetPtr = ReturnValue.getValue();
2823 if (!SRetPtr)
2824 SRetPtr = CreateMemTemp(RetTy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002825 if (IRFunctionArgs.hasSRetArg()) {
2826 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002827 } else {
2828 llvm::Value *Addr =
2829 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
2830 Builder.CreateStore(SRetPtr, Addr);
2831 }
Anders Carlsson17490832009-12-24 20:40:36 +00002832 }
Mike Stump11289f42009-09-09 15:08:12 +00002833
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002834 assert(CallInfo.arg_size() == CallArgs.size() &&
2835 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002836 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002837 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002838 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002839 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002840 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00002841 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002842
John McCall47fb9502013-03-07 21:37:08 +00002843 CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002844
2845 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002846 if (IRFunctionArgs.hasPaddingArg(ArgNo))
2847 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
2848 llvm::UndefValue::get(ArgInfo.getPaddingType());
2849
2850 unsigned FirstIRArg, NumIRArgs;
2851 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002852
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002853 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002854 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002855 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002856 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2857 if (RV.isAggregate()) {
2858 // Replace the placeholder with the appropriate argument slot GEP.
2859 llvm::Instruction *Placeholder =
2860 cast<llvm::Instruction>(RV.getAggregateAddr());
2861 CGBuilderTy::InsertPoint IP = Builder.saveIP();
2862 Builder.SetInsertPoint(Placeholder);
2863 llvm::Value *Addr = Builder.CreateStructGEP(
2864 ArgMemory, ArgInfo.getInAllocaFieldIndex());
2865 Builder.restoreIP(IP);
2866 deferPlaceholderReplacement(Placeholder, Addr);
2867 } else {
2868 // Store the RValue into the argument struct.
2869 llvm::Value *Addr =
2870 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
David Majnemer32b57b02014-03-31 16:12:47 +00002871 unsigned AS = Addr->getType()->getPointerAddressSpace();
2872 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
2873 // There are some cases where a trivial bitcast is not avoidable. The
2874 // definition of a type later in a translation unit may change it's type
2875 // from {}* to (%struct.foo*)*.
2876 if (Addr->getType() != MemType)
2877 Addr = Builder.CreateBitCast(Addr, MemType);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002878 LValue argLV = MakeAddrLValue(Addr, I->Ty, TypeAlign);
2879 EmitInitStoreOfNonAggregate(*this, RV, argLV);
2880 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002881 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002882 }
2883
Daniel Dunbar03816342010-08-21 02:24:36 +00002884 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002885 assert(NumIRArgs == 1);
Daniel Dunbar747865a2009-02-05 09:16:39 +00002886 if (RV.isScalar() || RV.isComplex()) {
2887 // Make a temporary alloca to pass the argument.
Eli Friedman7e68c882011-06-15 18:26:32 +00002888 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2889 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
2890 AI->setAlignment(ArgInfo.getIndirectAlign());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002891 IRCallArgs[FirstIRArg] = AI;
John McCall47fb9502013-03-07 21:37:08 +00002892
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002893 LValue argLV = MakeAddrLValue(AI, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002894 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar747865a2009-02-05 09:16:39 +00002895 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002896 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00002897 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002898 // 1. If the argument is not byval, and we are required to copy the
2899 // source. (This case doesn't occur on any common architecture.)
2900 // 2. If the argument is byval, RV is not sufficiently aligned, and
2901 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00002902 // 3. If the argument is byval, but RV is located in an address space
2903 // different than that of the argument (0).
Eli Friedmanf7456192011-06-15 22:09:18 +00002904 llvm::Value *Addr = RV.getAggregateAddr();
2905 unsigned Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002906 const llvm::DataLayout *TD = &CGM.getDataLayout();
Guy Benyei3832bfd2013-03-10 12:59:00 +00002907 const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002908 const unsigned ArgAddrSpace =
2909 (FirstIRArg < IRFuncTy->getNumParams()
2910 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
2911 : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00002912 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall47fb9502013-03-07 21:37:08 +00002913 (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
Guy Benyei3832bfd2013-03-10 12:59:00 +00002914 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align) ||
2915 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002916 // Create an aligned temporary, and copy to it.
Eli Friedmanf7456192011-06-15 22:09:18 +00002917 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2918 if (Align > AI->getAlignment())
2919 AI->setAlignment(Align);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002920 IRCallArgs[FirstIRArg] = AI;
Chad Rosier615ed1a2012-03-29 17:37:10 +00002921 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002922 } else {
2923 // Skip the extra memcpy call.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002924 IRCallArgs[FirstIRArg] = Addr;
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002925 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002926 }
2927 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002928 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002929
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002930 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002931 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002932 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002933
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002934 case ABIArgInfo::Extend:
2935 case ABIArgInfo::Direct: {
2936 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002937 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
2938 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002939 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002940 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002941 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002942 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002943 else
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002944 V = Builder.CreateLoad(RV.getAggregateAddr());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002945
Chris Lattner3ce86682011-07-12 04:53:39 +00002946 // If the argument doesn't match, perform a bitcast to coerce it. This
2947 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002948 if (FirstIRArg < IRFuncTy->getNumParams() &&
2949 V->getType() != IRFuncTy->getParamType(FirstIRArg))
2950 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
2951 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002952 break;
2953 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002954
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002955 // FIXME: Avoid the conversion through memory if possible.
2956 llvm::Value *SrcPtr;
John McCall47fb9502013-03-07 21:37:08 +00002957 if (RV.isScalar() || RV.isComplex()) {
Eli Friedmanf4258eb2011-05-02 18:05:27 +00002958 SrcPtr = CreateMemTemp(I->Ty, "coerce");
John McCall47fb9502013-03-07 21:37:08 +00002959 LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002960 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Mike Stump11289f42009-09-09 15:08:12 +00002961 } else
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002962 SrcPtr = RV.getAggregateAddr();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002963
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002964 // If the value is offset in memory, apply the offset now.
2965 if (unsigned Offs = ArgInfo.getDirectOffset()) {
2966 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
2967 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002968 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002969 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
2970
2971 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002972
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002973 // Fast-isel and the optimizer generally like scalar values better than
2974 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00002975 llvm::StructType *STy =
2976 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002977 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
Chandler Carrutha6399a52012-10-10 11:29:08 +00002978 llvm::Type *SrcTy =
2979 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
2980 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
2981 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
2982
2983 // If the source type is smaller than the destination type of the
2984 // coerce-to logic, copy the source value into a temp alloca the size
2985 // of the destination type to allow loading all of it. The bits past
2986 // the source value are left undef.
2987 if (SrcSize < DstSize) {
2988 llvm::AllocaInst *TempAlloca
2989 = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
2990 Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
2991 SrcPtr = TempAlloca;
2992 } else {
2993 SrcPtr = Builder.CreateBitCast(SrcPtr,
2994 llvm::PointerType::getUnqual(STy));
2995 }
2996
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002997 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00002998 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2999 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerff941a62010-07-28 18:24:28 +00003000 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
3001 // We don't know what we're loading from.
3002 LI->setAlignment(1);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003003 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00003004 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00003005 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00003006 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003007 assert(NumIRArgs == 1);
3008 IRCallArgs[FirstIRArg] =
3009 CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00003010 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003011
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003012 break;
3013 }
3014
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003015 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003016 unsigned IRArgPos = FirstIRArg;
3017 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
3018 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003019 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003020 }
3021 }
Mike Stump11289f42009-09-09 15:08:12 +00003022
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003023 if (ArgMemory) {
3024 llvm::Value *Arg = ArgMemory;
Reid Klecknerafba553e2014-07-08 02:24:27 +00003025 if (CallInfo.isVariadic()) {
3026 // When passing non-POD arguments by value to variadic functions, we will
3027 // end up with a variadic prototype and an inalloca call site. In such
3028 // cases, we can't do any parameter mismatch checks. Give up and bitcast
3029 // the callee.
3030 unsigned CalleeAS =
3031 cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
3032 Callee = Builder.CreateBitCast(
3033 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
3034 } else {
3035 llvm::Type *LastParamTy =
3036 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
3037 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003038#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00003039 // Assert that these structs have equivalent element types.
3040 llvm::StructType *FullTy = CallInfo.getArgStruct();
3041 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3042 cast<llvm::PointerType>(LastParamTy)->getElementType());
3043 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3044 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3045 DE = DeclaredTy->element_end(),
3046 FI = FullTy->element_begin();
3047 DI != DE; ++DI, ++FI)
3048 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003049#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00003050 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3051 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003052 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003053 assert(IRFunctionArgs.hasInallocaArg());
3054 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003055 }
3056
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003057 if (!CallArgs.getCleanupsToDeactivate().empty())
3058 deactivateArgCleanupsBeforeCall(*this, CallArgs);
3059
Chris Lattner4ca97c32009-06-13 00:26:38 +00003060 // If the callee is a bitcast of a function to a varargs pointer to function
3061 // type, check to see if we can remove the bitcast. This handles some cases
3062 // with unprototyped functions.
3063 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
3064 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003065 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
3066 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00003067 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00003068 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00003069
Chris Lattner4ca97c32009-06-13 00:26:38 +00003070 if (CE->getOpcode() == llvm::Instruction::BitCast &&
3071 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00003072 ActualFT->getNumParams() == CurFT->getNumParams() &&
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003073 ActualFT->getNumParams() == IRCallArgs.size() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00003074 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00003075 bool ArgsMatch = true;
3076 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
3077 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
3078 ArgsMatch = false;
3079 break;
3080 }
Mike Stump11289f42009-09-09 15:08:12 +00003081
Chris Lattner4ca97c32009-06-13 00:26:38 +00003082 // Strip the cast if we can get away with it. This is a nice cleanup,
3083 // but also allows us to inline the function at -O0 if it is marked
3084 // always_inline.
3085 if (ArgsMatch)
3086 Callee = CalleeF;
3087 }
3088 }
Mike Stump11289f42009-09-09 15:08:12 +00003089
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003090 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
3091 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
3092 // Inalloca argument can have different type.
3093 if (IRFunctionArgs.hasInallocaArg() &&
3094 i == IRFunctionArgs.getInallocaArgNo())
3095 continue;
3096 if (i < IRFuncTy->getNumParams())
3097 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
3098 }
3099
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003100 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00003101 CodeGen::AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003102 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
3103 CallingConv, true);
Bill Wendling3087d022012-12-07 23:17:26 +00003104 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003105 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00003106
Craig Topper8a13c412014-05-21 05:09:00 +00003107 llvm::BasicBlock *InvokeDest = nullptr;
Bill Wendling5e85be42012-12-30 10:32:17 +00003108 if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
3109 llvm::Attribute::NoUnwind))
John McCallbd309292010-07-06 01:34:17 +00003110 InvokeDest = getInvokeDest();
3111
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003112 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00003113 if (!InvokeDest) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003114 CS = Builder.CreateCall(Callee, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003115 } else {
3116 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003117 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003118 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003119 }
Chris Lattnere70a0072010-06-29 16:40:28 +00003120 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00003121 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003122
Peter Collingbourne41af7c22014-05-20 17:12:51 +00003123 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
3124 !CS.hasFnAttr(llvm::Attribute::NoInline))
3125 Attrs =
3126 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3127 llvm::Attribute::AlwaysInline);
3128
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003129 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003130 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003131
Dan Gohman515a60d2012-02-16 00:57:37 +00003132 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3133 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003134 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003135 AddObjCARCExceptionMetadata(CS.getInstruction());
3136
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003137 // If the call doesn't return, finish the basic block and clear the
3138 // insertion point; this allows the rest of IRgen to discard
3139 // unreachable code.
3140 if (CS.doesNotReturn()) {
3141 Builder.CreateUnreachable();
3142 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003143
Mike Stump18bb9282009-05-16 07:57:57 +00003144 // FIXME: For now, emit a dummy basic block because expr emitters in
3145 // generally are not ready to handle emitting expressions at unreachable
3146 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003147 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003148
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003149 // Return a reasonable RValue.
3150 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00003151 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003152
3153 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00003154 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00003155 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003156
John McCall31168b02011-06-15 23:02:42 +00003157 // Emit any writebacks immediately. Arguably this should happen
3158 // after any return-value munging.
3159 if (CallArgs.hasWritebacks())
3160 emitWritebacks(*this, CallArgs);
3161
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003162 // The stack cleanup for inalloca arguments has to run out of the normal
3163 // lexical order, so deactivate it and run it manually here.
3164 CallArgs.freeArgumentMemory(*this);
3165
Hal Finkelee90a222014-09-26 05:04:30 +00003166 RValue Ret = [&] {
3167 switch (RetAI.getKind()) {
3168 case ABIArgInfo::InAlloca:
3169 case ABIArgInfo::Indirect:
3170 return convertTempToRValue(SRetPtr, RetTy, SourceLocation());
Daniel Dunbard3674e62008-09-11 01:48:57 +00003171
Hal Finkelee90a222014-09-26 05:04:30 +00003172 case ABIArgInfo::Ignore:
3173 // If we are ignoring an argument that had a result, make sure to
3174 // construct the appropriate return value for our caller.
3175 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003176
Hal Finkelee90a222014-09-26 05:04:30 +00003177 case ABIArgInfo::Extend:
3178 case ABIArgInfo::Direct: {
3179 llvm::Type *RetIRTy = ConvertType(RetTy);
3180 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
3181 switch (getEvaluationKind(RetTy)) {
3182 case TEK_Complex: {
3183 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
3184 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
3185 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003186 }
Hal Finkelee90a222014-09-26 05:04:30 +00003187 case TEK_Aggregate: {
3188 llvm::Value *DestPtr = ReturnValue.getValue();
3189 bool DestIsVolatile = ReturnValue.isVolatile();
3190
3191 if (!DestPtr) {
3192 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
3193 DestIsVolatile = false;
3194 }
3195 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
3196 return RValue::getAggregate(DestPtr);
3197 }
3198 case TEK_Scalar: {
3199 // If the argument doesn't match, perform a bitcast to coerce it. This
3200 // can happen due to trivial type mismatches.
3201 llvm::Value *V = CI;
3202 if (V->getType() != RetIRTy)
3203 V = Builder.CreateBitCast(V, RetIRTy);
3204 return RValue::get(V);
3205 }
3206 }
3207 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003208 }
Hal Finkelee90a222014-09-26 05:04:30 +00003209
3210 llvm::Value *DestPtr = ReturnValue.getValue();
3211 bool DestIsVolatile = ReturnValue.isVolatile();
3212
3213 if (!DestPtr) {
3214 DestPtr = CreateMemTemp(RetTy, "coerce");
3215 DestIsVolatile = false;
John McCall47fb9502013-03-07 21:37:08 +00003216 }
Hal Finkelee90a222014-09-26 05:04:30 +00003217
3218 // If the value is offset in memory, apply the offset now.
3219 llvm::Value *StorePtr = DestPtr;
3220 if (unsigned Offs = RetAI.getDirectOffset()) {
3221 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
3222 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
3223 StorePtr = Builder.CreateBitCast(StorePtr,
3224 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
John McCall47fb9502013-03-07 21:37:08 +00003225 }
Hal Finkelee90a222014-09-26 05:04:30 +00003226 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
3227
3228 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003229 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003230
Hal Finkelee90a222014-09-26 05:04:30 +00003231 case ABIArgInfo::Expand:
3232 llvm_unreachable("Invalid ABI kind for return argument");
Anders Carlsson17490832009-12-24 20:40:36 +00003233 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003234
Hal Finkelee90a222014-09-26 05:04:30 +00003235 llvm_unreachable("Unhandled ABIArgInfo::Kind");
3236 } ();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003237
Hal Finkelee90a222014-09-26 05:04:30 +00003238 if (Ret.isScalar() && TargetDecl) {
3239 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
3240 llvm::Value *OffsetValue = nullptr;
3241 if (const auto *Offset = AA->getOffset())
3242 OffsetValue = EmitScalarExpr(Offset);
3243
3244 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
3245 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
3246 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
3247 OffsetValue);
3248 }
Daniel Dunbar573884e2008-09-10 07:04:09 +00003249 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00003250
Hal Finkelee90a222014-09-26 05:04:30 +00003251 return Ret;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003252}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00003253
3254/* VarArg handling */
3255
3256llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
3257 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
3258}