blob: 50cbdb1b07171238fa289fafeca848cce1484b08 [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"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/InlineAsm.h"
Bill Wendling985d1c52013-02-15 21:30:01 +000031#include "llvm/MC/SubtargetFeature.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "llvm/Support/CallSite.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.
John McCall8dda7b22012-07-07 06:41:13 +000082 return arrangeLLVMFunctionInfo(FTNP->getResultType().getUnqualifiedType(),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000083 None, FTNP->getExtInfo(), RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +000084}
85
John McCall8dda7b22012-07-07 06:41:13 +000086/// Arrange the LLVM function layout for a value of the given function
87/// type, on top of any implicit parameters already stored. Use the
88/// given ExtInfo instead of the ExtInfo from the function type.
89static const CGFunctionInfo &arrangeLLVMFunctionInfo(CodeGenTypes &CGT,
90 SmallVectorImpl<CanQualType> &prefix,
91 CanQual<FunctionProtoType> FTP,
92 FunctionType::ExtInfo extInfo) {
93 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +000094 // FIXME: Kill copy.
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000095 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
John McCall8dda7b22012-07-07 06:41:13 +000096 prefix.push_back(FTP->getArgType(i));
John McCalla729c622012-02-17 03:33:10 +000097 CanQualType resultType = FTP->getResultType().getUnqualifiedType();
John McCall8dda7b22012-07-07 06:41:13 +000098 return CGT.arrangeLLVMFunctionInfo(resultType, prefix, extInfo, required);
99}
100
101/// Arrange the argument and result information for a free function (i.e.
102/// not a C++ or ObjC instance method) of the given type.
103static const CGFunctionInfo &arrangeFreeFunctionType(CodeGenTypes &CGT,
104 SmallVectorImpl<CanQualType> &prefix,
105 CanQual<FunctionProtoType> FTP) {
106 return arrangeLLVMFunctionInfo(CGT, prefix, FTP, FTP->getExtInfo());
107}
108
John McCall8dda7b22012-07-07 06:41:13 +0000109/// Arrange the argument and result information for a free function (i.e.
110/// not a C++ or ObjC instance method) of the given type.
111static const CGFunctionInfo &arrangeCXXMethodType(CodeGenTypes &CGT,
112 SmallVectorImpl<CanQualType> &prefix,
113 CanQual<FunctionProtoType> FTP) {
114 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
John McCall8dda7b22012-07-07 06:41:13 +0000115 return arrangeLLVMFunctionInfo(CGT, prefix, FTP, extInfo);
John McCall8ee376f2010-02-24 07:14:12 +0000116}
117
John McCalla729c622012-02-17 03:33:10 +0000118/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000119/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000120const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000121CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
John McCalla729c622012-02-17 03:33:10 +0000122 SmallVector<CanQualType, 16> argTypes;
John McCall8dda7b22012-07-07 06:41:13 +0000123 return ::arrangeFreeFunctionType(*this, argTypes, FTP);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000124}
125
John McCallab26cfa2010-02-05 21:31:56 +0000126static CallingConv getCallingConventionForDecl(const Decl *D) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000127 // Set the appropriate calling convention for the Function.
128 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000129 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000130
131 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000132 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000133
Douglas Gregora941dca2010-05-18 16:57:00 +0000134 if (D->hasAttr<ThisCallAttr>())
135 return CC_X86ThisCall;
136
Dawn Perchik335e16b2010-09-03 01:29:35 +0000137 if (D->hasAttr<PascalAttr>())
138 return CC_X86Pascal;
139
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000140 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
141 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
142
Derek Schuffa2020962012-10-16 22:30:41 +0000143 if (D->hasAttr<PnaclCallAttr>())
144 return CC_PnaclCall;
145
Guy Benyeif0a014b2012-12-25 08:53:55 +0000146 if (D->hasAttr<IntelOclBiccAttr>())
147 return CC_IntelOclBicc;
148
John McCallab26cfa2010-02-05 21:31:56 +0000149 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000150}
151
John McCalla729c622012-02-17 03:33:10 +0000152/// Arrange the argument and result information for a call to an
153/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000154/// (Zero value of RD means we don't have any meaningful "this" argument type,
155/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000156/// The member function must be an ordinary function, i.e. not a
157/// constructor or destructor.
158const CGFunctionInfo &
159CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
160 const FunctionProtoType *FTP) {
161 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000162
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000163 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000164 if (RD)
165 argTypes.push_back(GetThisType(Context, RD));
166 else
167 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000168
John McCall8dda7b22012-07-07 06:41:13 +0000169 return ::arrangeCXXMethodType(*this, argTypes,
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000170 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000171}
172
John McCalla729c622012-02-17 03:33:10 +0000173/// Arrange the argument and result information for a declaration or
174/// definition of the given C++ non-static member function. The
175/// member function must be an ordinary function, i.e. not a
176/// constructor or destructor.
177const CGFunctionInfo &
178CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000179 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000180 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
181
John McCalla729c622012-02-17 03:33:10 +0000182 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000183
John McCalla729c622012-02-17 03:33:10 +0000184 if (MD->isInstance()) {
185 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000186 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000187 return arrangeCXXMethodType(ThisType, prototype.getTypePtr());
John McCalla729c622012-02-17 03:33:10 +0000188 }
189
John McCall8dda7b22012-07-07 06:41:13 +0000190 return arrangeFreeFunctionType(prototype);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000191}
192
John McCalla729c622012-02-17 03:33:10 +0000193/// Arrange the argument and result information for a declaration
194/// or definition to the given constructor variant.
195const CGFunctionInfo &
196CodeGenTypes::arrangeCXXConstructorDeclaration(const CXXConstructorDecl *D,
197 CXXCtorType ctorKind) {
198 SmallVector<CanQualType, 16> argTypes;
199 argTypes.push_back(GetThisType(Context, D->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000200
201 GlobalDecl GD(D, ctorKind);
202 CanQualType resultType =
203 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000204
John McCall5d865c322010-08-31 07:33:07 +0000205 CanQual<FunctionProtoType> FTP = GetFormalType(D);
206
207 // Add the formal parameters.
208 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
John McCalla729c622012-02-17 03:33:10 +0000209 argTypes.push_back(FTP->getArgType(i));
John McCall5d865c322010-08-31 07:33:07 +0000210
Reid Kleckner89077a12013-12-17 19:46:40 +0000211 TheCXXABI.BuildConstructorSignature(D, ctorKind, resultType, argTypes);
212
213 RequiredArgs required =
214 (D->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All);
215
John McCall8dda7b22012-07-07 06:41:13 +0000216 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
John McCall8dda7b22012-07-07 06:41:13 +0000217 return arrangeLLVMFunctionInfo(resultType, argTypes, extInfo, required);
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000218}
219
John McCalla729c622012-02-17 03:33:10 +0000220/// Arrange the argument and result information for a declaration,
221/// definition, or call to the given destructor variant. It so
222/// happens that all three cases produce the same information.
223const CGFunctionInfo &
224CodeGenTypes::arrangeCXXDestructor(const CXXDestructorDecl *D,
225 CXXDtorType dtorKind) {
226 SmallVector<CanQualType, 2> argTypes;
227 argTypes.push_back(GetThisType(Context, D->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000228
229 GlobalDecl GD(D, dtorKind);
230 CanQualType resultType =
231 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
John McCall8ee376f2010-02-24 07:14:12 +0000232
John McCalla729c622012-02-17 03:33:10 +0000233 TheCXXABI.BuildDestructorSignature(D, dtorKind, resultType, argTypes);
John McCall5d865c322010-08-31 07:33:07 +0000234
235 CanQual<FunctionProtoType> FTP = GetFormalType(D);
236 assert(FTP->getNumArgs() == 0 && "dtor with formal parameters");
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +0000237 assert(FTP->isVariadic() == 0 && "dtor with formal parameters");
John McCall5d865c322010-08-31 07:33:07 +0000238
John McCall8dda7b22012-07-07 06:41:13 +0000239 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
John McCall8dda7b22012-07-07 06:41:13 +0000240 return arrangeLLVMFunctionInfo(resultType, argTypes, extInfo,
241 RequiredArgs::All);
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000242}
243
John McCalla729c622012-02-17 03:33:10 +0000244/// Arrange the argument and result information for the declaration or
245/// definition of the given function.
246const CGFunctionInfo &
247CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000248 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000249 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000250 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000251
John McCall2da83a32010-02-26 00:48:12 +0000252 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000253
John McCall2da83a32010-02-26 00:48:12 +0000254 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000255
256 // When declaring a function without a prototype, always use a
257 // non-variadic type.
258 if (isa<FunctionNoProtoType>(FTy)) {
259 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000260 return arrangeLLVMFunctionInfo(noProto->getResultType(), None,
261 noProto->getExtInfo(), RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000262 }
263
John McCall2da83a32010-02-26 00:48:12 +0000264 assert(isa<FunctionProtoType>(FTy));
John McCall8dda7b22012-07-07 06:41:13 +0000265 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>());
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000266}
267
John McCalla729c622012-02-17 03:33:10 +0000268/// Arrange the argument and result information for the declaration or
269/// definition of an Objective-C method.
270const CGFunctionInfo &
271CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
272 // It happens that this is the same as a call with no optional
273 // arguments, except also using the formal 'self' type.
274 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
275}
276
277/// Arrange the argument and result information for the function type
278/// through which to perform a send to the given Objective-C method,
279/// using the given receiver type. The receiver type is not always
280/// the 'self' type of the method or even an Objective-C pointer type.
281/// This is *not* the right method for actually performing such a
282/// message send, due to the possibility of optional arguments.
283const CGFunctionInfo &
284CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
285 QualType receiverType) {
286 SmallVector<CanQualType, 16> argTys;
287 argTys.push_back(Context.getCanonicalParamType(receiverType));
288 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000289 // FIXME: Kill copy?
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +0000290 for (ObjCMethodDecl::param_const_iterator i = MD->param_begin(),
John McCall8ee376f2010-02-24 07:14:12 +0000291 e = MD->param_end(); i != e; ++i) {
John McCalla729c622012-02-17 03:33:10 +0000292 argTys.push_back(Context.getCanonicalParamType((*i)->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000293 }
John McCall31168b02011-06-15 23:02:42 +0000294
295 FunctionType::ExtInfo einfo;
296 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD));
297
David Blaikiebbafb8a2012-03-11 07:00:24 +0000298 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000299 MD->hasAttr<NSReturnsRetainedAttr>())
300 einfo = einfo.withProducesResult(true);
301
John McCalla729c622012-02-17 03:33:10 +0000302 RequiredArgs required =
303 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
304
John McCall8dda7b22012-07-07 06:41:13 +0000305 return arrangeLLVMFunctionInfo(GetReturnType(MD->getResultType()), argTys,
306 einfo, required);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000307}
308
John McCalla729c622012-02-17 03:33:10 +0000309const CGFunctionInfo &
310CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000311 // FIXME: Do we need to handle ObjCMethodDecl?
312 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000313
Anders Carlsson6710c532010-02-06 02:44:09 +0000314 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
John McCalla729c622012-02-17 03:33:10 +0000315 return arrangeCXXConstructorDeclaration(CD, GD.getCtorType());
Anders Carlsson6710c532010-02-06 02:44:09 +0000316
317 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
John McCalla729c622012-02-17 03:33:10 +0000318 return arrangeCXXDestructor(DD, GD.getDtorType());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000319
John McCalla729c622012-02-17 03:33:10 +0000320 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000321}
322
John McCallc818bbb2012-12-07 07:03:17 +0000323/// Arrange a call as unto a free function, except possibly with an
324/// additional number of formal parameters considered required.
325static const CGFunctionInfo &
326arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000327 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000328 const CallArgList &args,
329 const FunctionType *fnType,
330 unsigned numExtraRequiredArgs) {
331 assert(args.size() >= numExtraRequiredArgs);
332
333 // In most cases, there are no optional arguments.
334 RequiredArgs required = RequiredArgs::All;
335
336 // If we have a variadic prototype, the required arguments are the
337 // extra prefix plus the arguments in the prototype.
338 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
339 if (proto->isVariadic())
340 required = RequiredArgs(proto->getNumArgs() + numExtraRequiredArgs);
341
342 // If we don't have a prototype at all, but we're supposed to
343 // explicitly use the variadic convention for unprototyped calls,
344 // treat all of the arguments as required but preserve the nominal
345 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000346 } else if (CGM.getTargetCodeGenInfo()
347 .isNoProtoCallVariadic(args,
348 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000349 required = RequiredArgs(args.size());
350 }
351
352 return CGT.arrangeFreeFunctionCall(fnType->getResultType(), args,
353 fnType->getExtInfo(), required);
354}
355
John McCalla729c622012-02-17 03:33:10 +0000356/// Figure out the rules for calling a function with the given formal
357/// type using the given arguments. The arguments are necessary
358/// because the function might be unprototyped, in which case it's
359/// target-dependent in crazy ways.
360const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000361CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
362 const FunctionType *fnType) {
Mark Lacey23455752013-10-10 20:57:00 +0000363 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 0);
John McCallc818bbb2012-12-07 07:03:17 +0000364}
John McCalla729c622012-02-17 03:33:10 +0000365
John McCallc818bbb2012-12-07 07:03:17 +0000366/// A block function call is essentially a free-function call with an
367/// extra implicit argument.
368const CGFunctionInfo &
369CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
370 const FunctionType *fnType) {
Mark Lacey23455752013-10-10 20:57:00 +0000371 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1);
John McCalla729c622012-02-17 03:33:10 +0000372}
373
374const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000375CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
376 const CallArgList &args,
377 FunctionType::ExtInfo info,
378 RequiredArgs required) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000379 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000380 SmallVector<CanQualType, 16> argTypes;
381 for (CallArgList::const_iterator i = args.begin(), e = args.end();
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000382 i != e; ++i)
John McCalla729c622012-02-17 03:33:10 +0000383 argTypes.push_back(Context.getCanonicalParamType(i->Ty));
John McCall8dda7b22012-07-07 06:41:13 +0000384 return arrangeLLVMFunctionInfo(GetReturnType(resultType), argTypes, info,
385 required);
386}
387
388/// Arrange a call to a C++ method, passing the given arguments.
389const CGFunctionInfo &
390CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
391 const FunctionProtoType *FPT,
392 RequiredArgs required) {
393 // FIXME: Kill copy.
394 SmallVector<CanQualType, 16> argTypes;
395 for (CallArgList::const_iterator i = args.begin(), e = args.end();
396 i != e; ++i)
397 argTypes.push_back(Context.getCanonicalParamType(i->Ty));
398
399 FunctionType::ExtInfo info = FPT->getExtInfo();
John McCall8dda7b22012-07-07 06:41:13 +0000400 return arrangeLLVMFunctionInfo(GetReturnType(FPT->getResultType()),
401 argTypes, info, required);
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000402}
403
John McCalla729c622012-02-17 03:33:10 +0000404const CGFunctionInfo &
405CodeGenTypes::arrangeFunctionDeclaration(QualType resultType,
406 const FunctionArgList &args,
407 const FunctionType::ExtInfo &info,
408 bool isVariadic) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000409 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000410 SmallVector<CanQualType, 16> argTypes;
411 for (FunctionArgList::const_iterator i = args.begin(), e = args.end();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +0000412 i != e; ++i)
John McCalla729c622012-02-17 03:33:10 +0000413 argTypes.push_back(Context.getCanonicalParamType((*i)->getType()));
414
415 RequiredArgs required =
416 (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
John McCall8dda7b22012-07-07 06:41:13 +0000417 return arrangeLLVMFunctionInfo(GetReturnType(resultType), argTypes, info,
418 required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000419}
420
John McCalla729c622012-02-17 03:33:10 +0000421const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000422 return arrangeLLVMFunctionInfo(getContext().VoidTy, None,
John McCall8dda7b22012-07-07 06:41:13 +0000423 FunctionType::ExtInfo(), RequiredArgs::All);
John McCalla738c252011-03-09 04:27:21 +0000424}
425
John McCalla729c622012-02-17 03:33:10 +0000426/// Arrange the argument and result information for an abstract value
427/// of a given function type. This is the method which all of the
428/// above functions ultimately defer to.
429const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000430CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
431 ArrayRef<CanQualType> argTypes,
432 FunctionType::ExtInfo info,
433 RequiredArgs required) {
John McCall2da83a32010-02-26 00:48:12 +0000434#ifndef NDEBUG
John McCalla729c622012-02-17 03:33:10 +0000435 for (ArrayRef<CanQualType>::const_iterator
436 I = argTypes.begin(), E = argTypes.end(); I != E; ++I)
John McCall2da83a32010-02-26 00:48:12 +0000437 assert(I->isCanonicalAsParam());
438#endif
439
John McCalla729c622012-02-17 03:33:10 +0000440 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
John McCallab26cfa2010-02-05 21:31:56 +0000441
Daniel Dunbare0be8292009-02-03 00:07:12 +0000442 // Lookup or create unique function info.
443 llvm::FoldingSetNodeID ID;
John McCalla729c622012-02-17 03:33:10 +0000444 CGFunctionInfo::Profile(ID, info, required, resultType, argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000445
John McCalla729c622012-02-17 03:33:10 +0000446 void *insertPos = 0;
447 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000448 if (FI)
449 return *FI;
450
John McCalla729c622012-02-17 03:33:10 +0000451 // Construct the function info. We co-allocate the ArgInfos.
452 FI = CGFunctionInfo::create(CC, info, resultType, argTypes, required);
453 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000454
John McCalla729c622012-02-17 03:33:10 +0000455 bool inserted = FunctionsBeingProcessed.insert(FI); (void)inserted;
456 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000457
Daniel Dunbar313321e2009-02-03 05:31:23 +0000458 // Compute ABI information.
Chris Lattner22326a12010-07-29 02:31:05 +0000459 getABIInfo().computeInfo(*FI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000460
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000461 // Loop over all of the computed argument and return value info. If any of
462 // them are direct or extend without a specified coerce type, specify the
463 // default now.
John McCalla729c622012-02-17 03:33:10 +0000464 ABIArgInfo &retInfo = FI->getReturnInfo();
465 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == 0)
466 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000467
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000468 for (CGFunctionInfo::arg_iterator I = FI->arg_begin(), E = FI->arg_end();
469 I != E; ++I)
470 if (I->info.canHaveCoerceToType() && I->info.getCoerceToType() == 0)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000471 I->info.setCoerceToType(ConvertType(I->type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000472
John McCalla729c622012-02-17 03:33:10 +0000473 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
474 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000475
Daniel Dunbare0be8292009-02-03 00:07:12 +0000476 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000477}
478
John McCalla729c622012-02-17 03:33:10 +0000479CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
480 const FunctionType::ExtInfo &info,
481 CanQualType resultType,
482 ArrayRef<CanQualType> argTypes,
483 RequiredArgs required) {
484 void *buffer = operator new(sizeof(CGFunctionInfo) +
485 sizeof(ArgInfo) * (argTypes.size() + 1));
486 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
487 FI->CallingConvention = llvmCC;
488 FI->EffectiveCallingConvention = llvmCC;
489 FI->ASTCallingConvention = info.getCC();
490 FI->NoReturn = info.getNoReturn();
491 FI->ReturnsRetained = info.getProducesResult();
492 FI->Required = required;
493 FI->HasRegParm = info.getHasRegParm();
494 FI->RegParm = info.getRegParm();
495 FI->NumArgs = argTypes.size();
496 FI->getArgsBuffer()[0].type = resultType;
497 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
498 FI->getArgsBuffer()[i + 1].type = argTypes[i];
499 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000500}
501
502/***/
503
John McCall85dd2c52011-05-15 02:19:42 +0000504void CodeGenTypes::GetExpandedTypes(QualType type,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000505 SmallVectorImpl<llvm::Type*> &expandedTypes) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000506 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(type)) {
507 uint64_t NumElts = AT->getSize().getZExtValue();
508 for (uint64_t Elt = 0; Elt < NumElts; ++Elt)
509 GetExpandedTypes(AT->getElementType(), expandedTypes);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000510 } else if (const RecordType *RT = type->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000511 const RecordDecl *RD = RT->getDecl();
512 assert(!RD->hasFlexibleArrayMember() &&
513 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000514 if (RD->isUnion()) {
515 // Unions can be here only in degenerative cases - all the fields are same
516 // after flattening. Thus we have to use the "largest" field.
517 const FieldDecl *LargestFD = 0;
518 CharUnits UnionSize = CharUnits::Zero();
519
520 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
521 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +0000522 const FieldDecl *FD = *i;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000523 assert(!FD->isBitField() &&
524 "Cannot expand structure with bit-field members.");
525 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
526 if (UnionSize < FieldSize) {
527 UnionSize = FieldSize;
528 LargestFD = FD;
529 }
530 }
531 if (LargestFD)
532 GetExpandedTypes(LargestFD->getType(), expandedTypes);
533 } else {
534 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
535 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +0000536 assert(!i->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000537 "Cannot expand structure with bit-field members.");
David Blaikie40ed2972012-06-06 20:45:41 +0000538 GetExpandedTypes(i->getType(), expandedTypes);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000539 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000540 }
541 } else if (const ComplexType *CT = type->getAs<ComplexType>()) {
542 llvm::Type *EltTy = ConvertType(CT->getElementType());
543 expandedTypes.push_back(EltTy);
544 expandedTypes.push_back(EltTy);
545 } else
546 expandedTypes.push_back(ConvertType(type));
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000547}
548
Mike Stump11289f42009-09-09 15:08:12 +0000549llvm::Function::arg_iterator
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000550CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
551 llvm::Function::arg_iterator AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000552 assert(LV.isSimple() &&
553 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000554
Bob Wilsone826a2a2011-08-03 05:58:22 +0000555 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
556 unsigned NumElts = AT->getSize().getZExtValue();
557 QualType EltTy = AT->getElementType();
558 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
Eli Friedman7f1ff602012-04-16 03:54:45 +0000559 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, Elt);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000560 LValue LV = MakeAddrLValue(EltAddr, EltTy);
561 AI = ExpandTypeFromArgs(EltTy, LV, AI);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000562 }
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000563 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000564 RecordDecl *RD = RT->getDecl();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000565 if (RD->isUnion()) {
566 // Unions can be here only in degenerative cases - all the fields are same
567 // after flattening. Thus we have to use the "largest" field.
568 const FieldDecl *LargestFD = 0;
569 CharUnits UnionSize = CharUnits::Zero();
Bob Wilsone826a2a2011-08-03 05:58:22 +0000570
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000571 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
572 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +0000573 const FieldDecl *FD = *i;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000574 assert(!FD->isBitField() &&
575 "Cannot expand structure with bit-field members.");
576 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
577 if (UnionSize < FieldSize) {
578 UnionSize = FieldSize;
579 LargestFD = FD;
580 }
581 }
582 if (LargestFD) {
583 // FIXME: What are the right qualifiers here?
Eli Friedman7f1ff602012-04-16 03:54:45 +0000584 LValue SubLV = EmitLValueForField(LV, LargestFD);
585 AI = ExpandTypeFromArgs(LargestFD->getType(), SubLV, AI);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000586 }
587 } else {
588 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
589 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +0000590 FieldDecl *FD = *i;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000591 QualType FT = FD->getType();
592
593 // FIXME: What are the right qualifiers here?
Eli Friedman7f1ff602012-04-16 03:54:45 +0000594 LValue SubLV = EmitLValueForField(LV, FD);
595 AI = ExpandTypeFromArgs(FT, SubLV, AI);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000596 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000597 }
598 } else if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
599 QualType EltTy = CT->getElementType();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000600 llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real");
Bob Wilsone826a2a2011-08-03 05:58:22 +0000601 EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(RealAddr, EltTy));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000602 llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag");
Bob Wilsone826a2a2011-08-03 05:58:22 +0000603 EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(ImagAddr, EltTy));
604 } else {
605 EmitStoreThroughLValue(RValue::get(AI), LV);
606 ++AI;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000607 }
608
609 return AI;
610}
611
Chris Lattner895c52b2010-06-27 06:04:18 +0000612/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +0000613/// accessing some number of bytes out of it, try to gep into the struct to get
614/// at its inner goodness. Dive as deep as possible without entering an element
615/// with an in-memory size smaller than DstSize.
616static llvm::Value *
Chris Lattner895c52b2010-06-27 06:04:18 +0000617EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000618 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +0000619 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +0000620 // We can't dive into a zero-element struct.
621 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000622
Chris Lattner2192fe52011-07-18 04:24:23 +0000623 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000624
Chris Lattner1cd66982010-06-27 05:56:15 +0000625 // If the first elt is at least as large as what we're looking for, or if the
626 // first element is the same size as the whole struct, we can enter it.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000627 uint64_t FirstEltSize =
Micah Villmowdd31ca12012-10-08 16:25:52 +0000628 CGF.CGM.getDataLayout().getTypeAllocSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000629 if (FirstEltSize < DstSize &&
Micah Villmowdd31ca12012-10-08 16:25:52 +0000630 FirstEltSize < CGF.CGM.getDataLayout().getTypeAllocSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +0000631 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000632
Chris Lattner1cd66982010-06-27 05:56:15 +0000633 // GEP into the first element.
634 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000635
Chris Lattner1cd66982010-06-27 05:56:15 +0000636 // If the first element is a struct, recurse.
Chris Lattner2192fe52011-07-18 04:24:23 +0000637 llvm::Type *SrcTy =
Chris Lattner1cd66982010-06-27 05:56:15 +0000638 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000639 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +0000640 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000641
642 return SrcPtr;
643}
644
Chris Lattner055097f2010-06-27 06:26:04 +0000645/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
646/// are either integers or pointers. This does a truncation of the value if it
647/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000648///
649/// This behaves as if the value were coerced through memory, so on big-endian
650/// targets the high bits are preserved in a truncation, while little-endian
651/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +0000652static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +0000653 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +0000654 CodeGenFunction &CGF) {
655 if (Val->getType() == Ty)
656 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000657
Chris Lattner055097f2010-06-27 06:26:04 +0000658 if (isa<llvm::PointerType>(Val->getType())) {
659 // If this is Pointer->Pointer avoid conversion to and from int.
660 if (isa<llvm::PointerType>(Ty))
661 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000662
Chris Lattner055097f2010-06-27 06:26:04 +0000663 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +0000664 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +0000665 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000666
Chris Lattner2192fe52011-07-18 04:24:23 +0000667 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +0000668 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +0000669 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000670
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000671 if (Val->getType() != DestIntTy) {
672 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
673 if (DL.isBigEndian()) {
674 // Preserve the high bits on big-endian targets.
675 // That is what memory coercion does.
676 uint64_t SrcSize = DL.getTypeAllocSizeInBits(Val->getType());
677 uint64_t DstSize = DL.getTypeAllocSizeInBits(DestIntTy);
678 if (SrcSize > DstSize) {
679 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
680 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
681 } else {
682 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
683 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
684 }
685 } else {
686 // Little-endian targets preserve the low bits. No shifts required.
687 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
688 }
689 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000690
Chris Lattner055097f2010-06-27 06:26:04 +0000691 if (isa<llvm::PointerType>(Ty))
692 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
693 return Val;
694}
695
Chris Lattner1cd66982010-06-27 05:56:15 +0000696
697
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000698/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
699/// a pointer to an object of type \arg Ty.
700///
701/// This safely handles the case when the src type is smaller than the
702/// destination type; in this situation the values of bits which not
703/// present in the src are undefined.
704static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000705 llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000706 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000707 llvm::Type *SrcTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000708 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000709
Chris Lattnerd200eda2010-06-28 22:51:39 +0000710 // If SrcTy and Ty are the same, just do a load.
711 if (SrcTy == Ty)
712 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000713
Micah Villmowdd31ca12012-10-08 16:25:52 +0000714 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000715
Chris Lattner2192fe52011-07-18 04:24:23 +0000716 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000717 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000718 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
719 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000720
Micah Villmowdd31ca12012-10-08 16:25:52 +0000721 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000722
Chris Lattner055097f2010-06-27 06:26:04 +0000723 // If the source and destination are integer or pointer types, just do an
724 // extension or truncation to the desired type.
725 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
726 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
727 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
728 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
729 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000730
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000731 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000732 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +0000733 // Generally SrcSize is never greater than DstSize, since this means we are
734 // losing bits. However, this can happen in cases where the structure has
735 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000736 //
Mike Stump18bb9282009-05-16 07:57:57 +0000737 // FIXME: Assert that we aren't truncating non-padding bits when have access
738 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000739 llvm::Value *Casted =
740 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000741 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
742 // FIXME: Use better alignment / avoid requiring aligned load.
743 Load->setAlignment(1);
744 return Load;
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000745 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000746
Chris Lattner3fcc7902010-06-27 01:06:27 +0000747 // Otherwise do coercion through memory. This is stupid, but
748 // simple.
749 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
Manman Ren84b921f2012-11-28 22:08:52 +0000750 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
751 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
752 llvm::Value *SrcCasted = CGF.Builder.CreateBitCast(SrcPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000753 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000754 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
755 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
756 1, false);
Chris Lattner3fcc7902010-06-27 01:06:27 +0000757 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000758}
759
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000760// Function to store a first-class aggregate into memory. We prefer to
761// store the elements rather than the aggregate to be more friendly to
762// fast-isel.
763// FIXME: Do we need to recurse here?
764static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
765 llvm::Value *DestPtr, bool DestIsVolatile,
766 bool LowAlignment) {
767 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +0000768 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000769 dyn_cast<llvm::StructType>(Val->getType())) {
770 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
771 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
772 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
773 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
774 DestIsVolatile);
775 if (LowAlignment)
776 SI->setAlignment(1);
777 }
778 } else {
Bill Wendlingf6af30f2012-03-16 21:45:12 +0000779 llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
780 if (LowAlignment)
781 SI->setAlignment(1);
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000782 }
783}
784
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000785/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
786/// where the source and destination may have different types.
787///
788/// This safely handles the case when the src type is larger than the
789/// destination type; the upper bits of the src will be lost.
790static void CreateCoercedStore(llvm::Value *Src,
791 llvm::Value *DstPtr,
Anders Carlsson17490832009-12-24 20:40:36 +0000792 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000793 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000794 llvm::Type *SrcTy = Src->getType();
795 llvm::Type *DstTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000796 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +0000797 if (SrcTy == DstTy) {
798 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
799 return;
800 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000801
Micah Villmowdd31ca12012-10-08 16:25:52 +0000802 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000803
Chris Lattner2192fe52011-07-18 04:24:23 +0000804 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000805 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
806 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
807 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000808
Chris Lattner055097f2010-06-27 06:26:04 +0000809 // If the source and destination are integer or pointer types, just do an
810 // extension or truncation to the desired type.
811 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
812 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
813 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
814 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
815 return;
816 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000817
Micah Villmowdd31ca12012-10-08 16:25:52 +0000818 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000819
Daniel Dunbar313321e2009-02-03 05:31:23 +0000820 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000821 if (SrcSize <= DstSize) {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000822 llvm::Value *Casted =
823 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000824 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000825 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000826 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000827 // Otherwise do coercion through memory. This is stupid, but
828 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000829
830 // Generally SrcSize is never greater than DstSize, since this means we are
831 // losing bits. However, this can happen in cases where the structure has
832 // additional padding, for example due to a user specified alignment.
833 //
834 // FIXME: Assert that we aren't truncating non-padding bits when have access
835 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000836 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
837 CGF.Builder.CreateStore(Src, Tmp);
Manman Ren84b921f2012-11-28 22:08:52 +0000838 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
839 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
840 llvm::Value *DstCasted = CGF.Builder.CreateBitCast(DstPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000841 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000842 CGF.Builder.CreateMemCpy(DstCasted, Casted,
843 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
844 1, false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000845 }
846}
847
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000848/***/
849
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000850bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000851 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +0000852}
853
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000854bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
855 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
856 switch (BT->getKind()) {
857 default:
858 return false;
859 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +0000860 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000861 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +0000862 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000863 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +0000864 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000865 }
866 }
867
868 return false;
869}
870
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000871bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
872 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
873 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
874 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +0000875 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000876 }
877 }
878
879 return false;
880}
881
Chris Lattnera5f58b02011-07-09 17:41:47 +0000882llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +0000883 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
884 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +0000885}
886
Chris Lattnera5f58b02011-07-09 17:41:47 +0000887llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +0000888CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000889
890 bool Inserted = FunctionsBeingProcessed.insert(&FI); (void)Inserted;
891 assert(Inserted && "Recursively being processed?");
892
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000893 SmallVector<llvm::Type*, 8> argTypes;
Chris Lattner2192fe52011-07-18 04:24:23 +0000894 llvm::Type *resultType = 0;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000895
John McCall85dd2c52011-05-15 02:19:42 +0000896 const ABIArgInfo &retAI = FI.getReturnInfo();
897 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +0000898 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +0000899 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +0000900
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000901 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +0000902 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +0000903 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +0000904 break;
905
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000906 case ABIArgInfo::Indirect: {
John McCall85dd2c52011-05-15 02:19:42 +0000907 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
908 resultType = llvm::Type::getVoidTy(getLLVMContext());
909
910 QualType ret = FI.getReturnType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000911 llvm::Type *ty = ConvertType(ret);
John McCall85dd2c52011-05-15 02:19:42 +0000912 unsigned addressSpace = Context.getTargetAddressSpace(ret);
913 argTypes.push_back(llvm::PointerType::get(ty, addressSpace));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000914 break;
915 }
916
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000917 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +0000918 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000919 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000920 }
Mike Stump11289f42009-09-09 15:08:12 +0000921
John McCallc818bbb2012-12-07 07:03:17 +0000922 // Add in all of the required arguments.
923 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), ie;
924 if (FI.isVariadic()) {
925 ie = it + FI.getRequiredArgs().getNumRequiredArgs();
926 } else {
927 ie = FI.arg_end();
928 }
929 for (; it != ie; ++it) {
John McCall85dd2c52011-05-15 02:19:42 +0000930 const ABIArgInfo &argAI = it->info;
Mike Stump11289f42009-09-09 15:08:12 +0000931
Rafael Espindolafad28de2012-10-24 01:59:00 +0000932 // Insert a padding type to ensure proper alignment.
933 if (llvm::Type *PaddingType = argAI.getPaddingType())
934 argTypes.push_back(PaddingType);
935
John McCall85dd2c52011-05-15 02:19:42 +0000936 switch (argAI.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000937 case ABIArgInfo::Ignore:
938 break;
939
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000940 case ABIArgInfo::Indirect: {
941 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +0000942 llvm::Type *LTy = ConvertTypeForMem(it->type);
John McCall85dd2c52011-05-15 02:19:42 +0000943 argTypes.push_back(LTy->getPointerTo());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000944 break;
945 }
946
947 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +0000948 case ABIArgInfo::Direct: {
Chris Lattner3dd716c2010-06-28 23:44:11 +0000949 // If the coerce-to type is a first class aggregate, flatten it. Either
950 // way is semantically identical, but fast-isel and the optimizer
951 // generally likes scalar values better than FCAs.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000952 llvm::Type *argType = argAI.getCoerceToType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000953 if (llvm::StructType *st = dyn_cast<llvm::StructType>(argType)) {
John McCall85dd2c52011-05-15 02:19:42 +0000954 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
955 argTypes.push_back(st->getElementType(i));
Chris Lattner3dd716c2010-06-28 23:44:11 +0000956 } else {
John McCall85dd2c52011-05-15 02:19:42 +0000957 argTypes.push_back(argType);
Chris Lattner3dd716c2010-06-28 23:44:11 +0000958 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +0000959 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +0000960 }
Mike Stump11289f42009-09-09 15:08:12 +0000961
Daniel Dunbard3674e62008-09-11 01:48:57 +0000962 case ABIArgInfo::Expand:
Chris Lattnera5f58b02011-07-09 17:41:47 +0000963 GetExpandedTypes(it->type, argTypes);
Daniel Dunbard3674e62008-09-11 01:48:57 +0000964 break;
965 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000966 }
967
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000968 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
969 assert(Erased && "Not in set?");
970
John McCalla729c622012-02-17 03:33:10 +0000971 return llvm::FunctionType::get(resultType, argTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +0000972}
973
Chris Lattner2192fe52011-07-18 04:24:23 +0000974llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +0000975 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +0000976 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000977
Chris Lattner8806e322011-07-10 00:18:59 +0000978 if (!isFuncTypeConvertible(FPT))
979 return llvm::StructType::get(getLLVMContext());
980
981 const CGFunctionInfo *Info;
982 if (isa<CXXDestructorDecl>(MD))
John McCalla729c622012-02-17 03:33:10 +0000983 Info = &arrangeCXXDestructor(cast<CXXDestructorDecl>(MD), GD.getDtorType());
Chris Lattner8806e322011-07-10 00:18:59 +0000984 else
John McCalla729c622012-02-17 03:33:10 +0000985 Info = &arrangeCXXMethodDeclaration(MD);
986 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +0000987}
988
Daniel Dunbar3668cb22009-02-02 23:43:58 +0000989void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbard931a872009-02-02 22:03:45 +0000990 const Decl *TargetDecl,
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000991 AttributeListType &PAL,
Bill Wendlingf4d64cb2013-02-22 00:13:35 +0000992 unsigned &CallingConv,
993 bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +0000994 llvm::AttrBuilder FuncAttrs;
995 llvm::AttrBuilder RetAttrs;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +0000996
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000997 CallingConv = FI.getEffectiveCallingConvention();
998
John McCallab26cfa2010-02-05 21:31:56 +0000999 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001000 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001001
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001002 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001003 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001004 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001005 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001006 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001007 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001008 if (TargetDecl->hasAttr<NoReturnAttr>())
1009 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
1010
1011 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
John McCallbe349de2010-07-08 06:48:12 +00001012 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl31ad7542011-03-13 17:09:40 +00001013 if (FPT && FPT->isNothrow(getContext()))
Bill Wendling207f0532012-12-20 19:27:06 +00001014 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith49af6292013-03-05 08:30:04 +00001015 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1016 // These attributes are not inherited by overloads.
1017 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1018 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001019 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001020 }
1021
Eric Christopherbf005ec2011-08-15 22:38:22 +00001022 // 'const' and 'pure' attribute functions are also nounwind.
1023 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001024 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1025 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001026 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001027 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1028 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001029 }
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001030 if (TargetDecl->hasAttr<MallocAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001031 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001032 }
1033
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001034 if (CodeGenOpts.OptimizeSize)
Bill Wendling207f0532012-12-20 19:27:06 +00001035 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
Quentin Colombet5ee5ca12012-10-26 00:29:48 +00001036 if (CodeGenOpts.OptimizeSize == 2)
Bill Wendling207f0532012-12-20 19:27:06 +00001037 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001038 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001039 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001040 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001041 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Devang Patel6e467b12009-06-04 23:32:02 +00001042
Bill Wendling2f81db62013-02-22 20:53:29 +00001043 if (AttrOnCallSite) {
1044 // Attributes that should go on the call site only.
1045 if (!CodeGenOpts.SimplifyLibCalls)
1046 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Bill Wendling706469b2013-02-28 22:49:57 +00001047 } else {
1048 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001049 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001050 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001051 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001052 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001053 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001054 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001055 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001056 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001057 }
1058
Bill Wendlingdabafea2013-03-13 22:24:33 +00001059 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001060 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001061 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001062 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001063 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001064 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001065 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001066 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001067 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001068 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001069 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001070 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001071
Bill Wendlingd8f49502013-08-01 21:41:02 +00001072 if (!CodeGenOpts.StackRealignment)
1073 FuncAttrs.addAttribute("no-realign-stack");
Bill Wendling985d1c52013-02-15 21:30:01 +00001074 }
1075
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001076 QualType RetTy = FI.getReturnType();
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001077 unsigned Index = 1;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001078 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001079 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001080 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001081 if (RetTy->hasSignedIntegerRepresentation())
1082 RetAttrs.addAttribute(llvm::Attribute::SExt);
1083 else if (RetTy->hasUnsignedIntegerRepresentation())
1084 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001085 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001086 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001087 if (RetAI.getInReg())
1088 RetAttrs.addAttribute(llvm::Attribute::InReg);
1089 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001090 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001091 break;
1092
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001093 case ABIArgInfo::Indirect: {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001094 llvm::AttrBuilder SRETAttrs;
Bill Wendling207f0532012-12-20 19:27:06 +00001095 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001096 if (RetAI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001097 SRETAttrs.addAttribute(llvm::Attribute::InReg);
Bill Wendlinga7912f82012-10-10 07:36:56 +00001098 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001099 AttributeSet::get(getLLVMContext(), Index, SRETAttrs));
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001100
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001101 ++Index;
Daniel Dunbarc2304432009-03-18 19:51:01 +00001102 // sret disables readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001103 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1104 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001105 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001106 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001107
Daniel Dunbard3674e62008-09-11 01:48:57 +00001108 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001109 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001110 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001111
Bill Wendlinga7912f82012-10-10 07:36:56 +00001112 if (RetAttrs.hasAttributes())
1113 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001114 AttributeSet::get(getLLVMContext(),
1115 llvm::AttributeSet::ReturnIndex,
1116 RetAttrs));
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001117
Mike Stump11289f42009-09-09 15:08:12 +00001118 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
Daniel Dunbar313321e2009-02-03 05:31:23 +00001119 ie = FI.arg_end(); it != ie; ++it) {
1120 QualType ParamType = it->type;
1121 const ABIArgInfo &AI = it->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001122 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001123
Rafael Espindolafad28de2012-10-24 01:59:00 +00001124 if (AI.getPaddingType()) {
Bill Wendling290d9522013-01-27 02:46:53 +00001125 if (AI.getPaddingInReg())
1126 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index,
1127 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001128 // Increment Index if there is padding.
1129 ++Index;
1130 }
1131
John McCall39ec71f2010-03-27 00:47:27 +00001132 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1133 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001134 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001135 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001136 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001137 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001138 Attrs.addAttribute(llvm::Attribute::SExt);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001139 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001140 Attrs.addAttribute(llvm::Attribute::ZExt);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001141 // FALL THROUGH
1142 case ABIArgInfo::Direct:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001143 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001144 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001145
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001146 // FIXME: handle sseregparm someday...
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001147
Chris Lattner2192fe52011-07-18 04:24:23 +00001148 if (llvm::StructType *STy =
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001149 dyn_cast<llvm::StructType>(AI.getCoerceToType())) {
1150 unsigned Extra = STy->getNumElements()-1; // 1 will be added below.
Bill Wendlinga7912f82012-10-10 07:36:56 +00001151 if (Attrs.hasAttributes())
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001152 for (unsigned I = 0; I < Extra; ++I)
Bill Wendling290d9522013-01-27 02:46:53 +00001153 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index + I,
1154 Attrs));
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001155 Index += Extra;
1156 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001157 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001158
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001159 case ABIArgInfo::Indirect:
Rafael Espindola703c47f2012-10-19 05:04:37 +00001160 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001161 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001162
Anders Carlsson20759ad2009-09-16 15:53:40 +00001163 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001164 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001165
Bill Wendlinga7912f82012-10-10 07:36:56 +00001166 Attrs.addAlignmentAttr(AI.getIndirectAlign());
1167
Daniel Dunbarc2304432009-03-18 19:51:01 +00001168 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001169 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1170 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001171 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001172
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001173 case ABIArgInfo::Ignore:
1174 // Skip increment, no matching LLVM parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001175 continue;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001176
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001177 case ABIArgInfo::Expand: {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001178 SmallVector<llvm::Type*, 8> types;
Mike Stump18bb9282009-05-16 07:57:57 +00001179 // FIXME: This is rather inefficient. Do we ever actually need to do
1180 // anything here? The result should be just reconstructed on the other
1181 // side, so extension should be a non-issue.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001182 getTypes().GetExpandedTypes(ParamType, types);
John McCall85dd2c52011-05-15 02:19:42 +00001183 Index += types.size();
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001184 continue;
1185 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001186 }
Mike Stump11289f42009-09-09 15:08:12 +00001187
Bill Wendlinga7912f82012-10-10 07:36:56 +00001188 if (Attrs.hasAttributes())
Bill Wendling290d9522013-01-27 02:46:53 +00001189 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index, Attrs));
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001190 ++Index;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001191 }
Bill Wendlinga7912f82012-10-10 07:36:56 +00001192 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001193 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001194 AttributeSet::get(getLLVMContext(),
1195 llvm::AttributeSet::FunctionIndex,
1196 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001197}
1198
John McCalla738c252011-03-09 04:27:21 +00001199/// An argument came in as a promoted argument; demote it back to its
1200/// declared type.
1201static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1202 const VarDecl *var,
1203 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001204 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001205
1206 // This can happen with promotions that actually don't change the
1207 // underlying type, like the enum promotions.
1208 if (value->getType() == varType) return value;
1209
1210 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1211 && "unexpected promotion type");
1212
1213 if (isa<llvm::IntegerType>(varType))
1214 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1215
1216 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1217}
1218
Daniel Dunbard931a872009-02-02 22:03:45 +00001219void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1220 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00001221 const FunctionArgList &Args) {
John McCallcaa19452009-07-28 01:00:58 +00001222 // If this is an implicit-return-zero function, go ahead and
1223 // initialize the return value. TODO: it might be nice to have
1224 // a more general mechanism for this that didn't require synthesized
1225 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00001226 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00001227 if (FD->hasImplicitReturnZero()) {
1228 QualType RetTy = FD->getResultType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001229 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00001230 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00001231 Builder.CreateStore(Zero, ReturnValue);
1232 }
1233 }
1234
Mike Stump18bb9282009-05-16 07:57:57 +00001235 // FIXME: We no longer need the types from FunctionArgList; lift up and
1236 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00001237
Daniel Dunbar613855c2008-09-09 23:27:19 +00001238 // Emit allocs for param decls. Give the LLVM Argument nodes names.
1239 llvm::Function::arg_iterator AI = Fn->arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00001240
Daniel Dunbar613855c2008-09-09 23:27:19 +00001241 // Name the struct return argument.
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001242 if (CGM.ReturnTypeUsesSRet(FI)) {
Daniel Dunbar613855c2008-09-09 23:27:19 +00001243 AI->setName("agg.result");
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001244 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1245 AI->getArgNo() + 1,
1246 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00001247 ++AI;
1248 }
Mike Stump11289f42009-09-09 15:08:12 +00001249
Reid Kleckner739756c2013-12-04 19:23:12 +00001250 // Create a pointer value for every parameter declaration. This usually
1251 // entails copying one or more LLVM IR arguments into an alloca. Don't push
1252 // any cleanups or do anything that might unwind. We do that separately, so
1253 // we can push the cleanups in the correct order for the ABI.
1254 SmallVector<llvm::Value *, 16> ArgVals;
1255 ArgVals.reserve(Args.size());
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00001256 assert(FI.arg_size() == Args.size() &&
1257 "Mismatch between function signature & arguments.");
Devang Patel68a15252011-03-03 20:13:15 +00001258 unsigned ArgNo = 1;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001259 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Devang Patel68a15252011-03-03 20:13:15 +00001260 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
1261 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00001262 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001263 QualType Ty = info_it->type;
1264 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001265
John McCalla738c252011-03-09 04:27:21 +00001266 bool isPromoted =
1267 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1268
Rafael Espindolafad28de2012-10-24 01:59:00 +00001269 // Skip the dummy padding argument.
1270 if (ArgI.getPaddingType())
1271 ++AI;
1272
Daniel Dunbard3674e62008-09-11 01:48:57 +00001273 switch (ArgI.getKind()) {
Daniel Dunbar747865a2009-02-05 09:16:39 +00001274 case ABIArgInfo::Indirect: {
Chris Lattner3dd716c2010-06-28 23:44:11 +00001275 llvm::Value *V = AI;
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001276
John McCall47fb9502013-03-07 21:37:08 +00001277 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001278 // Aggregates and complex variables are accessed by reference. All we
1279 // need to do is realign the value, if requested
1280 if (ArgI.getIndirectRealign()) {
1281 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1282
1283 // Copy from the incoming argument pointer to the temporary with the
1284 // appropriate alignment.
1285 //
1286 // FIXME: We should have a common utility for generating an aggregate
1287 // copy.
Chris Lattner2192fe52011-07-18 04:24:23 +00001288 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyck705ba072011-01-19 01:58:38 +00001289 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumidd634362011-03-10 14:02:21 +00001290 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1291 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1292 Builder.CreateMemCpy(Dst,
1293 Src,
Ken Dyck705ba072011-01-19 01:58:38 +00001294 llvm::ConstantInt::get(IntPtrTy,
1295 Size.getQuantity()),
Benjamin Krameracc6b4e2010-12-30 00:13:21 +00001296 ArgI.getIndirectAlign(),
1297 false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001298 V = AlignedTemp;
1299 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00001300 } else {
1301 // Load scalar value from indirect argument.
Ken Dyck705ba072011-01-19 01:58:38 +00001302 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
Nick Lewycky2d84e842013-10-02 02:29:49 +00001303 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty,
1304 Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001305
1306 if (isPromoted)
1307 V = emitArgumentDemotion(*this, Arg, V);
Daniel Dunbar747865a2009-02-05 09:16:39 +00001308 }
Reid Kleckner739756c2013-12-04 19:23:12 +00001309 ArgVals.push_back(V);
Daniel Dunbar747865a2009-02-05 09:16:39 +00001310 break;
1311 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001312
1313 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001314 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00001315
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001316 // If we have the trivial case, handle it with no muss and fuss.
1317 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001318 ArgI.getCoerceToType() == ConvertType(Ty) &&
1319 ArgI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001320 assert(AI != Fn->arg_end() && "Argument mismatch!");
1321 llvm::Value *V = AI;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001322
Bill Wendling507c3512012-10-16 05:23:44 +00001323 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001324 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1325 AI->getArgNo() + 1,
1326 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00001327
Chris Lattner7369c142011-07-20 06:29:00 +00001328 // Ensure the argument is the correct type.
1329 if (V->getType() != ArgI.getCoerceToType())
1330 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1331
John McCalla738c252011-03-09 04:27:21 +00001332 if (isPromoted)
1333 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00001334
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001335 if (const CXXMethodDecl *MD =
1336 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001337 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001338 V = CGM.getCXXABI().
1339 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001340 }
1341
Rafael Espindola8778c282012-11-29 16:09:03 +00001342 // Because of merging of function types from multiple decls it is
1343 // possible for the type of an argument to not match the corresponding
1344 // type in the function type. Since we are codegening the callee
1345 // in here, add a cast to the argument type.
1346 llvm::Type *LTy = ConvertType(Arg->getType());
1347 if (V->getType() != LTy)
1348 V = Builder.CreateBitCast(V, LTy);
1349
Reid Kleckner739756c2013-12-04 19:23:12 +00001350 ArgVals.push_back(V);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001351 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00001352 }
Mike Stump11289f42009-09-09 15:08:12 +00001353
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001354 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001355
Chris Lattnerff941a62010-07-28 18:24:28 +00001356 // The alignment we need to use is the max of the requested alignment for
1357 // the argument plus the alignment required by our access code below.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001358 unsigned AlignmentToUse =
Micah Villmowdd31ca12012-10-08 16:25:52 +00001359 CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerff941a62010-07-28 18:24:28 +00001360 AlignmentToUse = std::max(AlignmentToUse,
1361 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001362
Chris Lattnerff941a62010-07-28 18:24:28 +00001363 Alloca->setAlignment(AlignmentToUse);
Chris Lattnerc401de92010-07-05 20:21:00 +00001364 llvm::Value *V = Alloca;
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001365 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001366
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001367 // If the value is offset in memory, apply the offset now.
1368 if (unsigned Offs = ArgI.getDirectOffset()) {
1369 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1370 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001371 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001372 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1373 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001374
Chris Lattner15ec3612010-06-29 00:06:42 +00001375 // If the coerce-to type is a first class aggregate, we flatten it and
1376 // pass the elements. Either way is semantically identical, but fast-isel
1377 // and the optimizer generally likes scalar values better than FCAs.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001378 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
1379 if (STy && STy->getNumElements() > 1) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001380 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001381 llvm::Type *DstTy =
1382 cast<llvm::PointerType>(Ptr->getType())->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00001383 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001384
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001385 if (SrcSize <= DstSize) {
1386 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1387
1388 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1389 assert(AI != Fn->arg_end() && "Argument mismatch!");
1390 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1391 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
1392 Builder.CreateStore(AI++, EltPtr);
1393 }
1394 } else {
1395 llvm::AllocaInst *TempAlloca =
1396 CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1397 TempAlloca->setAlignment(AlignmentToUse);
1398 llvm::Value *TempV = TempAlloca;
1399
1400 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1401 assert(AI != Fn->arg_end() && "Argument mismatch!");
1402 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1403 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(TempV, 0, i);
1404 Builder.CreateStore(AI++, EltPtr);
1405 }
1406
1407 Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
Chris Lattner15ec3612010-06-29 00:06:42 +00001408 }
1409 } else {
1410 // Simple case, just do a coerced store of the argument into the alloca.
1411 assert(AI != Fn->arg_end() && "Argument mismatch!");
Chris Lattner9e748e92010-06-29 00:14:52 +00001412 AI->setName(Arg->getName() + ".coerce");
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001413 CreateCoercedStore(AI++, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00001414 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001415
1416
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001417 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00001418 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001419 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001420 if (isPromoted)
1421 V = emitArgumentDemotion(*this, Arg, V);
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00001422 }
Reid Kleckner739756c2013-12-04 19:23:12 +00001423 ArgVals.push_back(V);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001424 continue; // Skip ++AI increment, already done.
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001425 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001426
1427 case ABIArgInfo::Expand: {
1428 // If this structure was expanded into multiple arguments then
1429 // we need to create a temporary and reconstruct it from the
1430 // arguments.
Eli Friedman3d9f47f2011-11-03 21:39:02 +00001431 llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
Eli Friedmana0544d62011-12-03 04:14:32 +00001432 CharUnits Align = getContext().getDeclAlign(Arg);
1433 Alloca->setAlignment(Align.getQuantity());
1434 LValue LV = MakeAddrLValue(Alloca, Ty, Align);
Eli Friedman3d9f47f2011-11-03 21:39:02 +00001435 llvm::Function::arg_iterator End = ExpandTypeFromArgs(Ty, LV, AI);
Reid Kleckner739756c2013-12-04 19:23:12 +00001436 ArgVals.push_back(Alloca);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001437
1438 // Name the arguments used in expansion and increment AI.
1439 unsigned Index = 0;
1440 for (; AI != End; ++AI, ++Index)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001441 AI->setName(Arg->getName() + "." + Twine(Index));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001442 continue;
1443 }
1444
1445 case ABIArgInfo::Ignore:
1446 // Initialize the local variable appropriately.
John McCall47fb9502013-03-07 21:37:08 +00001447 if (!hasScalarEvaluationKind(Ty))
Reid Kleckner739756c2013-12-04 19:23:12 +00001448 ArgVals.push_back(CreateMemTemp(Ty));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001449 else
Reid Kleckner739756c2013-12-04 19:23:12 +00001450 ArgVals.push_back(llvm::UndefValue::get(ConvertType(Arg->getType())));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001451
1452 // Skip increment, no matching LLVM parameter.
1453 continue;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001454 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001455
1456 ++AI;
Daniel Dunbar613855c2008-09-09 23:27:19 +00001457 }
1458 assert(AI == Fn->arg_end() && "Argument mismatch!");
Reid Kleckner739756c2013-12-04 19:23:12 +00001459
1460 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1461 for (int I = Args.size() - 1; I >= 0; --I)
1462 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
1463 } else {
1464 for (unsigned I = 0, E = Args.size(); I != E; ++I)
1465 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
1466 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00001467}
1468
John McCallffa2c1a2012-01-29 07:46:59 +00001469static void eraseUnusedBitCasts(llvm::Instruction *insn) {
1470 while (insn->use_empty()) {
1471 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
1472 if (!bitcast) return;
1473
1474 // This is "safe" because we would have used a ConstantExpr otherwise.
1475 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
1476 bitcast->eraseFromParent();
1477 }
1478}
1479
John McCall31168b02011-06-15 23:02:42 +00001480/// Try to emit a fused autorelease of a return result.
1481static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
1482 llvm::Value *result) {
1483 // We must be immediately followed the cast.
1484 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
1485 if (BB->empty()) return 0;
1486 if (&BB->back() != result) return 0;
1487
Chris Lattner2192fe52011-07-18 04:24:23 +00001488 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00001489
1490 // result is in a BasicBlock and is therefore an Instruction.
1491 llvm::Instruction *generator = cast<llvm::Instruction>(result);
1492
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001493 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00001494
1495 // Look for:
1496 // %generator = bitcast %type1* %generator2 to %type2*
1497 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
1498 // We would have emitted this as a constant if the operand weren't
1499 // an Instruction.
1500 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
1501
1502 // Require the generator to be immediately followed by the cast.
1503 if (generator->getNextNode() != bitcast)
1504 return 0;
1505
1506 insnsToKill.push_back(bitcast);
1507 }
1508
1509 // Look for:
1510 // %generator = call i8* @objc_retain(i8* %originalResult)
1511 // or
1512 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
1513 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
1514 if (!call) return 0;
1515
1516 bool doRetainAutorelease;
1517
1518 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
1519 doRetainAutorelease = true;
1520 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
1521 .objc_retainAutoreleasedReturnValue) {
1522 doRetainAutorelease = false;
1523
John McCallcfa4e9b2012-09-07 23:30:50 +00001524 // If we emitted an assembly marker for this call (and the
1525 // ARCEntrypoints field should have been set if so), go looking
1526 // for that call. If we can't find it, we can't do this
1527 // optimization. But it should always be the immediately previous
1528 // instruction, unless we needed bitcasts around the call.
1529 if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
1530 llvm::Instruction *prev = call->getPrevNode();
1531 assert(prev);
1532 if (isa<llvm::BitCastInst>(prev)) {
1533 prev = prev->getPrevNode();
1534 assert(prev);
1535 }
1536 assert(isa<llvm::CallInst>(prev));
1537 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
1538 CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
1539 insnsToKill.push_back(prev);
1540 }
John McCall31168b02011-06-15 23:02:42 +00001541 } else {
1542 return 0;
1543 }
1544
1545 result = call->getArgOperand(0);
1546 insnsToKill.push_back(call);
1547
1548 // Keep killing bitcasts, for sanity. Note that we no longer care
1549 // about precise ordering as long as there's exactly one use.
1550 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
1551 if (!bitcast->hasOneUse()) break;
1552 insnsToKill.push_back(bitcast);
1553 result = bitcast->getOperand(0);
1554 }
1555
1556 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001557 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00001558 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
1559 (*i)->eraseFromParent();
1560
1561 // Do the fused retain/autorelease if we were asked to.
1562 if (doRetainAutorelease)
1563 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
1564
1565 // Cast back to the result type.
1566 return CGF.Builder.CreateBitCast(result, resultType);
1567}
1568
John McCallffa2c1a2012-01-29 07:46:59 +00001569/// If this is a +1 of the value of an immutable 'self', remove it.
1570static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
1571 llvm::Value *result) {
1572 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00001573 const ObjCMethodDecl *method =
1574 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCallffa2c1a2012-01-29 07:46:59 +00001575 if (!method) return 0;
1576 const VarDecl *self = method->getSelfDecl();
1577 if (!self->getType().isConstQualified()) return 0;
1578
1579 // Look for a retain call.
1580 llvm::CallInst *retainCall =
1581 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
1582 if (!retainCall ||
1583 retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
1584 return 0;
1585
1586 // Look for an ordinary load of 'self'.
1587 llvm::Value *retainedValue = retainCall->getArgOperand(0);
1588 llvm::LoadInst *load =
1589 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
1590 if (!load || load->isAtomic() || load->isVolatile() ||
1591 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
1592 return 0;
1593
1594 // Okay! Burn it all down. This relies for correctness on the
1595 // assumption that the retain is emitted as part of the return and
1596 // that thereafter everything is used "linearly".
1597 llvm::Type *resultType = result->getType();
1598 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
1599 assert(retainCall->use_empty());
1600 retainCall->eraseFromParent();
1601 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
1602
1603 return CGF.Builder.CreateBitCast(load, resultType);
1604}
1605
John McCall31168b02011-06-15 23:02:42 +00001606/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00001607///
1608/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00001609static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
1610 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00001611 // If we're returning 'self', kill the initial retain. This is a
1612 // heuristic attempt to "encourage correctness" in the really unfortunate
1613 // case where we have a return of self during a dealloc and we desperately
1614 // need to avoid the possible autorelease.
1615 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
1616 return self;
1617
John McCall31168b02011-06-15 23:02:42 +00001618 // At -O0, try to emit a fused retain/autorelease.
1619 if (CGF.shouldUseFusedARCCalls())
1620 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
1621 return fused;
1622
1623 return CGF.EmitARCAutoreleaseReturnValue(result);
1624}
1625
John McCall6e1c0122012-01-29 02:35:02 +00001626/// Heuristically search for a dominating store to the return-value slot.
1627static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
1628 // If there are multiple uses of the return-value slot, just check
1629 // for something immediately preceding the IP. Sometimes this can
1630 // happen with how we generate implicit-returns; it can also happen
1631 // with noreturn cleanups.
1632 if (!CGF.ReturnValue->hasOneUse()) {
1633 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
1634 if (IP->empty()) return 0;
1635 llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back());
1636 if (!store) return 0;
1637 if (store->getPointerOperand() != CGF.ReturnValue) return 0;
1638 assert(!store->isAtomic() && !store->isVolatile()); // see below
1639 return store;
1640 }
1641
1642 llvm::StoreInst *store =
1643 dyn_cast<llvm::StoreInst>(CGF.ReturnValue->use_back());
1644 if (!store) return 0;
1645
1646 // These aren't actually possible for non-coerced returns, and we
1647 // only care about non-coerced returns on this code path.
1648 assert(!store->isAtomic() && !store->isVolatile());
1649
1650 // Now do a first-and-dirty dominance check: just walk up the
1651 // single-predecessors chain from the current insertion point.
1652 llvm::BasicBlock *StoreBB = store->getParent();
1653 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
1654 while (IP != StoreBB) {
1655 if (!(IP = IP->getSinglePredecessor()))
1656 return 0;
1657 }
1658
1659 // Okay, the store's basic block dominates the insertion point; we
1660 // can do our thing.
1661 return store;
1662}
1663
Adrian Prantl3be10542013-05-02 17:30:20 +00001664void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001665 bool EmitRetDbgLoc,
1666 SourceLocation EndLoc) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001667 // Functions with no result always return void.
Chris Lattner726b3d02010-06-26 23:13:19 +00001668 if (ReturnValue == 0) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001669 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00001670 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001671 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00001672
Dan Gohman481e40c2010-07-20 20:13:52 +00001673 llvm::DebugLoc RetDbgLoc;
Chris Lattner726b3d02010-06-26 23:13:19 +00001674 llvm::Value *RV = 0;
1675 QualType RetTy = FI.getReturnType();
1676 const ABIArgInfo &RetAI = FI.getReturnInfo();
1677
1678 switch (RetAI.getKind()) {
Daniel Dunbar03816342010-08-21 02:24:36 +00001679 case ABIArgInfo::Indirect: {
John McCall47fb9502013-03-07 21:37:08 +00001680 switch (getEvaluationKind(RetTy)) {
1681 case TEK_Complex: {
1682 ComplexPairTy RT =
Nick Lewycky2d84e842013-10-02 02:29:49 +00001683 EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
1684 EndLoc);
John McCall47fb9502013-03-07 21:37:08 +00001685 EmitStoreOfComplex(RT,
1686 MakeNaturalAlignAddrLValue(CurFn->arg_begin(), RetTy),
1687 /*isInit*/ true);
1688 break;
1689 }
1690 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00001691 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00001692 break;
1693 case TEK_Scalar:
1694 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
1695 MakeNaturalAlignAddrLValue(CurFn->arg_begin(), RetTy),
1696 /*isInit*/ true);
1697 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00001698 }
1699 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00001700 }
Chris Lattner726b3d02010-06-26 23:13:19 +00001701
1702 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001703 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001704 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
1705 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001706 // The internal return value temp always will have pointer-to-return-type
1707 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001708
John McCall6e1c0122012-01-29 02:35:02 +00001709 // If there is a dominating store to ReturnValue, we can elide
1710 // the load, zap the store, and usually zap the alloca.
1711 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00001712 // Reuse the debug location from the store unless there is
1713 // cleanup code to be emitted between the store and return
1714 // instruction.
1715 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00001716 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001717 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001718 RV = SI->getValueOperand();
1719 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001720
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001721 // If that was the only use of the return value, nuke it as well now.
1722 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
1723 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
1724 ReturnValue = 0;
1725 }
John McCall6e1c0122012-01-29 02:35:02 +00001726
1727 // Otherwise, we have to do a simple load.
1728 } else {
1729 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00001730 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001731 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001732 llvm::Value *V = ReturnValue;
1733 // If the value is offset in memory, apply the offset now.
1734 if (unsigned Offs = RetAI.getDirectOffset()) {
1735 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
1736 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001737 V = Builder.CreateBitCast(V,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001738 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
1739 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001740
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001741 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00001742 }
John McCall31168b02011-06-15 23:02:42 +00001743
1744 // In ARC, end functions that return a retainable type with a call
1745 // to objc_autoreleaseReturnValue.
1746 if (AutoreleaseResult) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001747 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001748 !FI.isReturnsRetained() &&
1749 RetTy->isObjCRetainableType());
1750 RV = emitAutoreleaseOfResult(*this, RV);
1751 }
1752
Chris Lattner726b3d02010-06-26 23:13:19 +00001753 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00001754
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001755 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00001756 break;
1757
1758 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001759 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00001760 }
1761
Daniel Dunbar6696e222010-06-30 21:27:58 +00001762 llvm::Instruction *Ret = RV ? Builder.CreateRet(RV) : Builder.CreateRetVoid();
Devang Patel65497582010-07-21 18:08:50 +00001763 if (!RetDbgLoc.isUnknown())
1764 Ret->setDebugLoc(RetDbgLoc);
Daniel Dunbar613855c2008-09-09 23:27:19 +00001765}
1766
John McCall32ea9692011-03-11 20:59:21 +00001767void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001768 const VarDecl *param,
1769 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00001770 // StartFunction converted the ABI-lowered parameter(s) into a
1771 // local alloca. We need to turn that into an r-value suitable
1772 // for EmitCall.
John McCall32ea9692011-03-11 20:59:21 +00001773 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00001774
John McCall32ea9692011-03-11 20:59:21 +00001775 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001776
John McCall23f66262010-05-26 22:34:26 +00001777 // For the most part, we just need to load the alloca, except:
1778 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall47fb9502013-03-07 21:37:08 +00001779 // 2) references to non-scalars are pointers directly to the aggregate.
1780 // I don't know why references to scalars are different here.
John McCall32ea9692011-03-11 20:59:21 +00001781 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall47fb9502013-03-07 21:37:08 +00001782 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall32ea9692011-03-11 20:59:21 +00001783 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00001784
1785 // Locals which are references to scalars are represented
1786 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00001787 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00001788 }
1789
Nick Lewycky2d84e842013-10-02 02:29:49 +00001790 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00001791}
1792
John McCall31168b02011-06-15 23:02:42 +00001793static bool isProvablyNull(llvm::Value *addr) {
1794 return isa<llvm::ConstantPointerNull>(addr);
1795}
1796
1797static bool isProvablyNonNull(llvm::Value *addr) {
1798 return isa<llvm::AllocaInst>(addr);
1799}
1800
1801/// Emit the actual writing-back of a writeback.
1802static void emitWriteback(CodeGenFunction &CGF,
1803 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00001804 const LValue &srcLV = writeback.Source;
1805 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00001806 assert(!isProvablyNull(srcAddr) &&
1807 "shouldn't have writeback for provably null argument");
1808
1809 llvm::BasicBlock *contBB = 0;
1810
1811 // If the argument wasn't provably non-null, we need to null check
1812 // before doing the store.
1813 bool provablyNonNull = isProvablyNonNull(srcAddr);
1814 if (!provablyNonNull) {
1815 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
1816 contBB = CGF.createBasicBlock("icr.done");
1817
1818 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
1819 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
1820 CGF.EmitBlock(writebackBB);
1821 }
1822
1823 // Load the value to writeback.
1824 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
1825
1826 // Cast it back, in case we're writing an id to a Foo* or something.
1827 value = CGF.Builder.CreateBitCast(value,
1828 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
1829 "icr.writeback-cast");
1830
1831 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00001832
1833 // If we have a "to use" value, it's something we need to emit a use
1834 // of. This has to be carefully threaded in: if it's done after the
1835 // release it's potentially undefined behavior (and the optimizer
1836 // will ignore it), and if it happens before the retain then the
1837 // optimizer could move the release there.
1838 if (writeback.ToUse) {
1839 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
1840
1841 // Retain the new value. No need to block-copy here: the block's
1842 // being passed up the stack.
1843 value = CGF.EmitARCRetainNonBlock(value);
1844
1845 // Emit the intrinsic use here.
1846 CGF.EmitARCIntrinsicUse(writeback.ToUse);
1847
1848 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00001849 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00001850
1851 // Put the new value in place (primitively).
1852 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
1853
1854 // Release the old value.
1855 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
1856
1857 // Otherwise, we can just do a normal lvalue store.
1858 } else {
1859 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
1860 }
John McCall31168b02011-06-15 23:02:42 +00001861
1862 // Jump to the continuation block.
1863 if (!provablyNonNull)
1864 CGF.EmitBlock(contBB);
1865}
1866
1867static void emitWritebacks(CodeGenFunction &CGF,
1868 const CallArgList &args) {
1869 for (CallArgList::writeback_iterator
1870 i = args.writeback_begin(), e = args.writeback_end(); i != e; ++i)
1871 emitWriteback(CGF, *i);
1872}
1873
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001874static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
1875 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00001876 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001877 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
1878 CallArgs.getCleanupsToDeactivate();
1879 // Iterate in reverse to increase the likelihood of popping the cleanup.
1880 for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
1881 I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
1882 CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
1883 I->IsActiveIP->eraseFromParent();
1884 }
1885}
1886
John McCalleff18842013-03-23 02:35:54 +00001887static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
1888 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
1889 if (uop->getOpcode() == UO_AddrOf)
1890 return uop->getSubExpr();
1891 return 0;
1892}
1893
John McCall31168b02011-06-15 23:02:42 +00001894/// Emit an argument that's being passed call-by-writeback. That is,
1895/// we are passing the address of
1896static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
1897 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00001898 LValue srcLV;
1899
1900 // Make an optimistic effort to emit the address as an l-value.
1901 // This can fail if the the argument expression is more complicated.
1902 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
1903 srcLV = CGF.EmitLValue(lvExpr);
1904
1905 // Otherwise, just emit it as a scalar.
1906 } else {
1907 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
1908
1909 QualType srcAddrType =
1910 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
1911 srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
1912 }
1913 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00001914
1915 // The dest and src types don't necessarily match in LLVM terms
1916 // because of the crazy ObjC compatibility rules.
1917
Chris Lattner2192fe52011-07-18 04:24:23 +00001918 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00001919 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
1920
1921 // If the address is a constant null, just pass the appropriate null.
1922 if (isProvablyNull(srcAddr)) {
1923 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
1924 CRE->getType());
1925 return;
1926 }
1927
John McCall31168b02011-06-15 23:02:42 +00001928 // Create the temporary.
1929 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
1930 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001931 // Loading an l-value can introduce a cleanup if the l-value is __weak,
1932 // and that cleanup will be conditional if we can't prove that the l-value
1933 // isn't null, so we need to register a dominating point so that the cleanups
1934 // system will make valid IR.
1935 CodeGenFunction::ConditionalEvaluation condEval(CGF);
1936
John McCall31168b02011-06-15 23:02:42 +00001937 // Zero-initialize it if we're not doing a copy-initialization.
1938 bool shouldCopy = CRE->shouldCopy();
1939 if (!shouldCopy) {
1940 llvm::Value *null =
1941 llvm::ConstantPointerNull::get(
1942 cast<llvm::PointerType>(destType->getElementType()));
1943 CGF.Builder.CreateStore(null, temp);
1944 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001945
John McCall31168b02011-06-15 23:02:42 +00001946 llvm::BasicBlock *contBB = 0;
John McCalleff18842013-03-23 02:35:54 +00001947 llvm::BasicBlock *originBB = 0;
John McCall31168b02011-06-15 23:02:42 +00001948
1949 // If the address is *not* known to be non-null, we need to switch.
1950 llvm::Value *finalArgument;
1951
1952 bool provablyNonNull = isProvablyNonNull(srcAddr);
1953 if (provablyNonNull) {
1954 finalArgument = temp;
1955 } else {
1956 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
1957
1958 finalArgument = CGF.Builder.CreateSelect(isNull,
1959 llvm::ConstantPointerNull::get(destType),
1960 temp, "icr.argument");
1961
1962 // If we need to copy, then the load has to be conditional, which
1963 // means we need control flow.
1964 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00001965 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00001966 contBB = CGF.createBasicBlock("icr.cont");
1967 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
1968 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
1969 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001970 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00001971 }
1972 }
1973
John McCalleff18842013-03-23 02:35:54 +00001974 llvm::Value *valueToUse = 0;
1975
John McCall31168b02011-06-15 23:02:42 +00001976 // Perform a copy if necessary.
1977 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001978 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00001979 assert(srcRV.isScalar());
1980
1981 llvm::Value *src = srcRV.getScalarVal();
1982 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
1983 "icr.cast");
1984
1985 // Use an ordinary store, not a store-to-lvalue.
1986 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00001987
1988 // If optimization is enabled, and the value was held in a
1989 // __strong variable, we need to tell the optimizer that this
1990 // value has to stay alive until we're doing the store back.
1991 // This is because the temporary is effectively unretained,
1992 // and so otherwise we can violate the high-level semantics.
1993 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
1994 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
1995 valueToUse = src;
1996 }
John McCall31168b02011-06-15 23:02:42 +00001997 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001998
John McCall31168b02011-06-15 23:02:42 +00001999 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002000 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00002001 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002002 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00002003
2004 // Make a phi for the value to intrinsically use.
2005 if (valueToUse) {
2006 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2007 "icr.to-use");
2008 phiToUse->addIncoming(valueToUse, copyBB);
2009 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2010 originBB);
2011 valueToUse = phiToUse;
2012 }
2013
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002014 condEval.end(CGF);
2015 }
John McCall31168b02011-06-15 23:02:42 +00002016
John McCalleff18842013-03-23 02:35:54 +00002017 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00002018 args.add(RValue::get(finalArgument), CRE->getType());
2019}
2020
Reid Kleckner739756c2013-12-04 19:23:12 +00002021void CodeGenFunction::EmitCallArgs(CallArgList &Args,
2022 ArrayRef<QualType> ArgTypes,
2023 CallExpr::const_arg_iterator ArgBeg,
2024 CallExpr::const_arg_iterator ArgEnd,
2025 bool ForceColumnInfo) {
2026 CGDebugInfo *DI = getDebugInfo();
2027 SourceLocation CallLoc;
2028 if (DI) CallLoc = DI->getLocation();
2029
2030 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
2031 // because arguments are destroyed left to right in the callee.
2032 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2033 size_t CallArgsStart = Args.size();
2034 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
2035 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2036 EmitCallArg(Args, *Arg, ArgTypes[I]);
2037 // Restore the debug location.
2038 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2039 }
2040
2041 // Un-reverse the arguments we just evaluated so they match up with the LLVM
2042 // IR function.
2043 std::reverse(Args.begin() + CallArgsStart, Args.end());
2044 return;
2045 }
2046
2047 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
2048 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2049 assert(Arg != ArgEnd);
2050 EmitCallArg(Args, *Arg, ArgTypes[I]);
2051 // Restore the debug location.
2052 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2053 }
2054}
2055
John McCall32ea9692011-03-11 20:59:21 +00002056void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2057 QualType type) {
John McCall31168b02011-06-15 23:02:42 +00002058 if (const ObjCIndirectCopyRestoreExpr *CRE
2059 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002060 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00002061 assert(getContext().hasSameType(E->getType(), type));
2062 return emitWritebackArg(*this, args, CRE);
2063 }
2064
John McCall0a76c0c2011-08-26 18:42:59 +00002065 assert(type->isReferenceType() == E->isGLValue() &&
2066 "reference binding to unmaterialized r-value!");
2067
John McCall17054bd62011-08-26 21:08:13 +00002068 if (E->isGLValue()) {
2069 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00002070 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00002071 }
Mike Stump11289f42009-09-09 15:08:12 +00002072
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002073 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2074
2075 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2076 // However, we still have to push an EH-only cleanup in case we unwind before
2077 // we make it to the call.
2078 if (HasAggregateEvalKind &&
Reid Kleckner739756c2013-12-04 19:23:12 +00002079 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002080 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2081 if (RD && RD->hasNonTrivialDestructor()) {
2082 AggValueSlot Slot = CreateAggTemp(type, "agg.arg.tmp");
2083 Slot.setExternallyDestructed();
2084 EmitAggExpr(E, Slot);
2085 RValue RV = Slot.asRValue();
2086 args.add(RV, type);
2087
2088 pushDestroy(EHCleanup, RV.getAggregateAddr(), type, destroyCXXObject,
2089 /*useEHCleanupForArray*/ true);
2090 // This unreachable is a temporary marker which will be removed later.
2091 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2092 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
2093 return;
2094 }
2095 }
2096
2097 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00002098 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2099 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2100 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00002101 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2102 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2103 } else {
2104 // We can't represent a misaligned lvalue in the CallArgList, so copy
2105 // to an aligned temporary now.
2106 llvm::Value *tmp = CreateMemTemp(type);
2107 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2108 L.getAlignment());
2109 args.add(RValue::getAggregate(tmp), type);
2110 }
Eli Friedmandf968192011-05-26 00:10:27 +00002111 return;
2112 }
2113
John McCall32ea9692011-03-11 20:59:21 +00002114 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00002115}
2116
Dan Gohman515a60d2012-02-16 00:57:37 +00002117// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2118// optimizer it can aggressively ignore unwind edges.
2119void
2120CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2121 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2122 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2123 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2124 CGM.getNoObjCARCExceptionsMetadata());
2125}
2126
John McCall882987f2013-02-28 19:01:20 +00002127/// Emits a call to the given no-arguments nounwind runtime function.
2128llvm::CallInst *
2129CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2130 const llvm::Twine &name) {
2131 return EmitNounwindRuntimeCall(callee, ArrayRef<llvm::Value*>(), name);
2132}
2133
2134/// Emits a call to the given nounwind runtime function.
2135llvm::CallInst *
2136CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2137 ArrayRef<llvm::Value*> args,
2138 const llvm::Twine &name) {
2139 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2140 call->setDoesNotThrow();
2141 return call;
2142}
2143
2144/// Emits a simple call (never an invoke) to the given no-arguments
2145/// runtime function.
2146llvm::CallInst *
2147CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2148 const llvm::Twine &name) {
2149 return EmitRuntimeCall(callee, ArrayRef<llvm::Value*>(), name);
2150}
2151
2152/// Emits a simple call (never an invoke) to the given runtime
2153/// function.
2154llvm::CallInst *
2155CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2156 ArrayRef<llvm::Value*> args,
2157 const llvm::Twine &name) {
2158 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2159 call->setCallingConv(getRuntimeCC());
2160 return call;
2161}
2162
2163/// Emits a call or invoke to the given noreturn runtime function.
2164void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2165 ArrayRef<llvm::Value*> args) {
2166 if (getInvokeDest()) {
2167 llvm::InvokeInst *invoke =
2168 Builder.CreateInvoke(callee,
2169 getUnreachableBlock(),
2170 getInvokeDest(),
2171 args);
2172 invoke->setDoesNotReturn();
2173 invoke->setCallingConv(getRuntimeCC());
2174 } else {
2175 llvm::CallInst *call = Builder.CreateCall(callee, args);
2176 call->setDoesNotReturn();
2177 call->setCallingConv(getRuntimeCC());
2178 Builder.CreateUnreachable();
2179 }
2180}
2181
2182/// Emits a call or invoke instruction to the given nullary runtime
2183/// function.
2184llvm::CallSite
2185CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2186 const Twine &name) {
2187 return EmitRuntimeCallOrInvoke(callee, ArrayRef<llvm::Value*>(), name);
2188}
2189
2190/// Emits a call or invoke instruction to the given runtime function.
2191llvm::CallSite
2192CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2193 ArrayRef<llvm::Value*> args,
2194 const Twine &name) {
2195 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2196 callSite.setCallingConv(getRuntimeCC());
2197 return callSite;
2198}
2199
2200llvm::CallSite
2201CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2202 const Twine &Name) {
2203 return EmitCallOrInvoke(Callee, ArrayRef<llvm::Value *>(), Name);
2204}
2205
John McCallbd309292010-07-06 01:34:17 +00002206/// Emits a call or invoke instruction to the given function, depending
2207/// on the current state of the EH stack.
2208llvm::CallSite
2209CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00002210 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002211 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00002212 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00002213
Dan Gohman515a60d2012-02-16 00:57:37 +00002214 llvm::Instruction *Inst;
2215 if (!InvokeDest)
2216 Inst = Builder.CreateCall(Callee, Args, Name);
2217 else {
2218 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
2219 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
2220 EmitBlock(ContBB);
2221 }
2222
2223 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2224 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002225 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00002226 AddObjCARCExceptionMetadata(Inst);
2227
2228 return Inst;
John McCallbd309292010-07-06 01:34:17 +00002229}
2230
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002231static void checkArgMatches(llvm::Value *Elt, unsigned &ArgNo,
2232 llvm::FunctionType *FTy) {
2233 if (ArgNo < FTy->getNumParams())
2234 assert(Elt->getType() == FTy->getParamType(ArgNo));
2235 else
2236 assert(FTy->isVarArg());
2237 ++ArgNo;
2238}
2239
Chris Lattnerd59d8672011-07-12 06:29:11 +00002240void CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV,
Craig Topper5603df42013-07-05 19:34:19 +00002241 SmallVectorImpl<llvm::Value *> &Args,
Chris Lattnerd59d8672011-07-12 06:29:11 +00002242 llvm::FunctionType *IRFuncTy) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002243 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2244 unsigned NumElts = AT->getSize().getZExtValue();
2245 QualType EltTy = AT->getElementType();
2246 llvm::Value *Addr = RV.getAggregateAddr();
2247 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
2248 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, Elt);
Nick Lewycky2d84e842013-10-02 02:29:49 +00002249 RValue EltRV = convertTempToRValue(EltAddr, EltTy, SourceLocation());
Bob Wilsone826a2a2011-08-03 05:58:22 +00002250 ExpandTypeToArgs(EltTy, EltRV, Args, IRFuncTy);
Chris Lattnerd59d8672011-07-12 06:29:11 +00002251 }
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002252 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002253 RecordDecl *RD = RT->getDecl();
2254 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
Eli Friedman7f1ff602012-04-16 03:54:45 +00002255 LValue LV = MakeAddrLValue(RV.getAggregateAddr(), Ty);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002256
2257 if (RD->isUnion()) {
2258 const FieldDecl *LargestFD = 0;
2259 CharUnits UnionSize = CharUnits::Zero();
2260
2261 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2262 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00002263 const FieldDecl *FD = *i;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002264 assert(!FD->isBitField() &&
2265 "Cannot expand structure with bit-field members.");
2266 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
2267 if (UnionSize < FieldSize) {
2268 UnionSize = FieldSize;
2269 LargestFD = FD;
2270 }
2271 }
2272 if (LargestFD) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002273 RValue FldRV = EmitRValueForField(LV, LargestFD, SourceLocation());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002274 ExpandTypeToArgs(LargestFD->getType(), FldRV, Args, IRFuncTy);
2275 }
2276 } else {
2277 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2278 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00002279 FieldDecl *FD = *i;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002280
Nick Lewycky2d84e842013-10-02 02:29:49 +00002281 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002282 ExpandTypeToArgs(FD->getType(), FldRV, Args, IRFuncTy);
2283 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00002284 }
Eli Friedman95ff7002011-11-15 02:46:03 +00002285 } else if (Ty->isAnyComplexType()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002286 ComplexPairTy CV = RV.getComplexVal();
2287 Args.push_back(CV.first);
2288 Args.push_back(CV.second);
2289 } else {
Chris Lattnerd59d8672011-07-12 06:29:11 +00002290 assert(RV.isScalar() &&
2291 "Unexpected non-scalar rvalue during struct expansion.");
2292
2293 // Insert a bitcast as needed.
2294 llvm::Value *V = RV.getScalarVal();
2295 if (Args.size() < IRFuncTy->getNumParams() &&
2296 V->getType() != IRFuncTy->getParamType(Args.size()))
2297 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(Args.size()));
2298
2299 Args.push_back(V);
2300 }
2301}
2302
2303
Daniel Dunbard931a872009-02-02 22:03:45 +00002304RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00002305 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00002306 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002307 const CallArgList &CallArgs,
David Chisnall9eecafa2010-05-01 11:15:56 +00002308 const Decl *TargetDecl,
David Chisnallff5f88c2010-05-02 13:41:58 +00002309 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00002310 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002311 SmallVector<llvm::Value*, 16> Args;
Daniel Dunbar613855c2008-09-09 23:27:19 +00002312
2313 // Handle struct-return functions by passing a pointer to the
2314 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00002315 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002316 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002317
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002318 // IRArgNo - Keep track of the argument number in the callee we're looking at.
2319 unsigned IRArgNo = 0;
2320 llvm::FunctionType *IRFuncTy =
2321 cast<llvm::FunctionType>(
2322 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00002323
Chris Lattner4ca97c32009-06-13 00:26:38 +00002324 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00002325 // alloca to hold the result, unless one is given to us.
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00002326 if (CGM.ReturnTypeUsesSRet(CallInfo)) {
Anders Carlsson17490832009-12-24 20:40:36 +00002327 llvm::Value *Value = ReturnValue.getValue();
2328 if (!Value)
Daniel Dunbara7566f12010-02-09 02:48:28 +00002329 Value = CreateMemTemp(RetTy);
Anders Carlsson17490832009-12-24 20:40:36 +00002330 Args.push_back(Value);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002331 checkArgMatches(Value, IRArgNo, IRFuncTy);
Anders Carlsson17490832009-12-24 20:40:36 +00002332 }
Mike Stump11289f42009-09-09 15:08:12 +00002333
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002334 assert(CallInfo.arg_size() == CallArgs.size() &&
2335 "Mismatch between function signature & arguments.");
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002336 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002337 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002338 I != E; ++I, ++info_it) {
2339 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00002340 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002341
John McCall47fb9502013-03-07 21:37:08 +00002342 CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002343
2344 // Insert a padding argument to ensure proper alignment.
2345 if (llvm::Type *PaddingType = ArgInfo.getPaddingType()) {
2346 Args.push_back(llvm::UndefValue::get(PaddingType));
2347 ++IRArgNo;
2348 }
2349
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002350 switch (ArgInfo.getKind()) {
Daniel Dunbar03816342010-08-21 02:24:36 +00002351 case ABIArgInfo::Indirect: {
Daniel Dunbar747865a2009-02-05 09:16:39 +00002352 if (RV.isScalar() || RV.isComplex()) {
2353 // Make a temporary alloca to pass the argument.
Eli Friedman7e68c882011-06-15 18:26:32 +00002354 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2355 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
2356 AI->setAlignment(ArgInfo.getIndirectAlign());
2357 Args.push_back(AI);
John McCall47fb9502013-03-07 21:37:08 +00002358
2359 LValue argLV =
2360 MakeAddrLValue(Args.back(), I->Ty, TypeAlign);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002361
Daniel Dunbar747865a2009-02-05 09:16:39 +00002362 if (RV.isScalar())
John McCall47fb9502013-03-07 21:37:08 +00002363 EmitStoreOfScalar(RV.getScalarVal(), argLV, /*init*/ true);
Daniel Dunbar747865a2009-02-05 09:16:39 +00002364 else
John McCall47fb9502013-03-07 21:37:08 +00002365 EmitStoreOfComplex(RV.getComplexVal(), argLV, /*init*/ true);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002366
2367 // Validate argument match.
2368 checkArgMatches(AI, IRArgNo, IRFuncTy);
Daniel Dunbar747865a2009-02-05 09:16:39 +00002369 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002370 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00002371 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002372 // 1. If the argument is not byval, and we are required to copy the
2373 // source. (This case doesn't occur on any common architecture.)
2374 // 2. If the argument is byval, RV is not sufficiently aligned, and
2375 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00002376 // 3. If the argument is byval, but RV is located in an address space
2377 // different than that of the argument (0).
Eli Friedmanf7456192011-06-15 22:09:18 +00002378 llvm::Value *Addr = RV.getAggregateAddr();
2379 unsigned Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002380 const llvm::DataLayout *TD = &CGM.getDataLayout();
Guy Benyei3832bfd2013-03-10 12:59:00 +00002381 const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
2382 const unsigned ArgAddrSpace = (IRArgNo < IRFuncTy->getNumParams() ?
2383 IRFuncTy->getParamType(IRArgNo)->getPointerAddressSpace() : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00002384 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall47fb9502013-03-07 21:37:08 +00002385 (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
Guy Benyei3832bfd2013-03-10 12:59:00 +00002386 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align) ||
2387 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002388 // Create an aligned temporary, and copy to it.
Eli Friedmanf7456192011-06-15 22:09:18 +00002389 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2390 if (Align > AI->getAlignment())
2391 AI->setAlignment(Align);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002392 Args.push_back(AI);
Chad Rosier615ed1a2012-03-29 17:37:10 +00002393 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002394
2395 // Validate argument match.
2396 checkArgMatches(AI, IRArgNo, IRFuncTy);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002397 } else {
2398 // Skip the extra memcpy call.
Eli Friedmanf7456192011-06-15 22:09:18 +00002399 Args.push_back(Addr);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002400
2401 // Validate argument match.
2402 checkArgMatches(Addr, IRArgNo, IRFuncTy);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002403 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002404 }
2405 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002406 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002407
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002408 case ABIArgInfo::Ignore:
2409 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002410
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002411 case ABIArgInfo::Extend:
2412 case ABIArgInfo::Direct: {
2413 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002414 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
2415 ArgInfo.getDirectOffset() == 0) {
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002416 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002417 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002418 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002419 else
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002420 V = Builder.CreateLoad(RV.getAggregateAddr());
2421
Chris Lattner3ce86682011-07-12 04:53:39 +00002422 // If the argument doesn't match, perform a bitcast to coerce it. This
2423 // can happen due to trivial type mismatches.
2424 if (IRArgNo < IRFuncTy->getNumParams() &&
2425 V->getType() != IRFuncTy->getParamType(IRArgNo))
2426 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRArgNo));
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002427 Args.push_back(V);
2428
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002429 checkArgMatches(V, IRArgNo, IRFuncTy);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002430 break;
2431 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002432
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002433 // FIXME: Avoid the conversion through memory if possible.
2434 llvm::Value *SrcPtr;
John McCall47fb9502013-03-07 21:37:08 +00002435 if (RV.isScalar() || RV.isComplex()) {
Eli Friedmanf4258eb2011-05-02 18:05:27 +00002436 SrcPtr = CreateMemTemp(I->Ty, "coerce");
John McCall47fb9502013-03-07 21:37:08 +00002437 LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
2438 if (RV.isScalar()) {
2439 EmitStoreOfScalar(RV.getScalarVal(), SrcLV, /*init*/ true);
2440 } else {
2441 EmitStoreOfComplex(RV.getComplexVal(), SrcLV, /*init*/ true);
2442 }
Mike Stump11289f42009-09-09 15:08:12 +00002443 } else
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002444 SrcPtr = RV.getAggregateAddr();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002445
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002446 // If the value is offset in memory, apply the offset now.
2447 if (unsigned Offs = ArgInfo.getDirectOffset()) {
2448 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
2449 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002450 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002451 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
2452
2453 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002454
Chris Lattner3dd716c2010-06-28 23:44:11 +00002455 // If the coerce-to type is a first class aggregate, we flatten it and
2456 // pass the elements. Either way is semantically identical, but fast-isel
2457 // and the optimizer generally likes scalar values better than FCAs.
Chris Lattner2192fe52011-07-18 04:24:23 +00002458 if (llvm::StructType *STy =
Chris Lattner15ec3612010-06-29 00:06:42 +00002459 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType())) {
Chandler Carrutha6399a52012-10-10 11:29:08 +00002460 llvm::Type *SrcTy =
2461 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
2462 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
2463 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
2464
2465 // If the source type is smaller than the destination type of the
2466 // coerce-to logic, copy the source value into a temp alloca the size
2467 // of the destination type to allow loading all of it. The bits past
2468 // the source value are left undef.
2469 if (SrcSize < DstSize) {
2470 llvm::AllocaInst *TempAlloca
2471 = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
2472 Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
2473 SrcPtr = TempAlloca;
2474 } else {
2475 SrcPtr = Builder.CreateBitCast(SrcPtr,
2476 llvm::PointerType::getUnqual(STy));
2477 }
2478
Chris Lattnerceddafb2010-07-05 20:41:41 +00002479 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2480 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerff941a62010-07-28 18:24:28 +00002481 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
2482 // We don't know what we're loading from.
2483 LI->setAlignment(1);
2484 Args.push_back(LI);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002485
2486 // Validate argument match.
2487 checkArgMatches(LI, IRArgNo, IRFuncTy);
Chris Lattner15ec3612010-06-29 00:06:42 +00002488 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00002489 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00002490 // In the simple case, just pass the coerced loaded value.
2491 Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(),
2492 *this));
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002493
2494 // Validate argument match.
2495 checkArgMatches(Args.back(), IRArgNo, IRFuncTy);
Chris Lattner3dd716c2010-06-28 23:44:11 +00002496 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002497
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002498 break;
2499 }
2500
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002501 case ABIArgInfo::Expand:
Chris Lattnerd59d8672011-07-12 06:29:11 +00002502 ExpandTypeToArgs(I->Ty, RV, Args, IRFuncTy);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002503 IRArgNo = Args.size();
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002504 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00002505 }
2506 }
Mike Stump11289f42009-09-09 15:08:12 +00002507
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002508 if (!CallArgs.getCleanupsToDeactivate().empty())
2509 deactivateArgCleanupsBeforeCall(*this, CallArgs);
2510
Chris Lattner4ca97c32009-06-13 00:26:38 +00002511 // If the callee is a bitcast of a function to a varargs pointer to function
2512 // type, check to see if we can remove the bitcast. This handles some cases
2513 // with unprototyped functions.
2514 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
2515 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002516 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
2517 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00002518 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00002519 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00002520
Chris Lattner4ca97c32009-06-13 00:26:38 +00002521 if (CE->getOpcode() == llvm::Instruction::BitCast &&
2522 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00002523 ActualFT->getNumParams() == CurFT->getNumParams() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00002524 ActualFT->getNumParams() == Args.size() &&
2525 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00002526 bool ArgsMatch = true;
2527 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
2528 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
2529 ArgsMatch = false;
2530 break;
2531 }
Mike Stump11289f42009-09-09 15:08:12 +00002532
Chris Lattner4ca97c32009-06-13 00:26:38 +00002533 // Strip the cast if we can get away with it. This is a nice cleanup,
2534 // but also allows us to inline the function at -O0 if it is marked
2535 // always_inline.
2536 if (ArgsMatch)
2537 Callee = CalleeF;
2538 }
2539 }
Mike Stump11289f42009-09-09 15:08:12 +00002540
Daniel Dunbar0ef34792009-09-12 00:59:20 +00002541 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00002542 CodeGen::AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00002543 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
2544 CallingConv, true);
Bill Wendling3087d022012-12-07 23:17:26 +00002545 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00002546 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00002547
John McCallbd309292010-07-06 01:34:17 +00002548 llvm::BasicBlock *InvokeDest = 0;
Bill Wendling5e85be42012-12-30 10:32:17 +00002549 if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
2550 llvm::Attribute::NoUnwind))
John McCallbd309292010-07-06 01:34:17 +00002551 InvokeDest = getInvokeDest();
2552
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002553 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00002554 if (!InvokeDest) {
Jay Foad5bd375a2011-07-15 08:37:34 +00002555 CS = Builder.CreateCall(Callee, Args);
Daniel Dunbar12347492009-02-23 17:26:39 +00002556 } else {
2557 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Jay Foad5bd375a2011-07-15 08:37:34 +00002558 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, Args);
Daniel Dunbar12347492009-02-23 17:26:39 +00002559 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00002560 }
Chris Lattnere70a0072010-06-29 16:40:28 +00002561 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00002562 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00002563
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002564 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00002565 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002566
Dan Gohman515a60d2012-02-16 00:57:37 +00002567 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2568 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002569 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00002570 AddObjCARCExceptionMetadata(CS.getInstruction());
2571
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002572 // If the call doesn't return, finish the basic block and clear the
2573 // insertion point; this allows the rest of IRgen to discard
2574 // unreachable code.
2575 if (CS.doesNotReturn()) {
2576 Builder.CreateUnreachable();
2577 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00002578
Mike Stump18bb9282009-05-16 07:57:57 +00002579 // FIXME: For now, emit a dummy basic block because expr emitters in
2580 // generally are not ready to handle emitting expressions at unreachable
2581 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002582 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00002583
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002584 // Return a reasonable RValue.
2585 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00002586 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002587
2588 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00002589 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00002590 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002591
John McCall31168b02011-06-15 23:02:42 +00002592 // Emit any writebacks immediately. Arguably this should happen
2593 // after any return-value munging.
2594 if (CallArgs.hasWritebacks())
2595 emitWritebacks(*this, CallArgs);
2596
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002597 switch (RetAI.getKind()) {
John McCall47fb9502013-03-07 21:37:08 +00002598 case ABIArgInfo::Indirect:
Nick Lewycky2d84e842013-10-02 02:29:49 +00002599 return convertTempToRValue(Args[0], RetTy, SourceLocation());
Daniel Dunbard3674e62008-09-11 01:48:57 +00002600
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002601 case ABIArgInfo::Ignore:
Daniel Dunbar01362822009-02-03 06:30:17 +00002602 // If we are ignoring an argument that had a result, make sure to
2603 // construct the appropriate return value for our caller.
Daniel Dunbarc79407f2009-02-05 07:09:07 +00002604 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002605
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002606 case ABIArgInfo::Extend:
2607 case ABIArgInfo::Direct: {
Chris Lattner3517f142011-07-13 03:59:32 +00002608 llvm::Type *RetIRTy = ConvertType(RetTy);
2609 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
John McCall47fb9502013-03-07 21:37:08 +00002610 switch (getEvaluationKind(RetTy)) {
2611 case TEK_Complex: {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002612 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
2613 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
2614 return RValue::getComplex(std::make_pair(Real, Imag));
2615 }
John McCall47fb9502013-03-07 21:37:08 +00002616 case TEK_Aggregate: {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002617 llvm::Value *DestPtr = ReturnValue.getValue();
2618 bool DestIsVolatile = ReturnValue.isVolatile();
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002619
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002620 if (!DestPtr) {
2621 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
2622 DestIsVolatile = false;
2623 }
Eli Friedmanaf9b3252011-05-17 21:08:01 +00002624 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002625 return RValue::getAggregate(DestPtr);
2626 }
John McCall47fb9502013-03-07 21:37:08 +00002627 case TEK_Scalar: {
2628 // If the argument doesn't match, perform a bitcast to coerce it. This
2629 // can happen due to trivial type mismatches.
2630 llvm::Value *V = CI;
2631 if (V->getType() != RetIRTy)
2632 V = Builder.CreateBitCast(V, RetIRTy);
2633 return RValue::get(V);
2634 }
2635 }
2636 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002637 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002638
Anders Carlsson17490832009-12-24 20:40:36 +00002639 llvm::Value *DestPtr = ReturnValue.getValue();
2640 bool DestIsVolatile = ReturnValue.isVolatile();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002641
Anders Carlsson17490832009-12-24 20:40:36 +00002642 if (!DestPtr) {
Daniel Dunbara7566f12010-02-09 02:48:28 +00002643 DestPtr = CreateMemTemp(RetTy, "coerce");
Anders Carlsson17490832009-12-24 20:40:36 +00002644 DestIsVolatile = false;
2645 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002646
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002647 // If the value is offset in memory, apply the offset now.
2648 llvm::Value *StorePtr = DestPtr;
2649 if (unsigned Offs = RetAI.getDirectOffset()) {
2650 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
2651 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002652 StorePtr = Builder.CreateBitCast(StorePtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002653 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
2654 }
2655 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002656
Nick Lewycky2d84e842013-10-02 02:29:49 +00002657 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Daniel Dunbar573884e2008-09-10 07:04:09 +00002658 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00002659
Daniel Dunbard3674e62008-09-11 01:48:57 +00002660 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002661 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar613855c2008-09-09 23:27:19 +00002662 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002663
David Blaikie83d382b2011-09-23 05:06:16 +00002664 llvm_unreachable("Unhandled ABIArgInfo::Kind");
Daniel Dunbar613855c2008-09-09 23:27:19 +00002665}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00002666
2667/* VarArg handling */
2668
2669llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
2670 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
2671}