blob: 78e22633068dfbf1eb2253483fae385d2c8c01d5 [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.
Alp Toker9cacbab2014-01-20 20:26:09 +000095 for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
96 prefix.push_back(FTP->getParamType(i));
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
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000126static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
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
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000149 if (D->hasAttr<MSABIAttr>())
150 return IsWindows ? CC_C : CC_X86_64Win64;
151
152 if (D->hasAttr<SysVABIAttr>())
153 return IsWindows ? CC_X86_64SysV : CC_C;
154
John McCallab26cfa2010-02-05 21:31:56 +0000155 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000156}
157
John McCalla729c622012-02-17 03:33:10 +0000158/// Arrange the argument and result information for a call to an
159/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000160/// (Zero value of RD means we don't have any meaningful "this" argument type,
161/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000162/// The member function must be an ordinary function, i.e. not a
163/// constructor or destructor.
164const CGFunctionInfo &
165CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
166 const FunctionProtoType *FTP) {
167 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000168
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000169 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000170 if (RD)
171 argTypes.push_back(GetThisType(Context, RD));
172 else
173 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000174
John McCall8dda7b22012-07-07 06:41:13 +0000175 return ::arrangeCXXMethodType(*this, argTypes,
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000176 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000177}
178
John McCalla729c622012-02-17 03:33:10 +0000179/// Arrange the argument and result information for a declaration or
180/// definition of the given C++ non-static member function. The
181/// member function must be an ordinary function, i.e. not a
182/// constructor or destructor.
183const CGFunctionInfo &
184CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000185 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000186 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
187
John McCalla729c622012-02-17 03:33:10 +0000188 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000189
John McCalla729c622012-02-17 03:33:10 +0000190 if (MD->isInstance()) {
191 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000192 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000193 return arrangeCXXMethodType(ThisType, prototype.getTypePtr());
John McCalla729c622012-02-17 03:33:10 +0000194 }
195
John McCall8dda7b22012-07-07 06:41:13 +0000196 return arrangeFreeFunctionType(prototype);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000197}
198
John McCalla729c622012-02-17 03:33:10 +0000199/// Arrange the argument and result information for a declaration
200/// or definition to the given constructor variant.
201const CGFunctionInfo &
202CodeGenTypes::arrangeCXXConstructorDeclaration(const CXXConstructorDecl *D,
203 CXXCtorType ctorKind) {
204 SmallVector<CanQualType, 16> argTypes;
205 argTypes.push_back(GetThisType(Context, D->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000206
207 GlobalDecl GD(D, ctorKind);
208 CanQualType resultType =
209 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000210
John McCall5d865c322010-08-31 07:33:07 +0000211 CanQual<FunctionProtoType> FTP = GetFormalType(D);
212
213 // Add the formal parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000214 for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
215 argTypes.push_back(FTP->getParamType(i));
John McCall5d865c322010-08-31 07:33:07 +0000216
Reid Kleckner89077a12013-12-17 19:46:40 +0000217 TheCXXABI.BuildConstructorSignature(D, ctorKind, resultType, argTypes);
218
219 RequiredArgs required =
220 (D->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All);
221
John McCall8dda7b22012-07-07 06:41:13 +0000222 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
John McCall8dda7b22012-07-07 06:41:13 +0000223 return arrangeLLVMFunctionInfo(resultType, argTypes, extInfo, required);
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000224}
225
John McCalla729c622012-02-17 03:33:10 +0000226/// Arrange the argument and result information for a declaration,
227/// definition, or call to the given destructor variant. It so
228/// happens that all three cases produce the same information.
229const CGFunctionInfo &
230CodeGenTypes::arrangeCXXDestructor(const CXXDestructorDecl *D,
231 CXXDtorType dtorKind) {
232 SmallVector<CanQualType, 2> argTypes;
233 argTypes.push_back(GetThisType(Context, D->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000234
235 GlobalDecl GD(D, dtorKind);
236 CanQualType resultType =
237 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
John McCall8ee376f2010-02-24 07:14:12 +0000238
John McCalla729c622012-02-17 03:33:10 +0000239 TheCXXABI.BuildDestructorSignature(D, dtorKind, resultType, argTypes);
John McCall5d865c322010-08-31 07:33:07 +0000240
241 CanQual<FunctionProtoType> FTP = GetFormalType(D);
Alp Toker9cacbab2014-01-20 20:26:09 +0000242 assert(FTP->getNumParams() == 0 && "dtor with formal parameters");
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +0000243 assert(FTP->isVariadic() == 0 && "dtor with formal parameters");
John McCall5d865c322010-08-31 07:33:07 +0000244
John McCall8dda7b22012-07-07 06:41:13 +0000245 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
John McCall8dda7b22012-07-07 06:41:13 +0000246 return arrangeLLVMFunctionInfo(resultType, argTypes, extInfo,
247 RequiredArgs::All);
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000248}
249
John McCalla729c622012-02-17 03:33:10 +0000250/// Arrange the argument and result information for the declaration or
251/// definition of the given function.
252const CGFunctionInfo &
253CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000254 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000255 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000256 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000257
John McCall2da83a32010-02-26 00:48:12 +0000258 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000259
John McCall2da83a32010-02-26 00:48:12 +0000260 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000261
262 // When declaring a function without a prototype, always use a
263 // non-variadic type.
264 if (isa<FunctionNoProtoType>(FTy)) {
265 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000266 return arrangeLLVMFunctionInfo(noProto->getResultType(), None,
267 noProto->getExtInfo(), RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000268 }
269
John McCall2da83a32010-02-26 00:48:12 +0000270 assert(isa<FunctionProtoType>(FTy));
John McCall8dda7b22012-07-07 06:41:13 +0000271 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>());
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000272}
273
John McCalla729c622012-02-17 03:33:10 +0000274/// Arrange the argument and result information for the declaration or
275/// definition of an Objective-C method.
276const CGFunctionInfo &
277CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
278 // It happens that this is the same as a call with no optional
279 // arguments, except also using the formal 'self' type.
280 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
281}
282
283/// Arrange the argument and result information for the function type
284/// through which to perform a send to the given Objective-C method,
285/// using the given receiver type. The receiver type is not always
286/// the 'self' type of the method or even an Objective-C pointer type.
287/// This is *not* the right method for actually performing such a
288/// message send, due to the possibility of optional arguments.
289const CGFunctionInfo &
290CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
291 QualType receiverType) {
292 SmallVector<CanQualType, 16> argTys;
293 argTys.push_back(Context.getCanonicalParamType(receiverType));
294 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000295 // FIXME: Kill copy?
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +0000296 for (ObjCMethodDecl::param_const_iterator i = MD->param_begin(),
John McCall8ee376f2010-02-24 07:14:12 +0000297 e = MD->param_end(); i != e; ++i) {
John McCalla729c622012-02-17 03:33:10 +0000298 argTys.push_back(Context.getCanonicalParamType((*i)->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000299 }
John McCall31168b02011-06-15 23:02:42 +0000300
301 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000302 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
303 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000304
David Blaikiebbafb8a2012-03-11 07:00:24 +0000305 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000306 MD->hasAttr<NSReturnsRetainedAttr>())
307 einfo = einfo.withProducesResult(true);
308
John McCalla729c622012-02-17 03:33:10 +0000309 RequiredArgs required =
310 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
311
John McCall8dda7b22012-07-07 06:41:13 +0000312 return arrangeLLVMFunctionInfo(GetReturnType(MD->getResultType()), argTys,
313 einfo, required);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000314}
315
John McCalla729c622012-02-17 03:33:10 +0000316const CGFunctionInfo &
317CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000318 // FIXME: Do we need to handle ObjCMethodDecl?
319 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000320
Anders Carlsson6710c532010-02-06 02:44:09 +0000321 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
John McCalla729c622012-02-17 03:33:10 +0000322 return arrangeCXXConstructorDeclaration(CD, GD.getCtorType());
Anders Carlsson6710c532010-02-06 02:44:09 +0000323
324 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
John McCalla729c622012-02-17 03:33:10 +0000325 return arrangeCXXDestructor(DD, GD.getDtorType());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000326
John McCalla729c622012-02-17 03:33:10 +0000327 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000328}
329
John McCallc818bbb2012-12-07 07:03:17 +0000330/// Arrange a call as unto a free function, except possibly with an
331/// additional number of formal parameters considered required.
332static const CGFunctionInfo &
333arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000334 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000335 const CallArgList &args,
336 const FunctionType *fnType,
337 unsigned numExtraRequiredArgs) {
338 assert(args.size() >= numExtraRequiredArgs);
339
340 // In most cases, there are no optional arguments.
341 RequiredArgs required = RequiredArgs::All;
342
343 // If we have a variadic prototype, the required arguments are the
344 // extra prefix plus the arguments in the prototype.
345 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
346 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000347 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000348
349 // If we don't have a prototype at all, but we're supposed to
350 // explicitly use the variadic convention for unprototyped calls,
351 // treat all of the arguments as required but preserve the nominal
352 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000353 } else if (CGM.getTargetCodeGenInfo()
354 .isNoProtoCallVariadic(args,
355 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000356 required = RequiredArgs(args.size());
357 }
358
359 return CGT.arrangeFreeFunctionCall(fnType->getResultType(), args,
360 fnType->getExtInfo(), required);
361}
362
John McCalla729c622012-02-17 03:33:10 +0000363/// Figure out the rules for calling a function with the given formal
364/// type using the given arguments. The arguments are necessary
365/// because the function might be unprototyped, in which case it's
366/// target-dependent in crazy ways.
367const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000368CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
369 const FunctionType *fnType) {
Mark Lacey23455752013-10-10 20:57:00 +0000370 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 0);
John McCallc818bbb2012-12-07 07:03:17 +0000371}
John McCalla729c622012-02-17 03:33:10 +0000372
John McCallc818bbb2012-12-07 07:03:17 +0000373/// A block function call is essentially a free-function call with an
374/// extra implicit argument.
375const CGFunctionInfo &
376CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
377 const FunctionType *fnType) {
Mark Lacey23455752013-10-10 20:57:00 +0000378 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1);
John McCalla729c622012-02-17 03:33:10 +0000379}
380
381const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000382CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
383 const CallArgList &args,
384 FunctionType::ExtInfo info,
385 RequiredArgs required) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000386 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000387 SmallVector<CanQualType, 16> argTypes;
388 for (CallArgList::const_iterator i = args.begin(), e = args.end();
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000389 i != e; ++i)
John McCalla729c622012-02-17 03:33:10 +0000390 argTypes.push_back(Context.getCanonicalParamType(i->Ty));
John McCall8dda7b22012-07-07 06:41:13 +0000391 return arrangeLLVMFunctionInfo(GetReturnType(resultType), argTypes, info,
392 required);
393}
394
395/// Arrange a call to a C++ method, passing the given arguments.
396const CGFunctionInfo &
397CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
398 const FunctionProtoType *FPT,
399 RequiredArgs required) {
400 // FIXME: Kill copy.
401 SmallVector<CanQualType, 16> argTypes;
402 for (CallArgList::const_iterator i = args.begin(), e = args.end();
403 i != e; ++i)
404 argTypes.push_back(Context.getCanonicalParamType(i->Ty));
405
406 FunctionType::ExtInfo info = FPT->getExtInfo();
John McCall8dda7b22012-07-07 06:41:13 +0000407 return arrangeLLVMFunctionInfo(GetReturnType(FPT->getResultType()),
408 argTypes, info, required);
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000409}
410
John McCalla729c622012-02-17 03:33:10 +0000411const CGFunctionInfo &
412CodeGenTypes::arrangeFunctionDeclaration(QualType resultType,
413 const FunctionArgList &args,
414 const FunctionType::ExtInfo &info,
415 bool isVariadic) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000416 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000417 SmallVector<CanQualType, 16> argTypes;
418 for (FunctionArgList::const_iterator i = args.begin(), e = args.end();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +0000419 i != e; ++i)
John McCalla729c622012-02-17 03:33:10 +0000420 argTypes.push_back(Context.getCanonicalParamType((*i)->getType()));
421
422 RequiredArgs required =
423 (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
John McCall8dda7b22012-07-07 06:41:13 +0000424 return arrangeLLVMFunctionInfo(GetReturnType(resultType), argTypes, info,
425 required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000426}
427
John McCalla729c622012-02-17 03:33:10 +0000428const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000429 return arrangeLLVMFunctionInfo(getContext().VoidTy, None,
John McCall8dda7b22012-07-07 06:41:13 +0000430 FunctionType::ExtInfo(), RequiredArgs::All);
John McCalla738c252011-03-09 04:27:21 +0000431}
432
John McCalla729c622012-02-17 03:33:10 +0000433/// Arrange the argument and result information for an abstract value
434/// of a given function type. This is the method which all of the
435/// above functions ultimately defer to.
436const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000437CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
438 ArrayRef<CanQualType> argTypes,
439 FunctionType::ExtInfo info,
440 RequiredArgs required) {
John McCall2da83a32010-02-26 00:48:12 +0000441#ifndef NDEBUG
John McCalla729c622012-02-17 03:33:10 +0000442 for (ArrayRef<CanQualType>::const_iterator
443 I = argTypes.begin(), E = argTypes.end(); I != E; ++I)
John McCall2da83a32010-02-26 00:48:12 +0000444 assert(I->isCanonicalAsParam());
445#endif
446
John McCalla729c622012-02-17 03:33:10 +0000447 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
John McCallab26cfa2010-02-05 21:31:56 +0000448
Daniel Dunbare0be8292009-02-03 00:07:12 +0000449 // Lookup or create unique function info.
450 llvm::FoldingSetNodeID ID;
John McCalla729c622012-02-17 03:33:10 +0000451 CGFunctionInfo::Profile(ID, info, required, resultType, argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000452
John McCalla729c622012-02-17 03:33:10 +0000453 void *insertPos = 0;
454 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000455 if (FI)
456 return *FI;
457
John McCalla729c622012-02-17 03:33:10 +0000458 // Construct the function info. We co-allocate the ArgInfos.
459 FI = CGFunctionInfo::create(CC, info, resultType, argTypes, required);
460 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000461
John McCalla729c622012-02-17 03:33:10 +0000462 bool inserted = FunctionsBeingProcessed.insert(FI); (void)inserted;
463 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000464
Daniel Dunbar313321e2009-02-03 05:31:23 +0000465 // Compute ABI information.
Chris Lattner22326a12010-07-29 02:31:05 +0000466 getABIInfo().computeInfo(*FI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000467
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000468 // Loop over all of the computed argument and return value info. If any of
469 // them are direct or extend without a specified coerce type, specify the
470 // default now.
John McCalla729c622012-02-17 03:33:10 +0000471 ABIArgInfo &retInfo = FI->getReturnInfo();
472 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == 0)
473 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000474
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000475 for (CGFunctionInfo::arg_iterator I = FI->arg_begin(), E = FI->arg_end();
476 I != E; ++I)
477 if (I->info.canHaveCoerceToType() && I->info.getCoerceToType() == 0)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000478 I->info.setCoerceToType(ConvertType(I->type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000479
John McCalla729c622012-02-17 03:33:10 +0000480 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
481 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000482
Daniel Dunbare0be8292009-02-03 00:07:12 +0000483 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000484}
485
John McCalla729c622012-02-17 03:33:10 +0000486CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
487 const FunctionType::ExtInfo &info,
488 CanQualType resultType,
489 ArrayRef<CanQualType> argTypes,
490 RequiredArgs required) {
491 void *buffer = operator new(sizeof(CGFunctionInfo) +
492 sizeof(ArgInfo) * (argTypes.size() + 1));
493 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
494 FI->CallingConvention = llvmCC;
495 FI->EffectiveCallingConvention = llvmCC;
496 FI->ASTCallingConvention = info.getCC();
497 FI->NoReturn = info.getNoReturn();
498 FI->ReturnsRetained = info.getProducesResult();
499 FI->Required = required;
500 FI->HasRegParm = info.getHasRegParm();
501 FI->RegParm = info.getRegParm();
502 FI->NumArgs = argTypes.size();
503 FI->getArgsBuffer()[0].type = resultType;
504 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
505 FI->getArgsBuffer()[i + 1].type = argTypes[i];
506 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000507}
508
509/***/
510
John McCall85dd2c52011-05-15 02:19:42 +0000511void CodeGenTypes::GetExpandedTypes(QualType type,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000512 SmallVectorImpl<llvm::Type*> &expandedTypes) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000513 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(type)) {
514 uint64_t NumElts = AT->getSize().getZExtValue();
515 for (uint64_t Elt = 0; Elt < NumElts; ++Elt)
516 GetExpandedTypes(AT->getElementType(), expandedTypes);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000517 } else if (const RecordType *RT = type->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000518 const RecordDecl *RD = RT->getDecl();
519 assert(!RD->hasFlexibleArrayMember() &&
520 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000521 if (RD->isUnion()) {
522 // Unions can be here only in degenerative cases - all the fields are same
523 // after flattening. Thus we have to use the "largest" field.
524 const FieldDecl *LargestFD = 0;
525 CharUnits UnionSize = CharUnits::Zero();
526
527 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
528 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +0000529 const FieldDecl *FD = *i;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000530 assert(!FD->isBitField() &&
531 "Cannot expand structure with bit-field members.");
532 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
533 if (UnionSize < FieldSize) {
534 UnionSize = FieldSize;
535 LargestFD = FD;
536 }
537 }
538 if (LargestFD)
539 GetExpandedTypes(LargestFD->getType(), expandedTypes);
540 } else {
541 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
542 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +0000543 assert(!i->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000544 "Cannot expand structure with bit-field members.");
David Blaikie40ed2972012-06-06 20:45:41 +0000545 GetExpandedTypes(i->getType(), expandedTypes);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000546 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000547 }
548 } else if (const ComplexType *CT = type->getAs<ComplexType>()) {
549 llvm::Type *EltTy = ConvertType(CT->getElementType());
550 expandedTypes.push_back(EltTy);
551 expandedTypes.push_back(EltTy);
552 } else
553 expandedTypes.push_back(ConvertType(type));
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000554}
555
Mike Stump11289f42009-09-09 15:08:12 +0000556llvm::Function::arg_iterator
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000557CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
558 llvm::Function::arg_iterator AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000559 assert(LV.isSimple() &&
560 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000561
Bob Wilsone826a2a2011-08-03 05:58:22 +0000562 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
563 unsigned NumElts = AT->getSize().getZExtValue();
564 QualType EltTy = AT->getElementType();
565 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
Eli Friedman7f1ff602012-04-16 03:54:45 +0000566 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, Elt);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000567 LValue LV = MakeAddrLValue(EltAddr, EltTy);
568 AI = ExpandTypeFromArgs(EltTy, LV, AI);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000569 }
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000570 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000571 RecordDecl *RD = RT->getDecl();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000572 if (RD->isUnion()) {
573 // Unions can be here only in degenerative cases - all the fields are same
574 // after flattening. Thus we have to use the "largest" field.
575 const FieldDecl *LargestFD = 0;
576 CharUnits UnionSize = CharUnits::Zero();
Bob Wilsone826a2a2011-08-03 05:58:22 +0000577
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000578 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
579 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +0000580 const FieldDecl *FD = *i;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000581 assert(!FD->isBitField() &&
582 "Cannot expand structure with bit-field members.");
583 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
584 if (UnionSize < FieldSize) {
585 UnionSize = FieldSize;
586 LargestFD = FD;
587 }
588 }
589 if (LargestFD) {
590 // FIXME: What are the right qualifiers here?
Eli Friedman7f1ff602012-04-16 03:54:45 +0000591 LValue SubLV = EmitLValueForField(LV, LargestFD);
592 AI = ExpandTypeFromArgs(LargestFD->getType(), SubLV, AI);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000593 }
594 } else {
595 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
596 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +0000597 FieldDecl *FD = *i;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000598 QualType FT = FD->getType();
599
600 // FIXME: What are the right qualifiers here?
Eli Friedman7f1ff602012-04-16 03:54:45 +0000601 LValue SubLV = EmitLValueForField(LV, FD);
602 AI = ExpandTypeFromArgs(FT, SubLV, AI);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000603 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000604 }
605 } else if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
606 QualType EltTy = CT->getElementType();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000607 llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real");
Bob Wilsone826a2a2011-08-03 05:58:22 +0000608 EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(RealAddr, EltTy));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000609 llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag");
Bob Wilsone826a2a2011-08-03 05:58:22 +0000610 EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(ImagAddr, EltTy));
611 } else {
612 EmitStoreThroughLValue(RValue::get(AI), LV);
613 ++AI;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000614 }
615
616 return AI;
617}
618
Chris Lattner895c52b2010-06-27 06:04:18 +0000619/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +0000620/// accessing some number of bytes out of it, try to gep into the struct to get
621/// at its inner goodness. Dive as deep as possible without entering an element
622/// with an in-memory size smaller than DstSize.
623static llvm::Value *
Chris Lattner895c52b2010-06-27 06:04:18 +0000624EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000625 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +0000626 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +0000627 // We can't dive into a zero-element struct.
628 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000629
Chris Lattner2192fe52011-07-18 04:24:23 +0000630 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000631
Chris Lattner1cd66982010-06-27 05:56:15 +0000632 // If the first elt is at least as large as what we're looking for, or if the
633 // first element is the same size as the whole struct, we can enter it.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000634 uint64_t FirstEltSize =
Micah Villmowdd31ca12012-10-08 16:25:52 +0000635 CGF.CGM.getDataLayout().getTypeAllocSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000636 if (FirstEltSize < DstSize &&
Micah Villmowdd31ca12012-10-08 16:25:52 +0000637 FirstEltSize < CGF.CGM.getDataLayout().getTypeAllocSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +0000638 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000639
Chris Lattner1cd66982010-06-27 05:56:15 +0000640 // GEP into the first element.
641 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000642
Chris Lattner1cd66982010-06-27 05:56:15 +0000643 // If the first element is a struct, recurse.
Chris Lattner2192fe52011-07-18 04:24:23 +0000644 llvm::Type *SrcTy =
Chris Lattner1cd66982010-06-27 05:56:15 +0000645 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000646 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +0000647 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000648
649 return SrcPtr;
650}
651
Chris Lattner055097f2010-06-27 06:26:04 +0000652/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
653/// are either integers or pointers. This does a truncation of the value if it
654/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000655///
656/// This behaves as if the value were coerced through memory, so on big-endian
657/// targets the high bits are preserved in a truncation, while little-endian
658/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +0000659static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +0000660 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +0000661 CodeGenFunction &CGF) {
662 if (Val->getType() == Ty)
663 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000664
Chris Lattner055097f2010-06-27 06:26:04 +0000665 if (isa<llvm::PointerType>(Val->getType())) {
666 // If this is Pointer->Pointer avoid conversion to and from int.
667 if (isa<llvm::PointerType>(Ty))
668 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000669
Chris Lattner055097f2010-06-27 06:26:04 +0000670 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +0000671 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +0000672 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000673
Chris Lattner2192fe52011-07-18 04:24:23 +0000674 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +0000675 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +0000676 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000677
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000678 if (Val->getType() != DestIntTy) {
679 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
680 if (DL.isBigEndian()) {
681 // Preserve the high bits on big-endian targets.
682 // That is what memory coercion does.
683 uint64_t SrcSize = DL.getTypeAllocSizeInBits(Val->getType());
684 uint64_t DstSize = DL.getTypeAllocSizeInBits(DestIntTy);
685 if (SrcSize > DstSize) {
686 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
687 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
688 } else {
689 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
690 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
691 }
692 } else {
693 // Little-endian targets preserve the low bits. No shifts required.
694 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
695 }
696 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000697
Chris Lattner055097f2010-06-27 06:26:04 +0000698 if (isa<llvm::PointerType>(Ty))
699 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
700 return Val;
701}
702
Chris Lattner1cd66982010-06-27 05:56:15 +0000703
704
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000705/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
706/// a pointer to an object of type \arg Ty.
707///
708/// This safely handles the case when the src type is smaller than the
709/// destination type; in this situation the values of bits which not
710/// present in the src are undefined.
711static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000712 llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000713 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000714 llvm::Type *SrcTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000715 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000716
Chris Lattnerd200eda2010-06-28 22:51:39 +0000717 // If SrcTy and Ty are the same, just do a load.
718 if (SrcTy == Ty)
719 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000720
Micah Villmowdd31ca12012-10-08 16:25:52 +0000721 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000722
Chris Lattner2192fe52011-07-18 04:24:23 +0000723 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000724 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000725 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
726 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000727
Micah Villmowdd31ca12012-10-08 16:25:52 +0000728 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000729
Chris Lattner055097f2010-06-27 06:26:04 +0000730 // If the source and destination are integer or pointer types, just do an
731 // extension or truncation to the desired type.
732 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
733 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
734 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
735 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
736 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000737
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000738 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000739 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +0000740 // Generally SrcSize is never greater than DstSize, since this means we are
741 // losing bits. However, this can happen in cases where the structure has
742 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000743 //
Mike Stump18bb9282009-05-16 07:57:57 +0000744 // FIXME: Assert that we aren't truncating non-padding bits when have access
745 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000746 llvm::Value *Casted =
747 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000748 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
749 // FIXME: Use better alignment / avoid requiring aligned load.
750 Load->setAlignment(1);
751 return Load;
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000752 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000753
Chris Lattner3fcc7902010-06-27 01:06:27 +0000754 // Otherwise do coercion through memory. This is stupid, but
755 // simple.
756 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
Manman Ren84b921f2012-11-28 22:08:52 +0000757 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
758 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
759 llvm::Value *SrcCasted = CGF.Builder.CreateBitCast(SrcPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000760 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000761 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
762 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
763 1, false);
Chris Lattner3fcc7902010-06-27 01:06:27 +0000764 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000765}
766
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000767// Function to store a first-class aggregate into memory. We prefer to
768// store the elements rather than the aggregate to be more friendly to
769// fast-isel.
770// FIXME: Do we need to recurse here?
771static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
772 llvm::Value *DestPtr, bool DestIsVolatile,
773 bool LowAlignment) {
774 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +0000775 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000776 dyn_cast<llvm::StructType>(Val->getType())) {
777 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
778 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
779 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
780 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
781 DestIsVolatile);
782 if (LowAlignment)
783 SI->setAlignment(1);
784 }
785 } else {
Bill Wendlingf6af30f2012-03-16 21:45:12 +0000786 llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
787 if (LowAlignment)
788 SI->setAlignment(1);
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000789 }
790}
791
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000792/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
793/// where the source and destination may have different types.
794///
795/// This safely handles the case when the src type is larger than the
796/// destination type; the upper bits of the src will be lost.
797static void CreateCoercedStore(llvm::Value *Src,
798 llvm::Value *DstPtr,
Anders Carlsson17490832009-12-24 20:40:36 +0000799 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000800 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000801 llvm::Type *SrcTy = Src->getType();
802 llvm::Type *DstTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000803 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +0000804 if (SrcTy == DstTy) {
805 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
806 return;
807 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000808
Micah Villmowdd31ca12012-10-08 16:25:52 +0000809 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000810
Chris Lattner2192fe52011-07-18 04:24:23 +0000811 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000812 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
813 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
814 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000815
Chris Lattner055097f2010-06-27 06:26:04 +0000816 // If the source and destination are integer or pointer types, just do an
817 // extension or truncation to the desired type.
818 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
819 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
820 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
821 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
822 return;
823 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000824
Micah Villmowdd31ca12012-10-08 16:25:52 +0000825 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000826
Daniel Dunbar313321e2009-02-03 05:31:23 +0000827 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000828 if (SrcSize <= DstSize) {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000829 llvm::Value *Casted =
830 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000831 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000832 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000833 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000834 // Otherwise do coercion through memory. This is stupid, but
835 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000836
837 // Generally SrcSize is never greater than DstSize, since this means we are
838 // losing bits. However, this can happen in cases where the structure has
839 // additional padding, for example due to a user specified alignment.
840 //
841 // FIXME: Assert that we aren't truncating non-padding bits when have access
842 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000843 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
844 CGF.Builder.CreateStore(Src, Tmp);
Manman Ren84b921f2012-11-28 22:08:52 +0000845 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
846 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
847 llvm::Value *DstCasted = CGF.Builder.CreateBitCast(DstPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000848 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000849 CGF.Builder.CreateMemCpy(DstCasted, Casted,
850 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
851 1, false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000852 }
853}
854
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000855/***/
856
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000857bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000858 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +0000859}
860
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000861bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
862 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
863 switch (BT->getKind()) {
864 default:
865 return false;
866 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +0000867 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000868 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +0000869 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000870 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +0000871 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000872 }
873 }
874
875 return false;
876}
877
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000878bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
879 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
880 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
881 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +0000882 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000883 }
884 }
885
886 return false;
887}
888
Chris Lattnera5f58b02011-07-09 17:41:47 +0000889llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +0000890 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
891 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +0000892}
893
Chris Lattnera5f58b02011-07-09 17:41:47 +0000894llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +0000895CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000896
897 bool Inserted = FunctionsBeingProcessed.insert(&FI); (void)Inserted;
898 assert(Inserted && "Recursively being processed?");
899
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000900 SmallVector<llvm::Type*, 8> argTypes;
Chris Lattner2192fe52011-07-18 04:24:23 +0000901 llvm::Type *resultType = 0;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000902
John McCall85dd2c52011-05-15 02:19:42 +0000903 const ABIArgInfo &retAI = FI.getReturnInfo();
904 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +0000905 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +0000906 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +0000907
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000908 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +0000909 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +0000910 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +0000911 break;
912
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000913 case ABIArgInfo::Indirect: {
John McCall85dd2c52011-05-15 02:19:42 +0000914 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
915 resultType = llvm::Type::getVoidTy(getLLVMContext());
916
917 QualType ret = FI.getReturnType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000918 llvm::Type *ty = ConvertType(ret);
John McCall85dd2c52011-05-15 02:19:42 +0000919 unsigned addressSpace = Context.getTargetAddressSpace(ret);
920 argTypes.push_back(llvm::PointerType::get(ty, addressSpace));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000921 break;
922 }
923
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000924 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +0000925 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000926 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000927 }
Mike Stump11289f42009-09-09 15:08:12 +0000928
John McCallc818bbb2012-12-07 07:03:17 +0000929 // Add in all of the required arguments.
930 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), ie;
931 if (FI.isVariadic()) {
932 ie = it + FI.getRequiredArgs().getNumRequiredArgs();
933 } else {
934 ie = FI.arg_end();
935 }
936 for (; it != ie; ++it) {
John McCall85dd2c52011-05-15 02:19:42 +0000937 const ABIArgInfo &argAI = it->info;
Mike Stump11289f42009-09-09 15:08:12 +0000938
Rafael Espindolafad28de2012-10-24 01:59:00 +0000939 // Insert a padding type to ensure proper alignment.
940 if (llvm::Type *PaddingType = argAI.getPaddingType())
941 argTypes.push_back(PaddingType);
942
John McCall85dd2c52011-05-15 02:19:42 +0000943 switch (argAI.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000944 case ABIArgInfo::Ignore:
945 break;
946
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000947 case ABIArgInfo::Indirect: {
948 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +0000949 llvm::Type *LTy = ConvertTypeForMem(it->type);
John McCall85dd2c52011-05-15 02:19:42 +0000950 argTypes.push_back(LTy->getPointerTo());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000951 break;
952 }
953
954 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +0000955 case ABIArgInfo::Direct: {
Chris Lattner3dd716c2010-06-28 23:44:11 +0000956 // If the coerce-to type is a first class aggregate, flatten it. Either
957 // way is semantically identical, but fast-isel and the optimizer
958 // generally likes scalar values better than FCAs.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000959 llvm::Type *argType = argAI.getCoerceToType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000960 if (llvm::StructType *st = dyn_cast<llvm::StructType>(argType)) {
John McCall85dd2c52011-05-15 02:19:42 +0000961 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
962 argTypes.push_back(st->getElementType(i));
Chris Lattner3dd716c2010-06-28 23:44:11 +0000963 } else {
John McCall85dd2c52011-05-15 02:19:42 +0000964 argTypes.push_back(argType);
Chris Lattner3dd716c2010-06-28 23:44:11 +0000965 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +0000966 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +0000967 }
Mike Stump11289f42009-09-09 15:08:12 +0000968
Daniel Dunbard3674e62008-09-11 01:48:57 +0000969 case ABIArgInfo::Expand:
Chris Lattnera5f58b02011-07-09 17:41:47 +0000970 GetExpandedTypes(it->type, argTypes);
Daniel Dunbard3674e62008-09-11 01:48:57 +0000971 break;
972 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000973 }
974
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000975 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
976 assert(Erased && "Not in set?");
977
John McCalla729c622012-02-17 03:33:10 +0000978 return llvm::FunctionType::get(resultType, argTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +0000979}
980
Chris Lattner2192fe52011-07-18 04:24:23 +0000981llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +0000982 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +0000983 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000984
Chris Lattner8806e322011-07-10 00:18:59 +0000985 if (!isFuncTypeConvertible(FPT))
986 return llvm::StructType::get(getLLVMContext());
987
988 const CGFunctionInfo *Info;
989 if (isa<CXXDestructorDecl>(MD))
John McCalla729c622012-02-17 03:33:10 +0000990 Info = &arrangeCXXDestructor(cast<CXXDestructorDecl>(MD), GD.getDtorType());
Chris Lattner8806e322011-07-10 00:18:59 +0000991 else
John McCalla729c622012-02-17 03:33:10 +0000992 Info = &arrangeCXXMethodDeclaration(MD);
993 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +0000994}
995
Daniel Dunbar3668cb22009-02-02 23:43:58 +0000996void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbard931a872009-02-02 22:03:45 +0000997 const Decl *TargetDecl,
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000998 AttributeListType &PAL,
Bill Wendlingf4d64cb2013-02-22 00:13:35 +0000999 unsigned &CallingConv,
1000 bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001001 llvm::AttrBuilder FuncAttrs;
1002 llvm::AttrBuilder RetAttrs;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001003
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001004 CallingConv = FI.getEffectiveCallingConvention();
1005
John McCallab26cfa2010-02-05 21:31:56 +00001006 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001007 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001008
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001009 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001010 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001011 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001012 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001013 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001014 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001015 if (TargetDecl->hasAttr<NoReturnAttr>())
1016 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
1017
1018 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
John McCallbe349de2010-07-08 06:48:12 +00001019 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl31ad7542011-03-13 17:09:40 +00001020 if (FPT && FPT->isNothrow(getContext()))
Bill Wendling207f0532012-12-20 19:27:06 +00001021 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith49af6292013-03-05 08:30:04 +00001022 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1023 // These attributes are not inherited by overloads.
1024 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1025 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001026 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001027 }
1028
Eric Christopherbf005ec2011-08-15 22:38:22 +00001029 // 'const' and 'pure' attribute functions are also nounwind.
1030 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001031 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1032 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001033 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001034 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1035 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001036 }
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001037 if (TargetDecl->hasAttr<MallocAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001038 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001039 }
1040
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001041 if (CodeGenOpts.OptimizeSize)
Bill Wendling207f0532012-12-20 19:27:06 +00001042 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
Quentin Colombet5ee5ca12012-10-26 00:29:48 +00001043 if (CodeGenOpts.OptimizeSize == 2)
Bill Wendling207f0532012-12-20 19:27:06 +00001044 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001045 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001046 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001047 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001048 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Devang Patel6e467b12009-06-04 23:32:02 +00001049
Bill Wendling2f81db62013-02-22 20:53:29 +00001050 if (AttrOnCallSite) {
1051 // Attributes that should go on the call site only.
1052 if (!CodeGenOpts.SimplifyLibCalls)
1053 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Bill Wendling706469b2013-02-28 22:49:57 +00001054 } else {
1055 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001056 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001057 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001058 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001059 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001060 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001061 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001062 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001063 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001064 }
1065
Bill Wendlingdabafea2013-03-13 22:24:33 +00001066 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001067 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001068 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001069 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001070 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001071 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001072 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001073 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001074 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001075 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001076 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001077 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001078
Bill Wendlingd8f49502013-08-01 21:41:02 +00001079 if (!CodeGenOpts.StackRealignment)
1080 FuncAttrs.addAttribute("no-realign-stack");
Bill Wendling985d1c52013-02-15 21:30:01 +00001081 }
1082
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001083 QualType RetTy = FI.getReturnType();
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001084 unsigned Index = 1;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001085 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001086 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001087 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001088 if (RetTy->hasSignedIntegerRepresentation())
1089 RetAttrs.addAttribute(llvm::Attribute::SExt);
1090 else if (RetTy->hasUnsignedIntegerRepresentation())
1091 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001092 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001093 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001094 if (RetAI.getInReg())
1095 RetAttrs.addAttribute(llvm::Attribute::InReg);
1096 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001097 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001098 break;
1099
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001100 case ABIArgInfo::Indirect: {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001101 llvm::AttrBuilder SRETAttrs;
Bill Wendling207f0532012-12-20 19:27:06 +00001102 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001103 if (RetAI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001104 SRETAttrs.addAttribute(llvm::Attribute::InReg);
Bill Wendlinga7912f82012-10-10 07:36:56 +00001105 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001106 AttributeSet::get(getLLVMContext(), Index, SRETAttrs));
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001107
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001108 ++Index;
Daniel Dunbarc2304432009-03-18 19:51:01 +00001109 // sret disables readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001110 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1111 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001112 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001113 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001114
Daniel Dunbard3674e62008-09-11 01:48:57 +00001115 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001116 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001117 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001118
Bill Wendlinga7912f82012-10-10 07:36:56 +00001119 if (RetAttrs.hasAttributes())
1120 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001121 AttributeSet::get(getLLVMContext(),
1122 llvm::AttributeSet::ReturnIndex,
1123 RetAttrs));
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001124
Mike Stump11289f42009-09-09 15:08:12 +00001125 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
Daniel Dunbar313321e2009-02-03 05:31:23 +00001126 ie = FI.arg_end(); it != ie; ++it) {
1127 QualType ParamType = it->type;
1128 const ABIArgInfo &AI = it->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001129 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001130
Rafael Espindolafad28de2012-10-24 01:59:00 +00001131 if (AI.getPaddingType()) {
Bill Wendling290d9522013-01-27 02:46:53 +00001132 if (AI.getPaddingInReg())
1133 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index,
1134 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001135 // Increment Index if there is padding.
1136 ++Index;
1137 }
1138
John McCall39ec71f2010-03-27 00:47:27 +00001139 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1140 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001141 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001142 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001143 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001144 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001145 Attrs.addAttribute(llvm::Attribute::SExt);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001146 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001147 Attrs.addAttribute(llvm::Attribute::ZExt);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001148 // FALL THROUGH
1149 case ABIArgInfo::Direct:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001150 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001151 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001152
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001153 // FIXME: handle sseregparm someday...
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001154
Chris Lattner2192fe52011-07-18 04:24:23 +00001155 if (llvm::StructType *STy =
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001156 dyn_cast<llvm::StructType>(AI.getCoerceToType())) {
1157 unsigned Extra = STy->getNumElements()-1; // 1 will be added below.
Bill Wendlinga7912f82012-10-10 07:36:56 +00001158 if (Attrs.hasAttributes())
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001159 for (unsigned I = 0; I < Extra; ++I)
Bill Wendling290d9522013-01-27 02:46:53 +00001160 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index + I,
1161 Attrs));
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001162 Index += Extra;
1163 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001164 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001165
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001166 case ABIArgInfo::Indirect:
Rafael Espindola703c47f2012-10-19 05:04:37 +00001167 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001168 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001169
Anders Carlsson20759ad2009-09-16 15:53:40 +00001170 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001171 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001172
Bill Wendlinga7912f82012-10-10 07:36:56 +00001173 Attrs.addAlignmentAttr(AI.getIndirectAlign());
1174
Daniel Dunbarc2304432009-03-18 19:51:01 +00001175 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001176 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1177 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001178 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001179
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001180 case ABIArgInfo::Ignore:
1181 // Skip increment, no matching LLVM parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001182 continue;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001183
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001184 case ABIArgInfo::Expand: {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001185 SmallVector<llvm::Type*, 8> types;
Mike Stump18bb9282009-05-16 07:57:57 +00001186 // FIXME: This is rather inefficient. Do we ever actually need to do
1187 // anything here? The result should be just reconstructed on the other
1188 // side, so extension should be a non-issue.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001189 getTypes().GetExpandedTypes(ParamType, types);
John McCall85dd2c52011-05-15 02:19:42 +00001190 Index += types.size();
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001191 continue;
1192 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001193 }
Mike Stump11289f42009-09-09 15:08:12 +00001194
Bill Wendlinga7912f82012-10-10 07:36:56 +00001195 if (Attrs.hasAttributes())
Bill Wendling290d9522013-01-27 02:46:53 +00001196 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index, Attrs));
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001197 ++Index;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001198 }
Bill Wendlinga7912f82012-10-10 07:36:56 +00001199 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001200 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001201 AttributeSet::get(getLLVMContext(),
1202 llvm::AttributeSet::FunctionIndex,
1203 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001204}
1205
John McCalla738c252011-03-09 04:27:21 +00001206/// An argument came in as a promoted argument; demote it back to its
1207/// declared type.
1208static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1209 const VarDecl *var,
1210 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001211 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001212
1213 // This can happen with promotions that actually don't change the
1214 // underlying type, like the enum promotions.
1215 if (value->getType() == varType) return value;
1216
1217 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1218 && "unexpected promotion type");
1219
1220 if (isa<llvm::IntegerType>(varType))
1221 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1222
1223 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1224}
1225
Daniel Dunbard931a872009-02-02 22:03:45 +00001226void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1227 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00001228 const FunctionArgList &Args) {
John McCallcaa19452009-07-28 01:00:58 +00001229 // If this is an implicit-return-zero function, go ahead and
1230 // initialize the return value. TODO: it might be nice to have
1231 // a more general mechanism for this that didn't require synthesized
1232 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00001233 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00001234 if (FD->hasImplicitReturnZero()) {
1235 QualType RetTy = FD->getResultType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001236 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00001237 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00001238 Builder.CreateStore(Zero, ReturnValue);
1239 }
1240 }
1241
Mike Stump18bb9282009-05-16 07:57:57 +00001242 // FIXME: We no longer need the types from FunctionArgList; lift up and
1243 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00001244
Daniel Dunbar613855c2008-09-09 23:27:19 +00001245 // Emit allocs for param decls. Give the LLVM Argument nodes names.
1246 llvm::Function::arg_iterator AI = Fn->arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00001247
Daniel Dunbar613855c2008-09-09 23:27:19 +00001248 // Name the struct return argument.
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001249 if (CGM.ReturnTypeUsesSRet(FI)) {
Daniel Dunbar613855c2008-09-09 23:27:19 +00001250 AI->setName("agg.result");
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001251 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1252 AI->getArgNo() + 1,
1253 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00001254 ++AI;
1255 }
Mike Stump11289f42009-09-09 15:08:12 +00001256
Reid Kleckner739756c2013-12-04 19:23:12 +00001257 // Create a pointer value for every parameter declaration. This usually
1258 // entails copying one or more LLVM IR arguments into an alloca. Don't push
1259 // any cleanups or do anything that might unwind. We do that separately, so
1260 // we can push the cleanups in the correct order for the ABI.
1261 SmallVector<llvm::Value *, 16> ArgVals;
1262 ArgVals.reserve(Args.size());
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00001263 assert(FI.arg_size() == Args.size() &&
1264 "Mismatch between function signature & arguments.");
Devang Patel68a15252011-03-03 20:13:15 +00001265 unsigned ArgNo = 1;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001266 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Devang Patel68a15252011-03-03 20:13:15 +00001267 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
1268 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00001269 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001270 QualType Ty = info_it->type;
1271 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001272
John McCalla738c252011-03-09 04:27:21 +00001273 bool isPromoted =
1274 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1275
Rafael Espindolafad28de2012-10-24 01:59:00 +00001276 // Skip the dummy padding argument.
1277 if (ArgI.getPaddingType())
1278 ++AI;
1279
Daniel Dunbard3674e62008-09-11 01:48:57 +00001280 switch (ArgI.getKind()) {
Daniel Dunbar747865a2009-02-05 09:16:39 +00001281 case ABIArgInfo::Indirect: {
Chris Lattner3dd716c2010-06-28 23:44:11 +00001282 llvm::Value *V = AI;
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001283
John McCall47fb9502013-03-07 21:37:08 +00001284 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001285 // Aggregates and complex variables are accessed by reference. All we
1286 // need to do is realign the value, if requested
1287 if (ArgI.getIndirectRealign()) {
1288 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1289
1290 // Copy from the incoming argument pointer to the temporary with the
1291 // appropriate alignment.
1292 //
1293 // FIXME: We should have a common utility for generating an aggregate
1294 // copy.
Chris Lattner2192fe52011-07-18 04:24:23 +00001295 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyck705ba072011-01-19 01:58:38 +00001296 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumidd634362011-03-10 14:02:21 +00001297 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1298 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1299 Builder.CreateMemCpy(Dst,
1300 Src,
Ken Dyck705ba072011-01-19 01:58:38 +00001301 llvm::ConstantInt::get(IntPtrTy,
1302 Size.getQuantity()),
Benjamin Krameracc6b4e2010-12-30 00:13:21 +00001303 ArgI.getIndirectAlign(),
1304 false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001305 V = AlignedTemp;
1306 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00001307 } else {
1308 // Load scalar value from indirect argument.
Ken Dyck705ba072011-01-19 01:58:38 +00001309 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
Nick Lewycky2d84e842013-10-02 02:29:49 +00001310 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty,
1311 Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001312
1313 if (isPromoted)
1314 V = emitArgumentDemotion(*this, Arg, V);
Daniel Dunbar747865a2009-02-05 09:16:39 +00001315 }
Reid Kleckner739756c2013-12-04 19:23:12 +00001316 ArgVals.push_back(V);
Daniel Dunbar747865a2009-02-05 09:16:39 +00001317 break;
1318 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001319
1320 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001321 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00001322
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001323 // If we have the trivial case, handle it with no muss and fuss.
1324 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001325 ArgI.getCoerceToType() == ConvertType(Ty) &&
1326 ArgI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001327 assert(AI != Fn->arg_end() && "Argument mismatch!");
1328 llvm::Value *V = AI;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001329
Bill Wendling507c3512012-10-16 05:23:44 +00001330 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001331 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1332 AI->getArgNo() + 1,
1333 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00001334
Chris Lattner7369c142011-07-20 06:29:00 +00001335 // Ensure the argument is the correct type.
1336 if (V->getType() != ArgI.getCoerceToType())
1337 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1338
John McCalla738c252011-03-09 04:27:21 +00001339 if (isPromoted)
1340 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00001341
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001342 if (const CXXMethodDecl *MD =
1343 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001344 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001345 V = CGM.getCXXABI().
1346 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001347 }
1348
Rafael Espindola8778c282012-11-29 16:09:03 +00001349 // Because of merging of function types from multiple decls it is
1350 // possible for the type of an argument to not match the corresponding
1351 // type in the function type. Since we are codegening the callee
1352 // in here, add a cast to the argument type.
1353 llvm::Type *LTy = ConvertType(Arg->getType());
1354 if (V->getType() != LTy)
1355 V = Builder.CreateBitCast(V, LTy);
1356
Reid Kleckner739756c2013-12-04 19:23:12 +00001357 ArgVals.push_back(V);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001358 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00001359 }
Mike Stump11289f42009-09-09 15:08:12 +00001360
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001361 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001362
Chris Lattnerff941a62010-07-28 18:24:28 +00001363 // The alignment we need to use is the max of the requested alignment for
1364 // the argument plus the alignment required by our access code below.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001365 unsigned AlignmentToUse =
Micah Villmowdd31ca12012-10-08 16:25:52 +00001366 CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerff941a62010-07-28 18:24:28 +00001367 AlignmentToUse = std::max(AlignmentToUse,
1368 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001369
Chris Lattnerff941a62010-07-28 18:24:28 +00001370 Alloca->setAlignment(AlignmentToUse);
Chris Lattnerc401de92010-07-05 20:21:00 +00001371 llvm::Value *V = Alloca;
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001372 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001373
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001374 // If the value is offset in memory, apply the offset now.
1375 if (unsigned Offs = ArgI.getDirectOffset()) {
1376 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1377 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001378 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001379 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1380 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001381
Chris Lattner15ec3612010-06-29 00:06:42 +00001382 // If the coerce-to type is a first class aggregate, we flatten it and
1383 // pass the elements. Either way is semantically identical, but fast-isel
1384 // and the optimizer generally likes scalar values better than FCAs.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001385 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
1386 if (STy && STy->getNumElements() > 1) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001387 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001388 llvm::Type *DstTy =
1389 cast<llvm::PointerType>(Ptr->getType())->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00001390 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001391
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001392 if (SrcSize <= DstSize) {
1393 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1394
1395 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1396 assert(AI != Fn->arg_end() && "Argument mismatch!");
1397 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1398 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
1399 Builder.CreateStore(AI++, EltPtr);
1400 }
1401 } else {
1402 llvm::AllocaInst *TempAlloca =
1403 CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1404 TempAlloca->setAlignment(AlignmentToUse);
1405 llvm::Value *TempV = TempAlloca;
1406
1407 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1408 assert(AI != Fn->arg_end() && "Argument mismatch!");
1409 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1410 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(TempV, 0, i);
1411 Builder.CreateStore(AI++, EltPtr);
1412 }
1413
1414 Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
Chris Lattner15ec3612010-06-29 00:06:42 +00001415 }
1416 } else {
1417 // Simple case, just do a coerced store of the argument into the alloca.
1418 assert(AI != Fn->arg_end() && "Argument mismatch!");
Chris Lattner9e748e92010-06-29 00:14:52 +00001419 AI->setName(Arg->getName() + ".coerce");
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001420 CreateCoercedStore(AI++, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00001421 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001422
1423
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001424 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00001425 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001426 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001427 if (isPromoted)
1428 V = emitArgumentDemotion(*this, Arg, V);
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00001429 }
Reid Kleckner739756c2013-12-04 19:23:12 +00001430 ArgVals.push_back(V);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001431 continue; // Skip ++AI increment, already done.
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001432 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001433
1434 case ABIArgInfo::Expand: {
1435 // If this structure was expanded into multiple arguments then
1436 // we need to create a temporary and reconstruct it from the
1437 // arguments.
Eli Friedman3d9f47f2011-11-03 21:39:02 +00001438 llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
Eli Friedmana0544d62011-12-03 04:14:32 +00001439 CharUnits Align = getContext().getDeclAlign(Arg);
1440 Alloca->setAlignment(Align.getQuantity());
1441 LValue LV = MakeAddrLValue(Alloca, Ty, Align);
Eli Friedman3d9f47f2011-11-03 21:39:02 +00001442 llvm::Function::arg_iterator End = ExpandTypeFromArgs(Ty, LV, AI);
Reid Kleckner739756c2013-12-04 19:23:12 +00001443 ArgVals.push_back(Alloca);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001444
1445 // Name the arguments used in expansion and increment AI.
1446 unsigned Index = 0;
1447 for (; AI != End; ++AI, ++Index)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001448 AI->setName(Arg->getName() + "." + Twine(Index));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001449 continue;
1450 }
1451
1452 case ABIArgInfo::Ignore:
1453 // Initialize the local variable appropriately.
John McCall47fb9502013-03-07 21:37:08 +00001454 if (!hasScalarEvaluationKind(Ty))
Reid Kleckner739756c2013-12-04 19:23:12 +00001455 ArgVals.push_back(CreateMemTemp(Ty));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001456 else
Reid Kleckner739756c2013-12-04 19:23:12 +00001457 ArgVals.push_back(llvm::UndefValue::get(ConvertType(Arg->getType())));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001458
1459 // Skip increment, no matching LLVM parameter.
1460 continue;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001461 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001462
1463 ++AI;
Daniel Dunbar613855c2008-09-09 23:27:19 +00001464 }
1465 assert(AI == Fn->arg_end() && "Argument mismatch!");
Reid Kleckner739756c2013-12-04 19:23:12 +00001466
1467 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1468 for (int I = Args.size() - 1; I >= 0; --I)
1469 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
1470 } else {
1471 for (unsigned I = 0, E = Args.size(); I != E; ++I)
1472 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
1473 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00001474}
1475
John McCallffa2c1a2012-01-29 07:46:59 +00001476static void eraseUnusedBitCasts(llvm::Instruction *insn) {
1477 while (insn->use_empty()) {
1478 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
1479 if (!bitcast) return;
1480
1481 // This is "safe" because we would have used a ConstantExpr otherwise.
1482 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
1483 bitcast->eraseFromParent();
1484 }
1485}
1486
John McCall31168b02011-06-15 23:02:42 +00001487/// Try to emit a fused autorelease of a return result.
1488static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
1489 llvm::Value *result) {
1490 // We must be immediately followed the cast.
1491 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
1492 if (BB->empty()) return 0;
1493 if (&BB->back() != result) return 0;
1494
Chris Lattner2192fe52011-07-18 04:24:23 +00001495 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00001496
1497 // result is in a BasicBlock and is therefore an Instruction.
1498 llvm::Instruction *generator = cast<llvm::Instruction>(result);
1499
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001500 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00001501
1502 // Look for:
1503 // %generator = bitcast %type1* %generator2 to %type2*
1504 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
1505 // We would have emitted this as a constant if the operand weren't
1506 // an Instruction.
1507 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
1508
1509 // Require the generator to be immediately followed by the cast.
1510 if (generator->getNextNode() != bitcast)
1511 return 0;
1512
1513 insnsToKill.push_back(bitcast);
1514 }
1515
1516 // Look for:
1517 // %generator = call i8* @objc_retain(i8* %originalResult)
1518 // or
1519 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
1520 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
1521 if (!call) return 0;
1522
1523 bool doRetainAutorelease;
1524
1525 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
1526 doRetainAutorelease = true;
1527 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
1528 .objc_retainAutoreleasedReturnValue) {
1529 doRetainAutorelease = false;
1530
John McCallcfa4e9b2012-09-07 23:30:50 +00001531 // If we emitted an assembly marker for this call (and the
1532 // ARCEntrypoints field should have been set if so), go looking
1533 // for that call. If we can't find it, we can't do this
1534 // optimization. But it should always be the immediately previous
1535 // instruction, unless we needed bitcasts around the call.
1536 if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
1537 llvm::Instruction *prev = call->getPrevNode();
1538 assert(prev);
1539 if (isa<llvm::BitCastInst>(prev)) {
1540 prev = prev->getPrevNode();
1541 assert(prev);
1542 }
1543 assert(isa<llvm::CallInst>(prev));
1544 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
1545 CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
1546 insnsToKill.push_back(prev);
1547 }
John McCall31168b02011-06-15 23:02:42 +00001548 } else {
1549 return 0;
1550 }
1551
1552 result = call->getArgOperand(0);
1553 insnsToKill.push_back(call);
1554
1555 // Keep killing bitcasts, for sanity. Note that we no longer care
1556 // about precise ordering as long as there's exactly one use.
1557 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
1558 if (!bitcast->hasOneUse()) break;
1559 insnsToKill.push_back(bitcast);
1560 result = bitcast->getOperand(0);
1561 }
1562
1563 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001564 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00001565 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
1566 (*i)->eraseFromParent();
1567
1568 // Do the fused retain/autorelease if we were asked to.
1569 if (doRetainAutorelease)
1570 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
1571
1572 // Cast back to the result type.
1573 return CGF.Builder.CreateBitCast(result, resultType);
1574}
1575
John McCallffa2c1a2012-01-29 07:46:59 +00001576/// If this is a +1 of the value of an immutable 'self', remove it.
1577static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
1578 llvm::Value *result) {
1579 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00001580 const ObjCMethodDecl *method =
1581 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCallffa2c1a2012-01-29 07:46:59 +00001582 if (!method) return 0;
1583 const VarDecl *self = method->getSelfDecl();
1584 if (!self->getType().isConstQualified()) return 0;
1585
1586 // Look for a retain call.
1587 llvm::CallInst *retainCall =
1588 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
1589 if (!retainCall ||
1590 retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
1591 return 0;
1592
1593 // Look for an ordinary load of 'self'.
1594 llvm::Value *retainedValue = retainCall->getArgOperand(0);
1595 llvm::LoadInst *load =
1596 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
1597 if (!load || load->isAtomic() || load->isVolatile() ||
1598 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
1599 return 0;
1600
1601 // Okay! Burn it all down. This relies for correctness on the
1602 // assumption that the retain is emitted as part of the return and
1603 // that thereafter everything is used "linearly".
1604 llvm::Type *resultType = result->getType();
1605 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
1606 assert(retainCall->use_empty());
1607 retainCall->eraseFromParent();
1608 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
1609
1610 return CGF.Builder.CreateBitCast(load, resultType);
1611}
1612
John McCall31168b02011-06-15 23:02:42 +00001613/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00001614///
1615/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00001616static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
1617 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00001618 // If we're returning 'self', kill the initial retain. This is a
1619 // heuristic attempt to "encourage correctness" in the really unfortunate
1620 // case where we have a return of self during a dealloc and we desperately
1621 // need to avoid the possible autorelease.
1622 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
1623 return self;
1624
John McCall31168b02011-06-15 23:02:42 +00001625 // At -O0, try to emit a fused retain/autorelease.
1626 if (CGF.shouldUseFusedARCCalls())
1627 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
1628 return fused;
1629
1630 return CGF.EmitARCAutoreleaseReturnValue(result);
1631}
1632
John McCall6e1c0122012-01-29 02:35:02 +00001633/// Heuristically search for a dominating store to the return-value slot.
1634static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
1635 // If there are multiple uses of the return-value slot, just check
1636 // for something immediately preceding the IP. Sometimes this can
1637 // happen with how we generate implicit-returns; it can also happen
1638 // with noreturn cleanups.
1639 if (!CGF.ReturnValue->hasOneUse()) {
1640 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
1641 if (IP->empty()) return 0;
1642 llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back());
1643 if (!store) return 0;
1644 if (store->getPointerOperand() != CGF.ReturnValue) return 0;
1645 assert(!store->isAtomic() && !store->isVolatile()); // see below
1646 return store;
1647 }
1648
1649 llvm::StoreInst *store =
1650 dyn_cast<llvm::StoreInst>(CGF.ReturnValue->use_back());
1651 if (!store) return 0;
1652
1653 // These aren't actually possible for non-coerced returns, and we
1654 // only care about non-coerced returns on this code path.
1655 assert(!store->isAtomic() && !store->isVolatile());
1656
1657 // Now do a first-and-dirty dominance check: just walk up the
1658 // single-predecessors chain from the current insertion point.
1659 llvm::BasicBlock *StoreBB = store->getParent();
1660 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
1661 while (IP != StoreBB) {
1662 if (!(IP = IP->getSinglePredecessor()))
1663 return 0;
1664 }
1665
1666 // Okay, the store's basic block dominates the insertion point; we
1667 // can do our thing.
1668 return store;
1669}
1670
Adrian Prantl3be10542013-05-02 17:30:20 +00001671void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001672 bool EmitRetDbgLoc,
1673 SourceLocation EndLoc) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001674 // Functions with no result always return void.
Chris Lattner726b3d02010-06-26 23:13:19 +00001675 if (ReturnValue == 0) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001676 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00001677 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001678 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00001679
Dan Gohman481e40c2010-07-20 20:13:52 +00001680 llvm::DebugLoc RetDbgLoc;
Chris Lattner726b3d02010-06-26 23:13:19 +00001681 llvm::Value *RV = 0;
1682 QualType RetTy = FI.getReturnType();
1683 const ABIArgInfo &RetAI = FI.getReturnInfo();
1684
1685 switch (RetAI.getKind()) {
Daniel Dunbar03816342010-08-21 02:24:36 +00001686 case ABIArgInfo::Indirect: {
John McCall47fb9502013-03-07 21:37:08 +00001687 switch (getEvaluationKind(RetTy)) {
1688 case TEK_Complex: {
1689 ComplexPairTy RT =
Nick Lewycky2d84e842013-10-02 02:29:49 +00001690 EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
1691 EndLoc);
John McCall47fb9502013-03-07 21:37:08 +00001692 EmitStoreOfComplex(RT,
1693 MakeNaturalAlignAddrLValue(CurFn->arg_begin(), RetTy),
1694 /*isInit*/ true);
1695 break;
1696 }
1697 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00001698 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00001699 break;
1700 case TEK_Scalar:
1701 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
1702 MakeNaturalAlignAddrLValue(CurFn->arg_begin(), RetTy),
1703 /*isInit*/ true);
1704 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00001705 }
1706 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00001707 }
Chris Lattner726b3d02010-06-26 23:13:19 +00001708
1709 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001710 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001711 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
1712 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001713 // The internal return value temp always will have pointer-to-return-type
1714 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001715
John McCall6e1c0122012-01-29 02:35:02 +00001716 // If there is a dominating store to ReturnValue, we can elide
1717 // the load, zap the store, and usually zap the alloca.
1718 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00001719 // Reuse the debug location from the store unless there is
1720 // cleanup code to be emitted between the store and return
1721 // instruction.
1722 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00001723 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001724 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001725 RV = SI->getValueOperand();
1726 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001727
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001728 // If that was the only use of the return value, nuke it as well now.
1729 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
1730 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
1731 ReturnValue = 0;
1732 }
John McCall6e1c0122012-01-29 02:35:02 +00001733
1734 // Otherwise, we have to do a simple load.
1735 } else {
1736 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00001737 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001738 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001739 llvm::Value *V = ReturnValue;
1740 // If the value is offset in memory, apply the offset now.
1741 if (unsigned Offs = RetAI.getDirectOffset()) {
1742 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
1743 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001744 V = Builder.CreateBitCast(V,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001745 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
1746 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001747
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001748 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00001749 }
John McCall31168b02011-06-15 23:02:42 +00001750
1751 // In ARC, end functions that return a retainable type with a call
1752 // to objc_autoreleaseReturnValue.
1753 if (AutoreleaseResult) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001754 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001755 !FI.isReturnsRetained() &&
1756 RetTy->isObjCRetainableType());
1757 RV = emitAutoreleaseOfResult(*this, RV);
1758 }
1759
Chris Lattner726b3d02010-06-26 23:13:19 +00001760 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00001761
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001762 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00001763 break;
1764
1765 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001766 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00001767 }
1768
Daniel Dunbar6696e222010-06-30 21:27:58 +00001769 llvm::Instruction *Ret = RV ? Builder.CreateRet(RV) : Builder.CreateRetVoid();
Devang Patel65497582010-07-21 18:08:50 +00001770 if (!RetDbgLoc.isUnknown())
1771 Ret->setDebugLoc(RetDbgLoc);
Daniel Dunbar613855c2008-09-09 23:27:19 +00001772}
1773
John McCall32ea9692011-03-11 20:59:21 +00001774void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001775 const VarDecl *param,
1776 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00001777 // StartFunction converted the ABI-lowered parameter(s) into a
1778 // local alloca. We need to turn that into an r-value suitable
1779 // for EmitCall.
John McCall32ea9692011-03-11 20:59:21 +00001780 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00001781
John McCall32ea9692011-03-11 20:59:21 +00001782 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001783
John McCall23f66262010-05-26 22:34:26 +00001784 // For the most part, we just need to load the alloca, except:
1785 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall47fb9502013-03-07 21:37:08 +00001786 // 2) references to non-scalars are pointers directly to the aggregate.
1787 // I don't know why references to scalars are different here.
John McCall32ea9692011-03-11 20:59:21 +00001788 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall47fb9502013-03-07 21:37:08 +00001789 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall32ea9692011-03-11 20:59:21 +00001790 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00001791
1792 // Locals which are references to scalars are represented
1793 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00001794 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00001795 }
1796
Nick Lewycky2d84e842013-10-02 02:29:49 +00001797 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00001798}
1799
John McCall31168b02011-06-15 23:02:42 +00001800static bool isProvablyNull(llvm::Value *addr) {
1801 return isa<llvm::ConstantPointerNull>(addr);
1802}
1803
1804static bool isProvablyNonNull(llvm::Value *addr) {
1805 return isa<llvm::AllocaInst>(addr);
1806}
1807
1808/// Emit the actual writing-back of a writeback.
1809static void emitWriteback(CodeGenFunction &CGF,
1810 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00001811 const LValue &srcLV = writeback.Source;
1812 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00001813 assert(!isProvablyNull(srcAddr) &&
1814 "shouldn't have writeback for provably null argument");
1815
1816 llvm::BasicBlock *contBB = 0;
1817
1818 // If the argument wasn't provably non-null, we need to null check
1819 // before doing the store.
1820 bool provablyNonNull = isProvablyNonNull(srcAddr);
1821 if (!provablyNonNull) {
1822 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
1823 contBB = CGF.createBasicBlock("icr.done");
1824
1825 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
1826 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
1827 CGF.EmitBlock(writebackBB);
1828 }
1829
1830 // Load the value to writeback.
1831 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
1832
1833 // Cast it back, in case we're writing an id to a Foo* or something.
1834 value = CGF.Builder.CreateBitCast(value,
1835 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
1836 "icr.writeback-cast");
1837
1838 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00001839
1840 // If we have a "to use" value, it's something we need to emit a use
1841 // of. This has to be carefully threaded in: if it's done after the
1842 // release it's potentially undefined behavior (and the optimizer
1843 // will ignore it), and if it happens before the retain then the
1844 // optimizer could move the release there.
1845 if (writeback.ToUse) {
1846 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
1847
1848 // Retain the new value. No need to block-copy here: the block's
1849 // being passed up the stack.
1850 value = CGF.EmitARCRetainNonBlock(value);
1851
1852 // Emit the intrinsic use here.
1853 CGF.EmitARCIntrinsicUse(writeback.ToUse);
1854
1855 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00001856 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00001857
1858 // Put the new value in place (primitively).
1859 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
1860
1861 // Release the old value.
1862 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
1863
1864 // Otherwise, we can just do a normal lvalue store.
1865 } else {
1866 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
1867 }
John McCall31168b02011-06-15 23:02:42 +00001868
1869 // Jump to the continuation block.
1870 if (!provablyNonNull)
1871 CGF.EmitBlock(contBB);
1872}
1873
1874static void emitWritebacks(CodeGenFunction &CGF,
1875 const CallArgList &args) {
1876 for (CallArgList::writeback_iterator
1877 i = args.writeback_begin(), e = args.writeback_end(); i != e; ++i)
1878 emitWriteback(CGF, *i);
1879}
1880
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001881static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
1882 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00001883 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001884 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
1885 CallArgs.getCleanupsToDeactivate();
1886 // Iterate in reverse to increase the likelihood of popping the cleanup.
1887 for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
1888 I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
1889 CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
1890 I->IsActiveIP->eraseFromParent();
1891 }
1892}
1893
John McCalleff18842013-03-23 02:35:54 +00001894static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
1895 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
1896 if (uop->getOpcode() == UO_AddrOf)
1897 return uop->getSubExpr();
1898 return 0;
1899}
1900
John McCall31168b02011-06-15 23:02:42 +00001901/// Emit an argument that's being passed call-by-writeback. That is,
1902/// we are passing the address of
1903static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
1904 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00001905 LValue srcLV;
1906
1907 // Make an optimistic effort to emit the address as an l-value.
1908 // This can fail if the the argument expression is more complicated.
1909 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
1910 srcLV = CGF.EmitLValue(lvExpr);
1911
1912 // Otherwise, just emit it as a scalar.
1913 } else {
1914 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
1915
1916 QualType srcAddrType =
1917 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
1918 srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
1919 }
1920 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00001921
1922 // The dest and src types don't necessarily match in LLVM terms
1923 // because of the crazy ObjC compatibility rules.
1924
Chris Lattner2192fe52011-07-18 04:24:23 +00001925 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00001926 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
1927
1928 // If the address is a constant null, just pass the appropriate null.
1929 if (isProvablyNull(srcAddr)) {
1930 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
1931 CRE->getType());
1932 return;
1933 }
1934
John McCall31168b02011-06-15 23:02:42 +00001935 // Create the temporary.
1936 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
1937 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001938 // Loading an l-value can introduce a cleanup if the l-value is __weak,
1939 // and that cleanup will be conditional if we can't prove that the l-value
1940 // isn't null, so we need to register a dominating point so that the cleanups
1941 // system will make valid IR.
1942 CodeGenFunction::ConditionalEvaluation condEval(CGF);
1943
John McCall31168b02011-06-15 23:02:42 +00001944 // Zero-initialize it if we're not doing a copy-initialization.
1945 bool shouldCopy = CRE->shouldCopy();
1946 if (!shouldCopy) {
1947 llvm::Value *null =
1948 llvm::ConstantPointerNull::get(
1949 cast<llvm::PointerType>(destType->getElementType()));
1950 CGF.Builder.CreateStore(null, temp);
1951 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001952
John McCall31168b02011-06-15 23:02:42 +00001953 llvm::BasicBlock *contBB = 0;
John McCalleff18842013-03-23 02:35:54 +00001954 llvm::BasicBlock *originBB = 0;
John McCall31168b02011-06-15 23:02:42 +00001955
1956 // If the address is *not* known to be non-null, we need to switch.
1957 llvm::Value *finalArgument;
1958
1959 bool provablyNonNull = isProvablyNonNull(srcAddr);
1960 if (provablyNonNull) {
1961 finalArgument = temp;
1962 } else {
1963 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
1964
1965 finalArgument = CGF.Builder.CreateSelect(isNull,
1966 llvm::ConstantPointerNull::get(destType),
1967 temp, "icr.argument");
1968
1969 // If we need to copy, then the load has to be conditional, which
1970 // means we need control flow.
1971 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00001972 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00001973 contBB = CGF.createBasicBlock("icr.cont");
1974 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
1975 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
1976 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001977 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00001978 }
1979 }
1980
John McCalleff18842013-03-23 02:35:54 +00001981 llvm::Value *valueToUse = 0;
1982
John McCall31168b02011-06-15 23:02:42 +00001983 // Perform a copy if necessary.
1984 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001985 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00001986 assert(srcRV.isScalar());
1987
1988 llvm::Value *src = srcRV.getScalarVal();
1989 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
1990 "icr.cast");
1991
1992 // Use an ordinary store, not a store-to-lvalue.
1993 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00001994
1995 // If optimization is enabled, and the value was held in a
1996 // __strong variable, we need to tell the optimizer that this
1997 // value has to stay alive until we're doing the store back.
1998 // This is because the temporary is effectively unretained,
1999 // and so otherwise we can violate the high-level semantics.
2000 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2001 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
2002 valueToUse = src;
2003 }
John McCall31168b02011-06-15 23:02:42 +00002004 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002005
John McCall31168b02011-06-15 23:02:42 +00002006 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002007 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00002008 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002009 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00002010
2011 // Make a phi for the value to intrinsically use.
2012 if (valueToUse) {
2013 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2014 "icr.to-use");
2015 phiToUse->addIncoming(valueToUse, copyBB);
2016 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2017 originBB);
2018 valueToUse = phiToUse;
2019 }
2020
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002021 condEval.end(CGF);
2022 }
John McCall31168b02011-06-15 23:02:42 +00002023
John McCalleff18842013-03-23 02:35:54 +00002024 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00002025 args.add(RValue::get(finalArgument), CRE->getType());
2026}
2027
Reid Kleckner739756c2013-12-04 19:23:12 +00002028void CodeGenFunction::EmitCallArgs(CallArgList &Args,
2029 ArrayRef<QualType> ArgTypes,
2030 CallExpr::const_arg_iterator ArgBeg,
2031 CallExpr::const_arg_iterator ArgEnd,
2032 bool ForceColumnInfo) {
2033 CGDebugInfo *DI = getDebugInfo();
2034 SourceLocation CallLoc;
2035 if (DI) CallLoc = DI->getLocation();
2036
2037 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
2038 // because arguments are destroyed left to right in the callee.
2039 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2040 size_t CallArgsStart = Args.size();
2041 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
2042 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2043 EmitCallArg(Args, *Arg, ArgTypes[I]);
2044 // Restore the debug location.
2045 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2046 }
2047
2048 // Un-reverse the arguments we just evaluated so they match up with the LLVM
2049 // IR function.
2050 std::reverse(Args.begin() + CallArgsStart, Args.end());
2051 return;
2052 }
2053
2054 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
2055 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2056 assert(Arg != ArgEnd);
2057 EmitCallArg(Args, *Arg, ArgTypes[I]);
2058 // Restore the debug location.
2059 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2060 }
2061}
2062
John McCall32ea9692011-03-11 20:59:21 +00002063void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2064 QualType type) {
John McCall31168b02011-06-15 23:02:42 +00002065 if (const ObjCIndirectCopyRestoreExpr *CRE
2066 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002067 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00002068 assert(getContext().hasSameType(E->getType(), type));
2069 return emitWritebackArg(*this, args, CRE);
2070 }
2071
John McCall0a76c0c2011-08-26 18:42:59 +00002072 assert(type->isReferenceType() == E->isGLValue() &&
2073 "reference binding to unmaterialized r-value!");
2074
John McCall17054bd62011-08-26 21:08:13 +00002075 if (E->isGLValue()) {
2076 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00002077 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00002078 }
Mike Stump11289f42009-09-09 15:08:12 +00002079
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002080 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2081
2082 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2083 // However, we still have to push an EH-only cleanup in case we unwind before
2084 // we make it to the call.
2085 if (HasAggregateEvalKind &&
Reid Kleckner739756c2013-12-04 19:23:12 +00002086 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002087 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2088 if (RD && RD->hasNonTrivialDestructor()) {
2089 AggValueSlot Slot = CreateAggTemp(type, "agg.arg.tmp");
2090 Slot.setExternallyDestructed();
2091 EmitAggExpr(E, Slot);
2092 RValue RV = Slot.asRValue();
2093 args.add(RV, type);
2094
2095 pushDestroy(EHCleanup, RV.getAggregateAddr(), type, destroyCXXObject,
2096 /*useEHCleanupForArray*/ true);
2097 // This unreachable is a temporary marker which will be removed later.
2098 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2099 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
2100 return;
2101 }
2102 }
2103
2104 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00002105 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2106 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2107 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00002108 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2109 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2110 } else {
2111 // We can't represent a misaligned lvalue in the CallArgList, so copy
2112 // to an aligned temporary now.
2113 llvm::Value *tmp = CreateMemTemp(type);
2114 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2115 L.getAlignment());
2116 args.add(RValue::getAggregate(tmp), type);
2117 }
Eli Friedmandf968192011-05-26 00:10:27 +00002118 return;
2119 }
2120
John McCall32ea9692011-03-11 20:59:21 +00002121 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00002122}
2123
Dan Gohman515a60d2012-02-16 00:57:37 +00002124// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2125// optimizer it can aggressively ignore unwind edges.
2126void
2127CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2128 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2129 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2130 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2131 CGM.getNoObjCARCExceptionsMetadata());
2132}
2133
John McCall882987f2013-02-28 19:01:20 +00002134/// Emits a call to the given no-arguments nounwind runtime function.
2135llvm::CallInst *
2136CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2137 const llvm::Twine &name) {
2138 return EmitNounwindRuntimeCall(callee, ArrayRef<llvm::Value*>(), name);
2139}
2140
2141/// Emits a call to the given nounwind runtime function.
2142llvm::CallInst *
2143CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2144 ArrayRef<llvm::Value*> args,
2145 const llvm::Twine &name) {
2146 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2147 call->setDoesNotThrow();
2148 return call;
2149}
2150
2151/// Emits a simple call (never an invoke) to the given no-arguments
2152/// runtime function.
2153llvm::CallInst *
2154CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2155 const llvm::Twine &name) {
2156 return EmitRuntimeCall(callee, ArrayRef<llvm::Value*>(), name);
2157}
2158
2159/// Emits a simple call (never an invoke) to the given runtime
2160/// function.
2161llvm::CallInst *
2162CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2163 ArrayRef<llvm::Value*> args,
2164 const llvm::Twine &name) {
2165 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2166 call->setCallingConv(getRuntimeCC());
2167 return call;
2168}
2169
2170/// Emits a call or invoke to the given noreturn runtime function.
2171void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2172 ArrayRef<llvm::Value*> args) {
2173 if (getInvokeDest()) {
2174 llvm::InvokeInst *invoke =
2175 Builder.CreateInvoke(callee,
2176 getUnreachableBlock(),
2177 getInvokeDest(),
2178 args);
2179 invoke->setDoesNotReturn();
2180 invoke->setCallingConv(getRuntimeCC());
2181 } else {
2182 llvm::CallInst *call = Builder.CreateCall(callee, args);
2183 call->setDoesNotReturn();
2184 call->setCallingConv(getRuntimeCC());
2185 Builder.CreateUnreachable();
2186 }
Justin Bogner06bd6d02014-01-13 21:24:18 +00002187 PGO.setCurrentRegionUnreachable();
John McCall882987f2013-02-28 19:01:20 +00002188}
2189
2190/// Emits a call or invoke instruction to the given nullary runtime
2191/// function.
2192llvm::CallSite
2193CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2194 const Twine &name) {
2195 return EmitRuntimeCallOrInvoke(callee, ArrayRef<llvm::Value*>(), name);
2196}
2197
2198/// Emits a call or invoke instruction to the given runtime function.
2199llvm::CallSite
2200CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2201 ArrayRef<llvm::Value*> args,
2202 const Twine &name) {
2203 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2204 callSite.setCallingConv(getRuntimeCC());
2205 return callSite;
2206}
2207
2208llvm::CallSite
2209CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2210 const Twine &Name) {
2211 return EmitCallOrInvoke(Callee, ArrayRef<llvm::Value *>(), Name);
2212}
2213
John McCallbd309292010-07-06 01:34:17 +00002214/// Emits a call or invoke instruction to the given function, depending
2215/// on the current state of the EH stack.
2216llvm::CallSite
2217CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00002218 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002219 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00002220 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00002221
Dan Gohman515a60d2012-02-16 00:57:37 +00002222 llvm::Instruction *Inst;
2223 if (!InvokeDest)
2224 Inst = Builder.CreateCall(Callee, Args, Name);
2225 else {
2226 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
2227 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
2228 EmitBlock(ContBB);
2229 }
2230
2231 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2232 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002233 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00002234 AddObjCARCExceptionMetadata(Inst);
2235
2236 return Inst;
John McCallbd309292010-07-06 01:34:17 +00002237}
2238
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002239static void checkArgMatches(llvm::Value *Elt, unsigned &ArgNo,
2240 llvm::FunctionType *FTy) {
2241 if (ArgNo < FTy->getNumParams())
2242 assert(Elt->getType() == FTy->getParamType(ArgNo));
2243 else
2244 assert(FTy->isVarArg());
2245 ++ArgNo;
2246}
2247
Chris Lattnerd59d8672011-07-12 06:29:11 +00002248void CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV,
Craig Topper5603df42013-07-05 19:34:19 +00002249 SmallVectorImpl<llvm::Value *> &Args,
Chris Lattnerd59d8672011-07-12 06:29:11 +00002250 llvm::FunctionType *IRFuncTy) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002251 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2252 unsigned NumElts = AT->getSize().getZExtValue();
2253 QualType EltTy = AT->getElementType();
2254 llvm::Value *Addr = RV.getAggregateAddr();
2255 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
2256 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, Elt);
Nick Lewycky2d84e842013-10-02 02:29:49 +00002257 RValue EltRV = convertTempToRValue(EltAddr, EltTy, SourceLocation());
Bob Wilsone826a2a2011-08-03 05:58:22 +00002258 ExpandTypeToArgs(EltTy, EltRV, Args, IRFuncTy);
Chris Lattnerd59d8672011-07-12 06:29:11 +00002259 }
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002260 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002261 RecordDecl *RD = RT->getDecl();
2262 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
Eli Friedman7f1ff602012-04-16 03:54:45 +00002263 LValue LV = MakeAddrLValue(RV.getAggregateAddr(), Ty);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002264
2265 if (RD->isUnion()) {
2266 const FieldDecl *LargestFD = 0;
2267 CharUnits UnionSize = CharUnits::Zero();
2268
2269 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2270 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00002271 const FieldDecl *FD = *i;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002272 assert(!FD->isBitField() &&
2273 "Cannot expand structure with bit-field members.");
2274 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
2275 if (UnionSize < FieldSize) {
2276 UnionSize = FieldSize;
2277 LargestFD = FD;
2278 }
2279 }
2280 if (LargestFD) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002281 RValue FldRV = EmitRValueForField(LV, LargestFD, SourceLocation());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002282 ExpandTypeToArgs(LargestFD->getType(), FldRV, Args, IRFuncTy);
2283 }
2284 } else {
2285 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2286 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00002287 FieldDecl *FD = *i;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002288
Nick Lewycky2d84e842013-10-02 02:29:49 +00002289 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002290 ExpandTypeToArgs(FD->getType(), FldRV, Args, IRFuncTy);
2291 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00002292 }
Eli Friedman95ff7002011-11-15 02:46:03 +00002293 } else if (Ty->isAnyComplexType()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002294 ComplexPairTy CV = RV.getComplexVal();
2295 Args.push_back(CV.first);
2296 Args.push_back(CV.second);
2297 } else {
Chris Lattnerd59d8672011-07-12 06:29:11 +00002298 assert(RV.isScalar() &&
2299 "Unexpected non-scalar rvalue during struct expansion.");
2300
2301 // Insert a bitcast as needed.
2302 llvm::Value *V = RV.getScalarVal();
2303 if (Args.size() < IRFuncTy->getNumParams() &&
2304 V->getType() != IRFuncTy->getParamType(Args.size()))
2305 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(Args.size()));
2306
2307 Args.push_back(V);
2308 }
2309}
2310
2311
Daniel Dunbard931a872009-02-02 22:03:45 +00002312RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00002313 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00002314 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002315 const CallArgList &CallArgs,
David Chisnall9eecafa2010-05-01 11:15:56 +00002316 const Decl *TargetDecl,
David Chisnallff5f88c2010-05-02 13:41:58 +00002317 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00002318 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002319 SmallVector<llvm::Value*, 16> Args;
Daniel Dunbar613855c2008-09-09 23:27:19 +00002320
2321 // Handle struct-return functions by passing a pointer to the
2322 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00002323 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002324 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002325
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002326 // IRArgNo - Keep track of the argument number in the callee we're looking at.
2327 unsigned IRArgNo = 0;
2328 llvm::FunctionType *IRFuncTy =
2329 cast<llvm::FunctionType>(
2330 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00002331
Chris Lattner4ca97c32009-06-13 00:26:38 +00002332 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00002333 // alloca to hold the result, unless one is given to us.
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00002334 if (CGM.ReturnTypeUsesSRet(CallInfo)) {
Anders Carlsson17490832009-12-24 20:40:36 +00002335 llvm::Value *Value = ReturnValue.getValue();
2336 if (!Value)
Daniel Dunbara7566f12010-02-09 02:48:28 +00002337 Value = CreateMemTemp(RetTy);
Anders Carlsson17490832009-12-24 20:40:36 +00002338 Args.push_back(Value);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002339 checkArgMatches(Value, IRArgNo, IRFuncTy);
Anders Carlsson17490832009-12-24 20:40:36 +00002340 }
Mike Stump11289f42009-09-09 15:08:12 +00002341
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002342 assert(CallInfo.arg_size() == CallArgs.size() &&
2343 "Mismatch between function signature & arguments.");
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002344 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002345 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002346 I != E; ++I, ++info_it) {
2347 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00002348 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002349
John McCall47fb9502013-03-07 21:37:08 +00002350 CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002351
2352 // Insert a padding argument to ensure proper alignment.
2353 if (llvm::Type *PaddingType = ArgInfo.getPaddingType()) {
2354 Args.push_back(llvm::UndefValue::get(PaddingType));
2355 ++IRArgNo;
2356 }
2357
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002358 switch (ArgInfo.getKind()) {
Daniel Dunbar03816342010-08-21 02:24:36 +00002359 case ABIArgInfo::Indirect: {
Daniel Dunbar747865a2009-02-05 09:16:39 +00002360 if (RV.isScalar() || RV.isComplex()) {
2361 // Make a temporary alloca to pass the argument.
Eli Friedman7e68c882011-06-15 18:26:32 +00002362 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2363 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
2364 AI->setAlignment(ArgInfo.getIndirectAlign());
2365 Args.push_back(AI);
John McCall47fb9502013-03-07 21:37:08 +00002366
2367 LValue argLV =
2368 MakeAddrLValue(Args.back(), I->Ty, TypeAlign);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002369
Daniel Dunbar747865a2009-02-05 09:16:39 +00002370 if (RV.isScalar())
John McCall47fb9502013-03-07 21:37:08 +00002371 EmitStoreOfScalar(RV.getScalarVal(), argLV, /*init*/ true);
Daniel Dunbar747865a2009-02-05 09:16:39 +00002372 else
John McCall47fb9502013-03-07 21:37:08 +00002373 EmitStoreOfComplex(RV.getComplexVal(), argLV, /*init*/ true);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002374
2375 // Validate argument match.
2376 checkArgMatches(AI, IRArgNo, IRFuncTy);
Daniel Dunbar747865a2009-02-05 09:16:39 +00002377 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002378 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00002379 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002380 // 1. If the argument is not byval, and we are required to copy the
2381 // source. (This case doesn't occur on any common architecture.)
2382 // 2. If the argument is byval, RV is not sufficiently aligned, and
2383 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00002384 // 3. If the argument is byval, but RV is located in an address space
2385 // different than that of the argument (0).
Eli Friedmanf7456192011-06-15 22:09:18 +00002386 llvm::Value *Addr = RV.getAggregateAddr();
2387 unsigned Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002388 const llvm::DataLayout *TD = &CGM.getDataLayout();
Guy Benyei3832bfd2013-03-10 12:59:00 +00002389 const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
2390 const unsigned ArgAddrSpace = (IRArgNo < IRFuncTy->getNumParams() ?
2391 IRFuncTy->getParamType(IRArgNo)->getPointerAddressSpace() : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00002392 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall47fb9502013-03-07 21:37:08 +00002393 (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
Guy Benyei3832bfd2013-03-10 12:59:00 +00002394 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align) ||
2395 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002396 // Create an aligned temporary, and copy to it.
Eli Friedmanf7456192011-06-15 22:09:18 +00002397 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2398 if (Align > AI->getAlignment())
2399 AI->setAlignment(Align);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002400 Args.push_back(AI);
Chad Rosier615ed1a2012-03-29 17:37:10 +00002401 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002402
2403 // Validate argument match.
2404 checkArgMatches(AI, IRArgNo, IRFuncTy);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002405 } else {
2406 // Skip the extra memcpy call.
Eli Friedmanf7456192011-06-15 22:09:18 +00002407 Args.push_back(Addr);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002408
2409 // Validate argument match.
2410 checkArgMatches(Addr, IRArgNo, IRFuncTy);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002411 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002412 }
2413 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002414 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002415
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002416 case ABIArgInfo::Ignore:
2417 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002418
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002419 case ABIArgInfo::Extend:
2420 case ABIArgInfo::Direct: {
2421 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002422 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
2423 ArgInfo.getDirectOffset() == 0) {
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002424 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002425 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002426 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002427 else
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002428 V = Builder.CreateLoad(RV.getAggregateAddr());
2429
Chris Lattner3ce86682011-07-12 04:53:39 +00002430 // If the argument doesn't match, perform a bitcast to coerce it. This
2431 // can happen due to trivial type mismatches.
2432 if (IRArgNo < IRFuncTy->getNumParams() &&
2433 V->getType() != IRFuncTy->getParamType(IRArgNo))
2434 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRArgNo));
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002435 Args.push_back(V);
2436
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002437 checkArgMatches(V, IRArgNo, IRFuncTy);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002438 break;
2439 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002440
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002441 // FIXME: Avoid the conversion through memory if possible.
2442 llvm::Value *SrcPtr;
John McCall47fb9502013-03-07 21:37:08 +00002443 if (RV.isScalar() || RV.isComplex()) {
Eli Friedmanf4258eb2011-05-02 18:05:27 +00002444 SrcPtr = CreateMemTemp(I->Ty, "coerce");
John McCall47fb9502013-03-07 21:37:08 +00002445 LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
2446 if (RV.isScalar()) {
2447 EmitStoreOfScalar(RV.getScalarVal(), SrcLV, /*init*/ true);
2448 } else {
2449 EmitStoreOfComplex(RV.getComplexVal(), SrcLV, /*init*/ true);
2450 }
Mike Stump11289f42009-09-09 15:08:12 +00002451 } else
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002452 SrcPtr = RV.getAggregateAddr();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002453
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002454 // If the value is offset in memory, apply the offset now.
2455 if (unsigned Offs = ArgInfo.getDirectOffset()) {
2456 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
2457 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002458 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002459 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
2460
2461 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002462
Chris Lattner3dd716c2010-06-28 23:44:11 +00002463 // If the coerce-to type is a first class aggregate, we flatten it and
2464 // pass the elements. Either way is semantically identical, but fast-isel
2465 // and the optimizer generally likes scalar values better than FCAs.
Chris Lattner2192fe52011-07-18 04:24:23 +00002466 if (llvm::StructType *STy =
Chris Lattner15ec3612010-06-29 00:06:42 +00002467 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType())) {
Chandler Carrutha6399a52012-10-10 11:29:08 +00002468 llvm::Type *SrcTy =
2469 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
2470 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
2471 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
2472
2473 // If the source type is smaller than the destination type of the
2474 // coerce-to logic, copy the source value into a temp alloca the size
2475 // of the destination type to allow loading all of it. The bits past
2476 // the source value are left undef.
2477 if (SrcSize < DstSize) {
2478 llvm::AllocaInst *TempAlloca
2479 = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
2480 Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
2481 SrcPtr = TempAlloca;
2482 } else {
2483 SrcPtr = Builder.CreateBitCast(SrcPtr,
2484 llvm::PointerType::getUnqual(STy));
2485 }
2486
Chris Lattnerceddafb2010-07-05 20:41:41 +00002487 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2488 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerff941a62010-07-28 18:24:28 +00002489 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
2490 // We don't know what we're loading from.
2491 LI->setAlignment(1);
2492 Args.push_back(LI);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002493
2494 // Validate argument match.
2495 checkArgMatches(LI, IRArgNo, IRFuncTy);
Chris Lattner15ec3612010-06-29 00:06:42 +00002496 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00002497 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00002498 // In the simple case, just pass the coerced loaded value.
2499 Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(),
2500 *this));
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002501
2502 // Validate argument match.
2503 checkArgMatches(Args.back(), IRArgNo, IRFuncTy);
Chris Lattner3dd716c2010-06-28 23:44:11 +00002504 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002505
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002506 break;
2507 }
2508
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002509 case ABIArgInfo::Expand:
Chris Lattnerd59d8672011-07-12 06:29:11 +00002510 ExpandTypeToArgs(I->Ty, RV, Args, IRFuncTy);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002511 IRArgNo = Args.size();
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002512 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00002513 }
2514 }
Mike Stump11289f42009-09-09 15:08:12 +00002515
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002516 if (!CallArgs.getCleanupsToDeactivate().empty())
2517 deactivateArgCleanupsBeforeCall(*this, CallArgs);
2518
Chris Lattner4ca97c32009-06-13 00:26:38 +00002519 // If the callee is a bitcast of a function to a varargs pointer to function
2520 // type, check to see if we can remove the bitcast. This handles some cases
2521 // with unprototyped functions.
2522 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
2523 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002524 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
2525 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00002526 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00002527 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00002528
Chris Lattner4ca97c32009-06-13 00:26:38 +00002529 if (CE->getOpcode() == llvm::Instruction::BitCast &&
2530 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00002531 ActualFT->getNumParams() == CurFT->getNumParams() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00002532 ActualFT->getNumParams() == Args.size() &&
2533 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00002534 bool ArgsMatch = true;
2535 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
2536 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
2537 ArgsMatch = false;
2538 break;
2539 }
Mike Stump11289f42009-09-09 15:08:12 +00002540
Chris Lattner4ca97c32009-06-13 00:26:38 +00002541 // Strip the cast if we can get away with it. This is a nice cleanup,
2542 // but also allows us to inline the function at -O0 if it is marked
2543 // always_inline.
2544 if (ArgsMatch)
2545 Callee = CalleeF;
2546 }
2547 }
Mike Stump11289f42009-09-09 15:08:12 +00002548
Daniel Dunbar0ef34792009-09-12 00:59:20 +00002549 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00002550 CodeGen::AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00002551 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
2552 CallingConv, true);
Bill Wendling3087d022012-12-07 23:17:26 +00002553 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00002554 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00002555
John McCallbd309292010-07-06 01:34:17 +00002556 llvm::BasicBlock *InvokeDest = 0;
Bill Wendling5e85be42012-12-30 10:32:17 +00002557 if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
2558 llvm::Attribute::NoUnwind))
John McCallbd309292010-07-06 01:34:17 +00002559 InvokeDest = getInvokeDest();
2560
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002561 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00002562 if (!InvokeDest) {
Jay Foad5bd375a2011-07-15 08:37:34 +00002563 CS = Builder.CreateCall(Callee, Args);
Daniel Dunbar12347492009-02-23 17:26:39 +00002564 } else {
2565 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Jay Foad5bd375a2011-07-15 08:37:34 +00002566 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, Args);
Daniel Dunbar12347492009-02-23 17:26:39 +00002567 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00002568 }
Chris Lattnere70a0072010-06-29 16:40:28 +00002569 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00002570 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00002571
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002572 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00002573 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002574
Dan Gohman515a60d2012-02-16 00:57:37 +00002575 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2576 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002577 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00002578 AddObjCARCExceptionMetadata(CS.getInstruction());
2579
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002580 // If the call doesn't return, finish the basic block and clear the
2581 // insertion point; this allows the rest of IRgen to discard
2582 // unreachable code.
2583 if (CS.doesNotReturn()) {
2584 Builder.CreateUnreachable();
2585 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00002586
Mike Stump18bb9282009-05-16 07:57:57 +00002587 // FIXME: For now, emit a dummy basic block because expr emitters in
2588 // generally are not ready to handle emitting expressions at unreachable
2589 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002590 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00002591
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002592 // Return a reasonable RValue.
2593 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00002594 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002595
2596 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00002597 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00002598 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002599
John McCall31168b02011-06-15 23:02:42 +00002600 // Emit any writebacks immediately. Arguably this should happen
2601 // after any return-value munging.
2602 if (CallArgs.hasWritebacks())
2603 emitWritebacks(*this, CallArgs);
2604
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002605 switch (RetAI.getKind()) {
John McCall47fb9502013-03-07 21:37:08 +00002606 case ABIArgInfo::Indirect:
Nick Lewycky2d84e842013-10-02 02:29:49 +00002607 return convertTempToRValue(Args[0], RetTy, SourceLocation());
Daniel Dunbard3674e62008-09-11 01:48:57 +00002608
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002609 case ABIArgInfo::Ignore:
Daniel Dunbar01362822009-02-03 06:30:17 +00002610 // If we are ignoring an argument that had a result, make sure to
2611 // construct the appropriate return value for our caller.
Daniel Dunbarc79407f2009-02-05 07:09:07 +00002612 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002613
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002614 case ABIArgInfo::Extend:
2615 case ABIArgInfo::Direct: {
Chris Lattner3517f142011-07-13 03:59:32 +00002616 llvm::Type *RetIRTy = ConvertType(RetTy);
2617 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
John McCall47fb9502013-03-07 21:37:08 +00002618 switch (getEvaluationKind(RetTy)) {
2619 case TEK_Complex: {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002620 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
2621 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
2622 return RValue::getComplex(std::make_pair(Real, Imag));
2623 }
John McCall47fb9502013-03-07 21:37:08 +00002624 case TEK_Aggregate: {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002625 llvm::Value *DestPtr = ReturnValue.getValue();
2626 bool DestIsVolatile = ReturnValue.isVolatile();
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002627
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002628 if (!DestPtr) {
2629 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
2630 DestIsVolatile = false;
2631 }
Eli Friedmanaf9b3252011-05-17 21:08:01 +00002632 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002633 return RValue::getAggregate(DestPtr);
2634 }
John McCall47fb9502013-03-07 21:37:08 +00002635 case TEK_Scalar: {
2636 // If the argument doesn't match, perform a bitcast to coerce it. This
2637 // can happen due to trivial type mismatches.
2638 llvm::Value *V = CI;
2639 if (V->getType() != RetIRTy)
2640 V = Builder.CreateBitCast(V, RetIRTy);
2641 return RValue::get(V);
2642 }
2643 }
2644 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002645 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002646
Anders Carlsson17490832009-12-24 20:40:36 +00002647 llvm::Value *DestPtr = ReturnValue.getValue();
2648 bool DestIsVolatile = ReturnValue.isVolatile();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002649
Anders Carlsson17490832009-12-24 20:40:36 +00002650 if (!DestPtr) {
Daniel Dunbara7566f12010-02-09 02:48:28 +00002651 DestPtr = CreateMemTemp(RetTy, "coerce");
Anders Carlsson17490832009-12-24 20:40:36 +00002652 DestIsVolatile = false;
2653 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002654
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002655 // If the value is offset in memory, apply the offset now.
2656 llvm::Value *StorePtr = DestPtr;
2657 if (unsigned Offs = RetAI.getDirectOffset()) {
2658 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
2659 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002660 StorePtr = Builder.CreateBitCast(StorePtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002661 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
2662 }
2663 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002664
Nick Lewycky2d84e842013-10-02 02:29:49 +00002665 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Daniel Dunbar573884e2008-09-10 07:04:09 +00002666 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00002667
Daniel Dunbard3674e62008-09-11 01:48:57 +00002668 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002669 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar613855c2008-09-09 23:27:19 +00002670 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002671
David Blaikie83d382b2011-09-23 05:06:16 +00002672 llvm_unreachable("Unhandled ABIArgInfo::Kind");
Daniel Dunbar613855c2008-09-09 23:27:19 +00002673}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00002674
2675/* VarArg handling */
2676
2677llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
2678 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
2679}