blob: 971a2ade1262cd1091ea4b897a2c8d50e4531ea5 [file] [log] [blame]
Chris Lattnera5f58b02011-07-09 17:41:47 +00001//===--- CGCall.cpp - Encapsulate calling convention details ----*- C++ -*-===//
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"
Chandler Carruth85098242010-06-15 23:19:56 +000025#include "clang/Frontend/CodeGenOptions.h"
Bill Wendling706469b2013-02-28 22:49:57 +000026#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000027#include "llvm/IR/Attributes.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/InlineAsm.h"
Bill Wendling985d1c52013-02-15 21:30:01 +000030#include "llvm/MC/SubtargetFeature.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "llvm/Support/CallSite.h"
Eli Friedmanf7456192011-06-15 22:09:18 +000032#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000033using namespace clang;
34using namespace CodeGen;
35
36/***/
37
John McCallab26cfa2010-02-05 21:31:56 +000038static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) {
39 switch (CC) {
40 default: return llvm::CallingConv::C;
41 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
42 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
Douglas Gregora941dca2010-05-18 16:57:00 +000043 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Anton Korobeynikov231e8752011-04-14 20:06:49 +000044 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
45 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Guy Benyeif0a014b2012-12-25 08:53:55 +000046 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Dawn Perchik335e16b2010-09-03 01:29:35 +000047 // TODO: add support for CC_X86Pascal to llvm
John McCallab26cfa2010-02-05 21:31:56 +000048 }
49}
50
John McCall8ee376f2010-02-24 07:14:12 +000051/// Derives the 'this' type for codegen purposes, i.e. ignoring method
52/// qualification.
53/// FIXME: address space qualification?
John McCall2da83a32010-02-26 00:48:12 +000054static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
55 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
56 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000057}
58
John McCall8ee376f2010-02-24 07:14:12 +000059/// Returns the canonical formal type of the given C++ method.
John McCall2da83a32010-02-26 00:48:12 +000060static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
61 return MD->getType()->getCanonicalTypeUnqualified()
62 .getAs<FunctionProtoType>();
John McCall8ee376f2010-02-24 07:14:12 +000063}
64
65/// Returns the "extra-canonicalized" return type, which discards
66/// qualifiers on the return type. Codegen doesn't care about them,
67/// and it makes ABI code a little easier to be able to assume that
68/// all parameter and return types are top-level unqualified.
John McCall2da83a32010-02-26 00:48:12 +000069static CanQualType GetReturnType(QualType RetTy) {
70 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall8ee376f2010-02-24 07:14:12 +000071}
72
John McCall8dda7b22012-07-07 06:41:13 +000073/// Arrange the argument and result information for a value of the given
74/// unprototyped freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +000075const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +000076CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCalla729c622012-02-17 03:33:10 +000077 // When translating an unprototyped function type, always use a
78 // variadic type.
John McCall8dda7b22012-07-07 06:41:13 +000079 return arrangeLLVMFunctionInfo(FTNP->getResultType().getUnqualifiedType(),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000080 None, FTNP->getExtInfo(), RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +000081}
82
John McCall8dda7b22012-07-07 06:41:13 +000083/// Arrange the LLVM function layout for a value of the given function
84/// type, on top of any implicit parameters already stored. Use the
85/// given ExtInfo instead of the ExtInfo from the function type.
86static const CGFunctionInfo &arrangeLLVMFunctionInfo(CodeGenTypes &CGT,
87 SmallVectorImpl<CanQualType> &prefix,
88 CanQual<FunctionProtoType> FTP,
89 FunctionType::ExtInfo extInfo) {
90 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +000091 // FIXME: Kill copy.
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000092 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
John McCall8dda7b22012-07-07 06:41:13 +000093 prefix.push_back(FTP->getArgType(i));
John McCalla729c622012-02-17 03:33:10 +000094 CanQualType resultType = FTP->getResultType().getUnqualifiedType();
John McCall8dda7b22012-07-07 06:41:13 +000095 return CGT.arrangeLLVMFunctionInfo(resultType, prefix, extInfo, required);
96}
97
98/// Arrange the argument and result information for a free function (i.e.
99/// not a C++ or ObjC instance method) of the given type.
100static const CGFunctionInfo &arrangeFreeFunctionType(CodeGenTypes &CGT,
101 SmallVectorImpl<CanQualType> &prefix,
102 CanQual<FunctionProtoType> FTP) {
103 return arrangeLLVMFunctionInfo(CGT, prefix, FTP, FTP->getExtInfo());
104}
105
106/// Given the formal ext-info of a C++ instance method, adjust it
107/// according to the C++ ABI in effect.
108static void adjustCXXMethodInfo(CodeGenTypes &CGT,
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +0000109 FunctionType::ExtInfo &extInfo,
110 bool isVariadic) {
111 if (extInfo.getCC() == CC_Default) {
112 CallingConv CC = CGT.getContext().getDefaultCXXMethodCallConv(isVariadic);
113 extInfo = extInfo.withCallingConv(CC);
114 }
John McCall8dda7b22012-07-07 06:41:13 +0000115}
116
117/// Arrange the argument and result information for a free function (i.e.
118/// not a C++ or ObjC instance method) of the given type.
119static const CGFunctionInfo &arrangeCXXMethodType(CodeGenTypes &CGT,
120 SmallVectorImpl<CanQualType> &prefix,
121 CanQual<FunctionProtoType> FTP) {
122 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +0000123 adjustCXXMethodInfo(CGT, extInfo, FTP->isVariadic());
John McCall8dda7b22012-07-07 06:41:13 +0000124 return arrangeLLVMFunctionInfo(CGT, prefix, FTP, extInfo);
John McCall8ee376f2010-02-24 07:14:12 +0000125}
126
John McCalla729c622012-02-17 03:33:10 +0000127/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000128/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000129const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000130CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
John McCalla729c622012-02-17 03:33:10 +0000131 SmallVector<CanQualType, 16> argTypes;
John McCall8dda7b22012-07-07 06:41:13 +0000132 return ::arrangeFreeFunctionType(*this, argTypes, FTP);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000133}
134
John McCallab26cfa2010-02-05 21:31:56 +0000135static CallingConv getCallingConventionForDecl(const Decl *D) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000136 // Set the appropriate calling convention for the Function.
137 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000138 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000139
140 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000141 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000142
Douglas Gregora941dca2010-05-18 16:57:00 +0000143 if (D->hasAttr<ThisCallAttr>())
144 return CC_X86ThisCall;
145
Dawn Perchik335e16b2010-09-03 01:29:35 +0000146 if (D->hasAttr<PascalAttr>())
147 return CC_X86Pascal;
148
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000149 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
150 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
151
Derek Schuffa2020962012-10-16 22:30:41 +0000152 if (D->hasAttr<PnaclCallAttr>())
153 return CC_PnaclCall;
154
Guy Benyeif0a014b2012-12-25 08:53:55 +0000155 if (D->hasAttr<IntelOclBiccAttr>())
156 return CC_IntelOclBicc;
157
John McCallab26cfa2010-02-05 21:31:56 +0000158 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000159}
160
John McCalla729c622012-02-17 03:33:10 +0000161/// Arrange the argument and result information for a call to an
162/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000163/// (Zero value of RD means we don't have any meaningful "this" argument type,
164/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000165/// The member function must be an ordinary function, i.e. not a
166/// constructor or destructor.
167const CGFunctionInfo &
168CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
169 const FunctionProtoType *FTP) {
170 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000171
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000172 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000173 if (RD)
174 argTypes.push_back(GetThisType(Context, RD));
175 else
176 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000177
John McCall8dda7b22012-07-07 06:41:13 +0000178 return ::arrangeCXXMethodType(*this, argTypes,
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000179 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000180}
181
John McCalla729c622012-02-17 03:33:10 +0000182/// Arrange the argument and result information for a declaration or
183/// definition of the given C++ non-static member function. The
184/// member function must be an ordinary function, i.e. not a
185/// constructor or destructor.
186const CGFunctionInfo &
187CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
John McCall0d635f52010-09-03 01:26:39 +0000188 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for contructors!");
189 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
190
John McCalla729c622012-02-17 03:33:10 +0000191 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000192
John McCalla729c622012-02-17 03:33:10 +0000193 if (MD->isInstance()) {
194 // The abstract case is perfectly fine.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000195 const CXXRecordDecl *ThisType =
196 CGM.getCXXABI().getThisArgumentTypeForMethod(MD);
197 return arrangeCXXMethodType(ThisType, prototype.getTypePtr());
John McCalla729c622012-02-17 03:33:10 +0000198 }
199
John McCall8dda7b22012-07-07 06:41:13 +0000200 return arrangeFreeFunctionType(prototype);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000201}
202
John McCalla729c622012-02-17 03:33:10 +0000203/// Arrange the argument and result information for a declaration
204/// or definition to the given constructor variant.
205const CGFunctionInfo &
206CodeGenTypes::arrangeCXXConstructorDeclaration(const CXXConstructorDecl *D,
207 CXXCtorType ctorKind) {
208 SmallVector<CanQualType, 16> argTypes;
209 argTypes.push_back(GetThisType(Context, D->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000210
211 GlobalDecl GD(D, ctorKind);
212 CanQualType resultType =
213 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000214
John McCalla729c622012-02-17 03:33:10 +0000215 TheCXXABI.BuildConstructorSignature(D, ctorKind, resultType, argTypes);
John McCall8ee376f2010-02-24 07:14:12 +0000216
John McCall5d865c322010-08-31 07:33:07 +0000217 CanQual<FunctionProtoType> FTP = GetFormalType(D);
218
John McCalla729c622012-02-17 03:33:10 +0000219 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, argTypes.size());
220
John McCall5d865c322010-08-31 07:33:07 +0000221 // Add the formal parameters.
222 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
John McCalla729c622012-02-17 03:33:10 +0000223 argTypes.push_back(FTP->getArgType(i));
John McCall5d865c322010-08-31 07:33:07 +0000224
John McCall8dda7b22012-07-07 06:41:13 +0000225 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +0000226 adjustCXXMethodInfo(*this, extInfo, FTP->isVariadic());
John McCall8dda7b22012-07-07 06:41:13 +0000227 return arrangeLLVMFunctionInfo(resultType, argTypes, extInfo, required);
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000228}
229
John McCalla729c622012-02-17 03:33:10 +0000230/// Arrange the argument and result information for a declaration,
231/// definition, or call to the given destructor variant. It so
232/// happens that all three cases produce the same information.
233const CGFunctionInfo &
234CodeGenTypes::arrangeCXXDestructor(const CXXDestructorDecl *D,
235 CXXDtorType dtorKind) {
236 SmallVector<CanQualType, 2> argTypes;
237 argTypes.push_back(GetThisType(Context, D->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000238
239 GlobalDecl GD(D, dtorKind);
240 CanQualType resultType =
241 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
John McCall8ee376f2010-02-24 07:14:12 +0000242
John McCalla729c622012-02-17 03:33:10 +0000243 TheCXXABI.BuildDestructorSignature(D, dtorKind, resultType, argTypes);
John McCall5d865c322010-08-31 07:33:07 +0000244
245 CanQual<FunctionProtoType> FTP = GetFormalType(D);
246 assert(FTP->getNumArgs() == 0 && "dtor with formal parameters");
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +0000247 assert(FTP->isVariadic() == 0 && "dtor with formal parameters");
John McCall5d865c322010-08-31 07:33:07 +0000248
John McCall8dda7b22012-07-07 06:41:13 +0000249 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +0000250 adjustCXXMethodInfo(*this, extInfo, false);
John McCall8dda7b22012-07-07 06:41:13 +0000251 return arrangeLLVMFunctionInfo(resultType, argTypes, extInfo,
252 RequiredArgs::All);
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000253}
254
John McCalla729c622012-02-17 03:33:10 +0000255/// Arrange the argument and result information for the declaration or
256/// definition of the given function.
257const CGFunctionInfo &
258CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000259 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000260 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000261 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000262
John McCall2da83a32010-02-26 00:48:12 +0000263 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000264
John McCall2da83a32010-02-26 00:48:12 +0000265 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000266
267 // When declaring a function without a prototype, always use a
268 // non-variadic type.
269 if (isa<FunctionNoProtoType>(FTy)) {
270 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000271 return arrangeLLVMFunctionInfo(noProto->getResultType(), None,
272 noProto->getExtInfo(), RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000273 }
274
John McCall2da83a32010-02-26 00:48:12 +0000275 assert(isa<FunctionProtoType>(FTy));
John McCall8dda7b22012-07-07 06:41:13 +0000276 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>());
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000277}
278
John McCalla729c622012-02-17 03:33:10 +0000279/// Arrange the argument and result information for the declaration or
280/// definition of an Objective-C method.
281const CGFunctionInfo &
282CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
283 // It happens that this is the same as a call with no optional
284 // arguments, except also using the formal 'self' type.
285 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
286}
287
288/// Arrange the argument and result information for the function type
289/// through which to perform a send to the given Objective-C method,
290/// using the given receiver type. The receiver type is not always
291/// the 'self' type of the method or even an Objective-C pointer type.
292/// This is *not* the right method for actually performing such a
293/// message send, due to the possibility of optional arguments.
294const CGFunctionInfo &
295CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
296 QualType receiverType) {
297 SmallVector<CanQualType, 16> argTys;
298 argTys.push_back(Context.getCanonicalParamType(receiverType));
299 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000300 // FIXME: Kill copy?
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +0000301 for (ObjCMethodDecl::param_const_iterator i = MD->param_begin(),
John McCall8ee376f2010-02-24 07:14:12 +0000302 e = MD->param_end(); i != e; ++i) {
John McCalla729c622012-02-17 03:33:10 +0000303 argTys.push_back(Context.getCanonicalParamType((*i)->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000304 }
John McCall31168b02011-06-15 23:02:42 +0000305
306 FunctionType::ExtInfo einfo;
307 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD));
308
David Blaikiebbafb8a2012-03-11 07:00:24 +0000309 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000310 MD->hasAttr<NSReturnsRetainedAttr>())
311 einfo = einfo.withProducesResult(true);
312
John McCalla729c622012-02-17 03:33:10 +0000313 RequiredArgs required =
314 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
315
John McCall8dda7b22012-07-07 06:41:13 +0000316 return arrangeLLVMFunctionInfo(GetReturnType(MD->getResultType()), argTys,
317 einfo, required);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000318}
319
John McCalla729c622012-02-17 03:33:10 +0000320const CGFunctionInfo &
321CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000322 // FIXME: Do we need to handle ObjCMethodDecl?
323 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000324
Anders Carlsson6710c532010-02-06 02:44:09 +0000325 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
John McCalla729c622012-02-17 03:33:10 +0000326 return arrangeCXXConstructorDeclaration(CD, GD.getCtorType());
Anders Carlsson6710c532010-02-06 02:44:09 +0000327
328 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
John McCalla729c622012-02-17 03:33:10 +0000329 return arrangeCXXDestructor(DD, GD.getDtorType());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000330
John McCalla729c622012-02-17 03:33:10 +0000331 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000332}
333
John McCallc818bbb2012-12-07 07:03:17 +0000334/// Arrange a call as unto a free function, except possibly with an
335/// additional number of formal parameters considered required.
336static const CGFunctionInfo &
337arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
338 const CallArgList &args,
339 const FunctionType *fnType,
340 unsigned numExtraRequiredArgs) {
341 assert(args.size() >= numExtraRequiredArgs);
342
343 // In most cases, there are no optional arguments.
344 RequiredArgs required = RequiredArgs::All;
345
346 // If we have a variadic prototype, the required arguments are the
347 // extra prefix plus the arguments in the prototype.
348 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
349 if (proto->isVariadic())
350 required = RequiredArgs(proto->getNumArgs() + numExtraRequiredArgs);
351
352 // If we don't have a prototype at all, but we're supposed to
353 // explicitly use the variadic convention for unprototyped calls,
354 // treat all of the arguments as required but preserve the nominal
355 // possibility of variadics.
356 } else if (CGT.CGM.getTargetCodeGenInfo()
357 .isNoProtoCallVariadic(args, cast<FunctionNoProtoType>(fnType))) {
358 required = RequiredArgs(args.size());
359 }
360
361 return CGT.arrangeFreeFunctionCall(fnType->getResultType(), args,
362 fnType->getExtInfo(), required);
363}
364
John McCalla729c622012-02-17 03:33:10 +0000365/// Figure out the rules for calling a function with the given formal
366/// type using the given arguments. The arguments are necessary
367/// because the function might be unprototyped, in which case it's
368/// target-dependent in crazy ways.
369const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000370CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
371 const FunctionType *fnType) {
John McCallc818bbb2012-12-07 07:03:17 +0000372 return arrangeFreeFunctionLikeCall(*this, args, fnType, 0);
373}
John McCalla729c622012-02-17 03:33:10 +0000374
John McCallc818bbb2012-12-07 07:03:17 +0000375/// A block function call is essentially a free-function call with an
376/// extra implicit argument.
377const CGFunctionInfo &
378CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
379 const FunctionType *fnType) {
380 return arrangeFreeFunctionLikeCall(*this, args, fnType, 1);
John McCalla729c622012-02-17 03:33:10 +0000381}
382
383const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000384CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
385 const CallArgList &args,
386 FunctionType::ExtInfo info,
387 RequiredArgs required) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000388 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000389 SmallVector<CanQualType, 16> argTypes;
390 for (CallArgList::const_iterator i = args.begin(), e = args.end();
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000391 i != e; ++i)
John McCalla729c622012-02-17 03:33:10 +0000392 argTypes.push_back(Context.getCanonicalParamType(i->Ty));
John McCall8dda7b22012-07-07 06:41:13 +0000393 return arrangeLLVMFunctionInfo(GetReturnType(resultType), argTypes, info,
394 required);
395}
396
397/// Arrange a call to a C++ method, passing the given arguments.
398const CGFunctionInfo &
399CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
400 const FunctionProtoType *FPT,
401 RequiredArgs required) {
402 // FIXME: Kill copy.
403 SmallVector<CanQualType, 16> argTypes;
404 for (CallArgList::const_iterator i = args.begin(), e = args.end();
405 i != e; ++i)
406 argTypes.push_back(Context.getCanonicalParamType(i->Ty));
407
408 FunctionType::ExtInfo info = FPT->getExtInfo();
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +0000409 adjustCXXMethodInfo(*this, info, FPT->isVariadic());
John McCall8dda7b22012-07-07 06:41:13 +0000410 return arrangeLLVMFunctionInfo(GetReturnType(FPT->getResultType()),
411 argTypes, info, required);
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000412}
413
John McCalla729c622012-02-17 03:33:10 +0000414const CGFunctionInfo &
415CodeGenTypes::arrangeFunctionDeclaration(QualType resultType,
416 const FunctionArgList &args,
417 const FunctionType::ExtInfo &info,
418 bool isVariadic) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000419 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000420 SmallVector<CanQualType, 16> argTypes;
421 for (FunctionArgList::const_iterator i = args.begin(), e = args.end();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +0000422 i != e; ++i)
John McCalla729c622012-02-17 03:33:10 +0000423 argTypes.push_back(Context.getCanonicalParamType((*i)->getType()));
424
425 RequiredArgs required =
426 (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
John McCall8dda7b22012-07-07 06:41:13 +0000427 return arrangeLLVMFunctionInfo(GetReturnType(resultType), argTypes, info,
428 required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000429}
430
John McCalla729c622012-02-17 03:33:10 +0000431const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000432 return arrangeLLVMFunctionInfo(getContext().VoidTy, None,
John McCall8dda7b22012-07-07 06:41:13 +0000433 FunctionType::ExtInfo(), RequiredArgs::All);
John McCalla738c252011-03-09 04:27:21 +0000434}
435
John McCalla729c622012-02-17 03:33:10 +0000436/// Arrange the argument and result information for an abstract value
437/// of a given function type. This is the method which all of the
438/// above functions ultimately defer to.
439const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000440CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
441 ArrayRef<CanQualType> argTypes,
442 FunctionType::ExtInfo info,
443 RequiredArgs required) {
John McCall2da83a32010-02-26 00:48:12 +0000444#ifndef NDEBUG
John McCalla729c622012-02-17 03:33:10 +0000445 for (ArrayRef<CanQualType>::const_iterator
446 I = argTypes.begin(), E = argTypes.end(); I != E; ++I)
John McCall2da83a32010-02-26 00:48:12 +0000447 assert(I->isCanonicalAsParam());
448#endif
449
John McCalla729c622012-02-17 03:33:10 +0000450 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
John McCallab26cfa2010-02-05 21:31:56 +0000451
Daniel Dunbare0be8292009-02-03 00:07:12 +0000452 // Lookup or create unique function info.
453 llvm::FoldingSetNodeID ID;
John McCalla729c622012-02-17 03:33:10 +0000454 CGFunctionInfo::Profile(ID, info, required, resultType, argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000455
John McCalla729c622012-02-17 03:33:10 +0000456 void *insertPos = 0;
457 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000458 if (FI)
459 return *FI;
460
John McCalla729c622012-02-17 03:33:10 +0000461 // Construct the function info. We co-allocate the ArgInfos.
462 FI = CGFunctionInfo::create(CC, info, resultType, argTypes, required);
463 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000464
John McCalla729c622012-02-17 03:33:10 +0000465 bool inserted = FunctionsBeingProcessed.insert(FI); (void)inserted;
466 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000467
Daniel Dunbar313321e2009-02-03 05:31:23 +0000468 // Compute ABI information.
Chris Lattner22326a12010-07-29 02:31:05 +0000469 getABIInfo().computeInfo(*FI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000470
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000471 // Loop over all of the computed argument and return value info. If any of
472 // them are direct or extend without a specified coerce type, specify the
473 // default now.
John McCalla729c622012-02-17 03:33:10 +0000474 ABIArgInfo &retInfo = FI->getReturnInfo();
475 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == 0)
476 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000477
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000478 for (CGFunctionInfo::arg_iterator I = FI->arg_begin(), E = FI->arg_end();
479 I != E; ++I)
480 if (I->info.canHaveCoerceToType() && I->info.getCoerceToType() == 0)
Chris Lattnera5f58b02011-07-09 17:41:47 +0000481 I->info.setCoerceToType(ConvertType(I->type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000482
John McCalla729c622012-02-17 03:33:10 +0000483 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
484 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000485
Daniel Dunbare0be8292009-02-03 00:07:12 +0000486 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000487}
488
John McCalla729c622012-02-17 03:33:10 +0000489CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
490 const FunctionType::ExtInfo &info,
491 CanQualType resultType,
492 ArrayRef<CanQualType> argTypes,
493 RequiredArgs required) {
494 void *buffer = operator new(sizeof(CGFunctionInfo) +
495 sizeof(ArgInfo) * (argTypes.size() + 1));
496 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
497 FI->CallingConvention = llvmCC;
498 FI->EffectiveCallingConvention = llvmCC;
499 FI->ASTCallingConvention = info.getCC();
500 FI->NoReturn = info.getNoReturn();
501 FI->ReturnsRetained = info.getProducesResult();
502 FI->Required = required;
503 FI->HasRegParm = info.getHasRegParm();
504 FI->RegParm = info.getRegParm();
505 FI->NumArgs = argTypes.size();
506 FI->getArgsBuffer()[0].type = resultType;
507 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
508 FI->getArgsBuffer()[i + 1].type = argTypes[i];
509 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000510}
511
512/***/
513
John McCall85dd2c52011-05-15 02:19:42 +0000514void CodeGenTypes::GetExpandedTypes(QualType type,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000515 SmallVectorImpl<llvm::Type*> &expandedTypes) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000516 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(type)) {
517 uint64_t NumElts = AT->getSize().getZExtValue();
518 for (uint64_t Elt = 0; Elt < NumElts; ++Elt)
519 GetExpandedTypes(AT->getElementType(), expandedTypes);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000520 } else if (const RecordType *RT = type->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000521 const RecordDecl *RD = RT->getDecl();
522 assert(!RD->hasFlexibleArrayMember() &&
523 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000524 if (RD->isUnion()) {
525 // Unions can be here only in degenerative cases - all the fields are same
526 // after flattening. Thus we have to use the "largest" field.
527 const FieldDecl *LargestFD = 0;
528 CharUnits UnionSize = CharUnits::Zero();
529
530 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
531 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +0000532 const FieldDecl *FD = *i;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000533 assert(!FD->isBitField() &&
534 "Cannot expand structure with bit-field members.");
535 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
536 if (UnionSize < FieldSize) {
537 UnionSize = FieldSize;
538 LargestFD = FD;
539 }
540 }
541 if (LargestFD)
542 GetExpandedTypes(LargestFD->getType(), expandedTypes);
543 } else {
544 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
545 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +0000546 assert(!i->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000547 "Cannot expand structure with bit-field members.");
David Blaikie40ed2972012-06-06 20:45:41 +0000548 GetExpandedTypes(i->getType(), expandedTypes);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000549 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000550 }
551 } else if (const ComplexType *CT = type->getAs<ComplexType>()) {
552 llvm::Type *EltTy = ConvertType(CT->getElementType());
553 expandedTypes.push_back(EltTy);
554 expandedTypes.push_back(EltTy);
555 } else
556 expandedTypes.push_back(ConvertType(type));
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000557}
558
Mike Stump11289f42009-09-09 15:08:12 +0000559llvm::Function::arg_iterator
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000560CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
561 llvm::Function::arg_iterator AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000562 assert(LV.isSimple() &&
563 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000564
Bob Wilsone826a2a2011-08-03 05:58:22 +0000565 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
566 unsigned NumElts = AT->getSize().getZExtValue();
567 QualType EltTy = AT->getElementType();
568 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
Eli Friedman7f1ff602012-04-16 03:54:45 +0000569 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, Elt);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000570 LValue LV = MakeAddrLValue(EltAddr, EltTy);
571 AI = ExpandTypeFromArgs(EltTy, LV, AI);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000572 }
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000573 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000574 RecordDecl *RD = RT->getDecl();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000575 if (RD->isUnion()) {
576 // Unions can be here only in degenerative cases - all the fields are same
577 // after flattening. Thus we have to use the "largest" field.
578 const FieldDecl *LargestFD = 0;
579 CharUnits UnionSize = CharUnits::Zero();
Bob Wilsone826a2a2011-08-03 05:58:22 +0000580
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000581 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
582 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +0000583 const FieldDecl *FD = *i;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000584 assert(!FD->isBitField() &&
585 "Cannot expand structure with bit-field members.");
586 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
587 if (UnionSize < FieldSize) {
588 UnionSize = FieldSize;
589 LargestFD = FD;
590 }
591 }
592 if (LargestFD) {
593 // FIXME: What are the right qualifiers here?
Eli Friedman7f1ff602012-04-16 03:54:45 +0000594 LValue SubLV = EmitLValueForField(LV, LargestFD);
595 AI = ExpandTypeFromArgs(LargestFD->getType(), SubLV, AI);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000596 }
597 } else {
598 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
599 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +0000600 FieldDecl *FD = *i;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000601 QualType FT = FD->getType();
602
603 // FIXME: What are the right qualifiers here?
Eli Friedman7f1ff602012-04-16 03:54:45 +0000604 LValue SubLV = EmitLValueForField(LV, FD);
605 AI = ExpandTypeFromArgs(FT, SubLV, AI);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000606 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000607 }
608 } else if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
609 QualType EltTy = CT->getElementType();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000610 llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real");
Bob Wilsone826a2a2011-08-03 05:58:22 +0000611 EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(RealAddr, EltTy));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000612 llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag");
Bob Wilsone826a2a2011-08-03 05:58:22 +0000613 EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(ImagAddr, EltTy));
614 } else {
615 EmitStoreThroughLValue(RValue::get(AI), LV);
616 ++AI;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000617 }
618
619 return AI;
620}
621
Chris Lattner895c52b2010-06-27 06:04:18 +0000622/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +0000623/// accessing some number of bytes out of it, try to gep into the struct to get
624/// at its inner goodness. Dive as deep as possible without entering an element
625/// with an in-memory size smaller than DstSize.
626static llvm::Value *
Chris Lattner895c52b2010-06-27 06:04:18 +0000627EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000628 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +0000629 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +0000630 // We can't dive into a zero-element struct.
631 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000632
Chris Lattner2192fe52011-07-18 04:24:23 +0000633 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000634
Chris Lattner1cd66982010-06-27 05:56:15 +0000635 // If the first elt is at least as large as what we're looking for, or if the
636 // first element is the same size as the whole struct, we can enter it.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000637 uint64_t FirstEltSize =
Micah Villmowdd31ca12012-10-08 16:25:52 +0000638 CGF.CGM.getDataLayout().getTypeAllocSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000639 if (FirstEltSize < DstSize &&
Micah Villmowdd31ca12012-10-08 16:25:52 +0000640 FirstEltSize < CGF.CGM.getDataLayout().getTypeAllocSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +0000641 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000642
Chris Lattner1cd66982010-06-27 05:56:15 +0000643 // GEP into the first element.
644 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000645
Chris Lattner1cd66982010-06-27 05:56:15 +0000646 // If the first element is a struct, recurse.
Chris Lattner2192fe52011-07-18 04:24:23 +0000647 llvm::Type *SrcTy =
Chris Lattner1cd66982010-06-27 05:56:15 +0000648 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000649 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +0000650 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000651
652 return SrcPtr;
653}
654
Chris Lattner055097f2010-06-27 06:26:04 +0000655/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
656/// are either integers or pointers. This does a truncation of the value if it
657/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000658///
659/// This behaves as if the value were coerced through memory, so on big-endian
660/// targets the high bits are preserved in a truncation, while little-endian
661/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +0000662static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +0000663 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +0000664 CodeGenFunction &CGF) {
665 if (Val->getType() == Ty)
666 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000667
Chris Lattner055097f2010-06-27 06:26:04 +0000668 if (isa<llvm::PointerType>(Val->getType())) {
669 // If this is Pointer->Pointer avoid conversion to and from int.
670 if (isa<llvm::PointerType>(Ty))
671 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000672
Chris Lattner055097f2010-06-27 06:26:04 +0000673 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +0000674 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +0000675 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000676
Chris Lattner2192fe52011-07-18 04:24:23 +0000677 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +0000678 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +0000679 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000680
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000681 if (Val->getType() != DestIntTy) {
682 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
683 if (DL.isBigEndian()) {
684 // Preserve the high bits on big-endian targets.
685 // That is what memory coercion does.
686 uint64_t SrcSize = DL.getTypeAllocSizeInBits(Val->getType());
687 uint64_t DstSize = DL.getTypeAllocSizeInBits(DestIntTy);
688 if (SrcSize > DstSize) {
689 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
690 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
691 } else {
692 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
693 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
694 }
695 } else {
696 // Little-endian targets preserve the low bits. No shifts required.
697 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
698 }
699 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000700
Chris Lattner055097f2010-06-27 06:26:04 +0000701 if (isa<llvm::PointerType>(Ty))
702 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
703 return Val;
704}
705
Chris Lattner1cd66982010-06-27 05:56:15 +0000706
707
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000708/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
709/// a pointer to an object of type \arg Ty.
710///
711/// This safely handles the case when the src type is smaller than the
712/// destination type; in this situation the values of bits which not
713/// present in the src are undefined.
714static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000715 llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000716 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000717 llvm::Type *SrcTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000718 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000719
Chris Lattnerd200eda2010-06-28 22:51:39 +0000720 // If SrcTy and Ty are the same, just do a load.
721 if (SrcTy == Ty)
722 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000723
Micah Villmowdd31ca12012-10-08 16:25:52 +0000724 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000725
Chris Lattner2192fe52011-07-18 04:24:23 +0000726 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000727 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000728 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
729 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000730
Micah Villmowdd31ca12012-10-08 16:25:52 +0000731 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000732
Chris Lattner055097f2010-06-27 06:26:04 +0000733 // If the source and destination are integer or pointer types, just do an
734 // extension or truncation to the desired type.
735 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
736 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
737 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
738 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
739 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000740
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000741 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000742 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +0000743 // Generally SrcSize is never greater than DstSize, since this means we are
744 // losing bits. However, this can happen in cases where the structure has
745 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000746 //
Mike Stump18bb9282009-05-16 07:57:57 +0000747 // FIXME: Assert that we aren't truncating non-padding bits when have access
748 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000749 llvm::Value *Casted =
750 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000751 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
752 // FIXME: Use better alignment / avoid requiring aligned load.
753 Load->setAlignment(1);
754 return Load;
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000755 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000756
Chris Lattner3fcc7902010-06-27 01:06:27 +0000757 // Otherwise do coercion through memory. This is stupid, but
758 // simple.
759 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
Manman Ren84b921f2012-11-28 22:08:52 +0000760 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
761 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
762 llvm::Value *SrcCasted = CGF.Builder.CreateBitCast(SrcPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000763 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000764 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
765 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
766 1, false);
Chris Lattner3fcc7902010-06-27 01:06:27 +0000767 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000768}
769
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000770// Function to store a first-class aggregate into memory. We prefer to
771// store the elements rather than the aggregate to be more friendly to
772// fast-isel.
773// FIXME: Do we need to recurse here?
774static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
775 llvm::Value *DestPtr, bool DestIsVolatile,
776 bool LowAlignment) {
777 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +0000778 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000779 dyn_cast<llvm::StructType>(Val->getType())) {
780 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
781 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
782 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
783 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
784 DestIsVolatile);
785 if (LowAlignment)
786 SI->setAlignment(1);
787 }
788 } else {
Bill Wendlingf6af30f2012-03-16 21:45:12 +0000789 llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
790 if (LowAlignment)
791 SI->setAlignment(1);
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000792 }
793}
794
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000795/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
796/// where the source and destination may have different types.
797///
798/// This safely handles the case when the src type is larger than the
799/// destination type; the upper bits of the src will be lost.
800static void CreateCoercedStore(llvm::Value *Src,
801 llvm::Value *DstPtr,
Anders Carlsson17490832009-12-24 20:40:36 +0000802 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000803 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000804 llvm::Type *SrcTy = Src->getType();
805 llvm::Type *DstTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000806 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +0000807 if (SrcTy == DstTy) {
808 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
809 return;
810 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000811
Micah Villmowdd31ca12012-10-08 16:25:52 +0000812 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000813
Chris Lattner2192fe52011-07-18 04:24:23 +0000814 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000815 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
816 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
817 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000818
Chris Lattner055097f2010-06-27 06:26:04 +0000819 // If the source and destination are integer or pointer types, just do an
820 // extension or truncation to the desired type.
821 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
822 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
823 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
824 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
825 return;
826 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000827
Micah Villmowdd31ca12012-10-08 16:25:52 +0000828 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000829
Daniel Dunbar313321e2009-02-03 05:31:23 +0000830 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000831 if (SrcSize <= DstSize) {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000832 llvm::Value *Casted =
833 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000834 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000835 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000836 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000837 // Otherwise do coercion through memory. This is stupid, but
838 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000839
840 // Generally SrcSize is never greater than DstSize, since this means we are
841 // losing bits. However, this can happen in cases where the structure has
842 // additional padding, for example due to a user specified alignment.
843 //
844 // FIXME: Assert that we aren't truncating non-padding bits when have access
845 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000846 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
847 CGF.Builder.CreateStore(Src, Tmp);
Manman Ren84b921f2012-11-28 22:08:52 +0000848 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
849 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
850 llvm::Value *DstCasted = CGF.Builder.CreateBitCast(DstPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000851 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000852 CGF.Builder.CreateMemCpy(DstCasted, Casted,
853 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
854 1, false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000855 }
856}
857
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000858/***/
859
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000860bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000861 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +0000862}
863
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000864bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
865 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
866 switch (BT->getKind()) {
867 default:
868 return false;
869 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +0000870 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000871 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +0000872 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000873 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +0000874 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000875 }
876 }
877
878 return false;
879}
880
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000881bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
882 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
883 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
884 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +0000885 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000886 }
887 }
888
889 return false;
890}
891
Chris Lattnera5f58b02011-07-09 17:41:47 +0000892llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +0000893 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
894 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +0000895}
896
Chris Lattnera5f58b02011-07-09 17:41:47 +0000897llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +0000898CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000899
900 bool Inserted = FunctionsBeingProcessed.insert(&FI); (void)Inserted;
901 assert(Inserted && "Recursively being processed?");
902
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000903 SmallVector<llvm::Type*, 8> argTypes;
Chris Lattner2192fe52011-07-18 04:24:23 +0000904 llvm::Type *resultType = 0;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000905
John McCall85dd2c52011-05-15 02:19:42 +0000906 const ABIArgInfo &retAI = FI.getReturnInfo();
907 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +0000908 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +0000909 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +0000910
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000911 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +0000912 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +0000913 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +0000914 break;
915
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000916 case ABIArgInfo::Indirect: {
John McCall85dd2c52011-05-15 02:19:42 +0000917 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
918 resultType = llvm::Type::getVoidTy(getLLVMContext());
919
920 QualType ret = FI.getReturnType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000921 llvm::Type *ty = ConvertType(ret);
John McCall85dd2c52011-05-15 02:19:42 +0000922 unsigned addressSpace = Context.getTargetAddressSpace(ret);
923 argTypes.push_back(llvm::PointerType::get(ty, addressSpace));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000924 break;
925 }
926
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000927 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +0000928 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000929 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000930 }
Mike Stump11289f42009-09-09 15:08:12 +0000931
John McCallc818bbb2012-12-07 07:03:17 +0000932 // Add in all of the required arguments.
933 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), ie;
934 if (FI.isVariadic()) {
935 ie = it + FI.getRequiredArgs().getNumRequiredArgs();
936 } else {
937 ie = FI.arg_end();
938 }
939 for (; it != ie; ++it) {
John McCall85dd2c52011-05-15 02:19:42 +0000940 const ABIArgInfo &argAI = it->info;
Mike Stump11289f42009-09-09 15:08:12 +0000941
Rafael Espindolafad28de2012-10-24 01:59:00 +0000942 // Insert a padding type to ensure proper alignment.
943 if (llvm::Type *PaddingType = argAI.getPaddingType())
944 argTypes.push_back(PaddingType);
945
John McCall85dd2c52011-05-15 02:19:42 +0000946 switch (argAI.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000947 case ABIArgInfo::Ignore:
948 break;
949
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000950 case ABIArgInfo::Indirect: {
951 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +0000952 llvm::Type *LTy = ConvertTypeForMem(it->type);
John McCall85dd2c52011-05-15 02:19:42 +0000953 argTypes.push_back(LTy->getPointerTo());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000954 break;
955 }
956
957 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +0000958 case ABIArgInfo::Direct: {
Chris Lattner3dd716c2010-06-28 23:44:11 +0000959 // If the coerce-to type is a first class aggregate, flatten it. Either
960 // way is semantically identical, but fast-isel and the optimizer
961 // generally likes scalar values better than FCAs.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000962 llvm::Type *argType = argAI.getCoerceToType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000963 if (llvm::StructType *st = dyn_cast<llvm::StructType>(argType)) {
John McCall85dd2c52011-05-15 02:19:42 +0000964 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
965 argTypes.push_back(st->getElementType(i));
Chris Lattner3dd716c2010-06-28 23:44:11 +0000966 } else {
John McCall85dd2c52011-05-15 02:19:42 +0000967 argTypes.push_back(argType);
Chris Lattner3dd716c2010-06-28 23:44:11 +0000968 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +0000969 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +0000970 }
Mike Stump11289f42009-09-09 15:08:12 +0000971
Daniel Dunbard3674e62008-09-11 01:48:57 +0000972 case ABIArgInfo::Expand:
Chris Lattnera5f58b02011-07-09 17:41:47 +0000973 GetExpandedTypes(it->type, argTypes);
Daniel Dunbard3674e62008-09-11 01:48:57 +0000974 break;
975 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000976 }
977
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000978 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
979 assert(Erased && "Not in set?");
980
John McCalla729c622012-02-17 03:33:10 +0000981 return llvm::FunctionType::get(resultType, argTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +0000982}
983
Chris Lattner2192fe52011-07-18 04:24:23 +0000984llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +0000985 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +0000986 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000987
Chris Lattner8806e322011-07-10 00:18:59 +0000988 if (!isFuncTypeConvertible(FPT))
989 return llvm::StructType::get(getLLVMContext());
990
991 const CGFunctionInfo *Info;
992 if (isa<CXXDestructorDecl>(MD))
John McCalla729c622012-02-17 03:33:10 +0000993 Info = &arrangeCXXDestructor(cast<CXXDestructorDecl>(MD), GD.getDtorType());
Chris Lattner8806e322011-07-10 00:18:59 +0000994 else
John McCalla729c622012-02-17 03:33:10 +0000995 Info = &arrangeCXXMethodDeclaration(MD);
996 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +0000997}
998
Daniel Dunbar3668cb22009-02-02 23:43:58 +0000999void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbard931a872009-02-02 22:03:45 +00001000 const Decl *TargetDecl,
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001001 AttributeListType &PAL,
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00001002 unsigned &CallingConv,
1003 bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001004 llvm::AttrBuilder FuncAttrs;
1005 llvm::AttrBuilder RetAttrs;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001006
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001007 CallingConv = FI.getEffectiveCallingConvention();
1008
John McCallab26cfa2010-02-05 21:31:56 +00001009 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001010 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001011
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001012 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001013 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001014 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001015 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001016 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001017 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001018 if (TargetDecl->hasAttr<NoReturnAttr>())
1019 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
1020
1021 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
John McCallbe349de2010-07-08 06:48:12 +00001022 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl31ad7542011-03-13 17:09:40 +00001023 if (FPT && FPT->isNothrow(getContext()))
Bill Wendling207f0532012-12-20 19:27:06 +00001024 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith49af6292013-03-05 08:30:04 +00001025 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1026 // These attributes are not inherited by overloads.
1027 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1028 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001029 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001030 }
1031
Eric Christopherbf005ec2011-08-15 22:38:22 +00001032 // 'const' and 'pure' attribute functions are also nounwind.
1033 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001034 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1035 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001036 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001037 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1038 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001039 }
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001040 if (TargetDecl->hasAttr<MallocAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001041 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001042 }
1043
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001044 if (CodeGenOpts.OptimizeSize)
Bill Wendling207f0532012-12-20 19:27:06 +00001045 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
Quentin Colombet5ee5ca12012-10-26 00:29:48 +00001046 if (CodeGenOpts.OptimizeSize == 2)
Bill Wendling207f0532012-12-20 19:27:06 +00001047 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001048 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001049 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001050 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001051 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Devang Patel6e467b12009-06-04 23:32:02 +00001052
Bill Wendling2f81db62013-02-22 20:53:29 +00001053 if (AttrOnCallSite) {
1054 // Attributes that should go on the call site only.
1055 if (!CodeGenOpts.SimplifyLibCalls)
1056 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Bill Wendling706469b2013-02-28 22:49:57 +00001057 } else {
1058 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001059 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001060 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001061 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001062 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001063 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001064 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001065 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001066 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001067 }
1068
Bill Wendlingdabafea2013-03-13 22:24:33 +00001069 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001070 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001071 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001072 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001073 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001074 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001075 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001076 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001077 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001078 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001079 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001080 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001081
Bill Wendlingd8f49502013-08-01 21:41:02 +00001082 if (!CodeGenOpts.StackRealignment)
1083 FuncAttrs.addAttribute("no-realign-stack");
Bill Wendling985d1c52013-02-15 21:30:01 +00001084 }
1085
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001086 QualType RetTy = FI.getReturnType();
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001087 unsigned Index = 1;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001088 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001089 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001090 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001091 if (RetTy->hasSignedIntegerRepresentation())
1092 RetAttrs.addAttribute(llvm::Attribute::SExt);
1093 else if (RetTy->hasUnsignedIntegerRepresentation())
1094 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001095 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001096 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001097 if (RetAI.getInReg())
1098 RetAttrs.addAttribute(llvm::Attribute::InReg);
1099 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001100 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001101 break;
1102
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001103 case ABIArgInfo::Indirect: {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001104 llvm::AttrBuilder SRETAttrs;
Bill Wendling207f0532012-12-20 19:27:06 +00001105 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001106 if (RetAI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001107 SRETAttrs.addAttribute(llvm::Attribute::InReg);
Bill Wendlinga7912f82012-10-10 07:36:56 +00001108 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001109 AttributeSet::get(getLLVMContext(), Index, SRETAttrs));
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001110
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001111 ++Index;
Daniel Dunbarc2304432009-03-18 19:51:01 +00001112 // sret disables readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001113 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1114 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001115 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001116 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001117
Daniel Dunbard3674e62008-09-11 01:48:57 +00001118 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001119 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001120 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001121
Bill Wendlinga7912f82012-10-10 07:36:56 +00001122 if (RetAttrs.hasAttributes())
1123 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001124 AttributeSet::get(getLLVMContext(),
1125 llvm::AttributeSet::ReturnIndex,
1126 RetAttrs));
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001127
Mike Stump11289f42009-09-09 15:08:12 +00001128 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
Daniel Dunbar313321e2009-02-03 05:31:23 +00001129 ie = FI.arg_end(); it != ie; ++it) {
1130 QualType ParamType = it->type;
1131 const ABIArgInfo &AI = it->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001132 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001133
Rafael Espindolafad28de2012-10-24 01:59:00 +00001134 if (AI.getPaddingType()) {
Bill Wendling290d9522013-01-27 02:46:53 +00001135 if (AI.getPaddingInReg())
1136 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index,
1137 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001138 // Increment Index if there is padding.
1139 ++Index;
1140 }
1141
John McCall39ec71f2010-03-27 00:47:27 +00001142 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1143 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001144 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001145 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001146 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001147 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001148 Attrs.addAttribute(llvm::Attribute::SExt);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001149 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001150 Attrs.addAttribute(llvm::Attribute::ZExt);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001151 // FALL THROUGH
1152 case ABIArgInfo::Direct:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001153 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001154 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001155
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001156 // FIXME: handle sseregparm someday...
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001157
Chris Lattner2192fe52011-07-18 04:24:23 +00001158 if (llvm::StructType *STy =
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001159 dyn_cast<llvm::StructType>(AI.getCoerceToType())) {
1160 unsigned Extra = STy->getNumElements()-1; // 1 will be added below.
Bill Wendlinga7912f82012-10-10 07:36:56 +00001161 if (Attrs.hasAttributes())
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001162 for (unsigned I = 0; I < Extra; ++I)
Bill Wendling290d9522013-01-27 02:46:53 +00001163 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index + I,
1164 Attrs));
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001165 Index += Extra;
1166 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001167 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001168
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001169 case ABIArgInfo::Indirect:
Rafael Espindola703c47f2012-10-19 05:04:37 +00001170 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001171 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001172
Anders Carlsson20759ad2009-09-16 15:53:40 +00001173 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001174 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001175
Bill Wendlinga7912f82012-10-10 07:36:56 +00001176 Attrs.addAlignmentAttr(AI.getIndirectAlign());
1177
Daniel Dunbarc2304432009-03-18 19:51:01 +00001178 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001179 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1180 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001181 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001182
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001183 case ABIArgInfo::Ignore:
1184 // Skip increment, no matching LLVM parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001185 continue;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001186
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001187 case ABIArgInfo::Expand: {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001188 SmallVector<llvm::Type*, 8> types;
Mike Stump18bb9282009-05-16 07:57:57 +00001189 // FIXME: This is rather inefficient. Do we ever actually need to do
1190 // anything here? The result should be just reconstructed on the other
1191 // side, so extension should be a non-issue.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001192 getTypes().GetExpandedTypes(ParamType, types);
John McCall85dd2c52011-05-15 02:19:42 +00001193 Index += types.size();
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001194 continue;
1195 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001196 }
Mike Stump11289f42009-09-09 15:08:12 +00001197
Bill Wendlinga7912f82012-10-10 07:36:56 +00001198 if (Attrs.hasAttributes())
Bill Wendling290d9522013-01-27 02:46:53 +00001199 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index, Attrs));
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001200 ++Index;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001201 }
Bill Wendlinga7912f82012-10-10 07:36:56 +00001202 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001203 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001204 AttributeSet::get(getLLVMContext(),
1205 llvm::AttributeSet::FunctionIndex,
1206 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001207}
1208
John McCalla738c252011-03-09 04:27:21 +00001209/// An argument came in as a promoted argument; demote it back to its
1210/// declared type.
1211static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1212 const VarDecl *var,
1213 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001214 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001215
1216 // This can happen with promotions that actually don't change the
1217 // underlying type, like the enum promotions.
1218 if (value->getType() == varType) return value;
1219
1220 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1221 && "unexpected promotion type");
1222
1223 if (isa<llvm::IntegerType>(varType))
1224 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1225
1226 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1227}
1228
Daniel Dunbard931a872009-02-02 22:03:45 +00001229void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1230 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00001231 const FunctionArgList &Args) {
John McCallcaa19452009-07-28 01:00:58 +00001232 // If this is an implicit-return-zero function, go ahead and
1233 // initialize the return value. TODO: it might be nice to have
1234 // a more general mechanism for this that didn't require synthesized
1235 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00001236 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00001237 if (FD->hasImplicitReturnZero()) {
1238 QualType RetTy = FD->getResultType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001239 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00001240 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00001241 Builder.CreateStore(Zero, ReturnValue);
1242 }
1243 }
1244
Mike Stump18bb9282009-05-16 07:57:57 +00001245 // FIXME: We no longer need the types from FunctionArgList; lift up and
1246 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00001247
Daniel Dunbar613855c2008-09-09 23:27:19 +00001248 // Emit allocs for param decls. Give the LLVM Argument nodes names.
1249 llvm::Function::arg_iterator AI = Fn->arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00001250
Daniel Dunbar613855c2008-09-09 23:27:19 +00001251 // Name the struct return argument.
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001252 if (CGM.ReturnTypeUsesSRet(FI)) {
Daniel Dunbar613855c2008-09-09 23:27:19 +00001253 AI->setName("agg.result");
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001254 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1255 AI->getArgNo() + 1,
1256 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00001257 ++AI;
1258 }
Mike Stump11289f42009-09-09 15:08:12 +00001259
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00001260 assert(FI.arg_size() == Args.size() &&
1261 "Mismatch between function signature & arguments.");
Devang Patel68a15252011-03-03 20:13:15 +00001262 unsigned ArgNo = 1;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001263 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Devang Patel68a15252011-03-03 20:13:15 +00001264 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
1265 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00001266 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001267 QualType Ty = info_it->type;
1268 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001269
John McCalla738c252011-03-09 04:27:21 +00001270 bool isPromoted =
1271 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1272
Rafael Espindolafad28de2012-10-24 01:59:00 +00001273 // Skip the dummy padding argument.
1274 if (ArgI.getPaddingType())
1275 ++AI;
1276
Daniel Dunbard3674e62008-09-11 01:48:57 +00001277 switch (ArgI.getKind()) {
Daniel Dunbar747865a2009-02-05 09:16:39 +00001278 case ABIArgInfo::Indirect: {
Chris Lattner3dd716c2010-06-28 23:44:11 +00001279 llvm::Value *V = AI;
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001280
John McCall47fb9502013-03-07 21:37:08 +00001281 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001282 // Aggregates and complex variables are accessed by reference. All we
1283 // need to do is realign the value, if requested
1284 if (ArgI.getIndirectRealign()) {
1285 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1286
1287 // Copy from the incoming argument pointer to the temporary with the
1288 // appropriate alignment.
1289 //
1290 // FIXME: We should have a common utility for generating an aggregate
1291 // copy.
Chris Lattner2192fe52011-07-18 04:24:23 +00001292 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyck705ba072011-01-19 01:58:38 +00001293 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumidd634362011-03-10 14:02:21 +00001294 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1295 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1296 Builder.CreateMemCpy(Dst,
1297 Src,
Ken Dyck705ba072011-01-19 01:58:38 +00001298 llvm::ConstantInt::get(IntPtrTy,
1299 Size.getQuantity()),
Benjamin Krameracc6b4e2010-12-30 00:13:21 +00001300 ArgI.getIndirectAlign(),
1301 false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001302 V = AlignedTemp;
1303 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00001304 } else {
1305 // Load scalar value from indirect argument.
Ken Dyck705ba072011-01-19 01:58:38 +00001306 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
1307 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty);
John McCalla738c252011-03-09 04:27:21 +00001308
1309 if (isPromoted)
1310 V = emitArgumentDemotion(*this, Arg, V);
Daniel Dunbar747865a2009-02-05 09:16:39 +00001311 }
Devang Patel68a15252011-03-03 20:13:15 +00001312 EmitParmDecl(*Arg, V, ArgNo);
Daniel Dunbar747865a2009-02-05 09:16:39 +00001313 break;
1314 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001315
1316 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001317 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00001318
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001319 // If we have the trivial case, handle it with no muss and fuss.
1320 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001321 ArgI.getCoerceToType() == ConvertType(Ty) &&
1322 ArgI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001323 assert(AI != Fn->arg_end() && "Argument mismatch!");
1324 llvm::Value *V = AI;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001325
Bill Wendling507c3512012-10-16 05:23:44 +00001326 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001327 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1328 AI->getArgNo() + 1,
1329 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00001330
Chris Lattner7369c142011-07-20 06:29:00 +00001331 // Ensure the argument is the correct type.
1332 if (V->getType() != ArgI.getCoerceToType())
1333 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1334
John McCalla738c252011-03-09 04:27:21 +00001335 if (isPromoted)
1336 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00001337
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001338 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
1339 if (MD->isVirtual() && Arg == CXXABIThisDecl)
1340 V = CGM.getCXXABI().adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
1341 }
1342
Rafael Espindola8778c282012-11-29 16:09:03 +00001343 // Because of merging of function types from multiple decls it is
1344 // possible for the type of an argument to not match the corresponding
1345 // type in the function type. Since we are codegening the callee
1346 // in here, add a cast to the argument type.
1347 llvm::Type *LTy = ConvertType(Arg->getType());
1348 if (V->getType() != LTy)
1349 V = Builder.CreateBitCast(V, LTy);
1350
Devang Patel68a15252011-03-03 20:13:15 +00001351 EmitParmDecl(*Arg, V, ArgNo);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001352 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00001353 }
Mike Stump11289f42009-09-09 15:08:12 +00001354
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001355 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001356
Chris Lattnerff941a62010-07-28 18:24:28 +00001357 // The alignment we need to use is the max of the requested alignment for
1358 // the argument plus the alignment required by our access code below.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001359 unsigned AlignmentToUse =
Micah Villmowdd31ca12012-10-08 16:25:52 +00001360 CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerff941a62010-07-28 18:24:28 +00001361 AlignmentToUse = std::max(AlignmentToUse,
1362 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001363
Chris Lattnerff941a62010-07-28 18:24:28 +00001364 Alloca->setAlignment(AlignmentToUse);
Chris Lattnerc401de92010-07-05 20:21:00 +00001365 llvm::Value *V = Alloca;
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001366 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001367
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001368 // If the value is offset in memory, apply the offset now.
1369 if (unsigned Offs = ArgI.getDirectOffset()) {
1370 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1371 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001372 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001373 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1374 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001375
Chris Lattner15ec3612010-06-29 00:06:42 +00001376 // If the coerce-to type is a first class aggregate, we flatten it and
1377 // pass the elements. Either way is semantically identical, but fast-isel
1378 // and the optimizer generally likes scalar values better than FCAs.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001379 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
1380 if (STy && STy->getNumElements() > 1) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001381 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001382 llvm::Type *DstTy =
1383 cast<llvm::PointerType>(Ptr->getType())->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00001384 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001385
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001386 if (SrcSize <= DstSize) {
1387 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1388
1389 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1390 assert(AI != Fn->arg_end() && "Argument mismatch!");
1391 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1392 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
1393 Builder.CreateStore(AI++, EltPtr);
1394 }
1395 } else {
1396 llvm::AllocaInst *TempAlloca =
1397 CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1398 TempAlloca->setAlignment(AlignmentToUse);
1399 llvm::Value *TempV = TempAlloca;
1400
1401 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1402 assert(AI != Fn->arg_end() && "Argument mismatch!");
1403 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1404 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(TempV, 0, i);
1405 Builder.CreateStore(AI++, EltPtr);
1406 }
1407
1408 Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
Chris Lattner15ec3612010-06-29 00:06:42 +00001409 }
1410 } else {
1411 // Simple case, just do a coerced store of the argument into the alloca.
1412 assert(AI != Fn->arg_end() && "Argument mismatch!");
Chris Lattner9e748e92010-06-29 00:14:52 +00001413 AI->setName(Arg->getName() + ".coerce");
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001414 CreateCoercedStore(AI++, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00001415 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001416
1417
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001418 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00001419 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Daniel Dunbar03816342010-08-21 02:24:36 +00001420 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty);
John McCalla738c252011-03-09 04:27:21 +00001421 if (isPromoted)
1422 V = emitArgumentDemotion(*this, Arg, V);
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00001423 }
Devang Patel68a15252011-03-03 20:13:15 +00001424 EmitParmDecl(*Arg, V, ArgNo);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001425 continue; // Skip ++AI increment, already done.
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001426 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001427
1428 case ABIArgInfo::Expand: {
1429 // If this structure was expanded into multiple arguments then
1430 // we need to create a temporary and reconstruct it from the
1431 // arguments.
Eli Friedman3d9f47f2011-11-03 21:39:02 +00001432 llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
Eli Friedmana0544d62011-12-03 04:14:32 +00001433 CharUnits Align = getContext().getDeclAlign(Arg);
1434 Alloca->setAlignment(Align.getQuantity());
1435 LValue LV = MakeAddrLValue(Alloca, Ty, Align);
Eli Friedman3d9f47f2011-11-03 21:39:02 +00001436 llvm::Function::arg_iterator End = ExpandTypeFromArgs(Ty, LV, AI);
1437 EmitParmDecl(*Arg, Alloca, ArgNo);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001438
1439 // Name the arguments used in expansion and increment AI.
1440 unsigned Index = 0;
1441 for (; AI != End; ++AI, ++Index)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001442 AI->setName(Arg->getName() + "." + Twine(Index));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001443 continue;
1444 }
1445
1446 case ABIArgInfo::Ignore:
1447 // Initialize the local variable appropriately.
John McCall47fb9502013-03-07 21:37:08 +00001448 if (!hasScalarEvaluationKind(Ty))
Devang Patel68a15252011-03-03 20:13:15 +00001449 EmitParmDecl(*Arg, CreateMemTemp(Ty), ArgNo);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001450 else
Devang Patel68a15252011-03-03 20:13:15 +00001451 EmitParmDecl(*Arg, llvm::UndefValue::get(ConvertType(Arg->getType())),
1452 ArgNo);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001453
1454 // Skip increment, no matching LLVM parameter.
1455 continue;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001456 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001457
1458 ++AI;
Daniel Dunbar613855c2008-09-09 23:27:19 +00001459 }
1460 assert(AI == Fn->arg_end() && "Argument mismatch!");
1461}
1462
John McCallffa2c1a2012-01-29 07:46:59 +00001463static void eraseUnusedBitCasts(llvm::Instruction *insn) {
1464 while (insn->use_empty()) {
1465 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
1466 if (!bitcast) return;
1467
1468 // This is "safe" because we would have used a ConstantExpr otherwise.
1469 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
1470 bitcast->eraseFromParent();
1471 }
1472}
1473
John McCall31168b02011-06-15 23:02:42 +00001474/// Try to emit a fused autorelease of a return result.
1475static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
1476 llvm::Value *result) {
1477 // We must be immediately followed the cast.
1478 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
1479 if (BB->empty()) return 0;
1480 if (&BB->back() != result) return 0;
1481
Chris Lattner2192fe52011-07-18 04:24:23 +00001482 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00001483
1484 // result is in a BasicBlock and is therefore an Instruction.
1485 llvm::Instruction *generator = cast<llvm::Instruction>(result);
1486
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001487 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00001488
1489 // Look for:
1490 // %generator = bitcast %type1* %generator2 to %type2*
1491 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
1492 // We would have emitted this as a constant if the operand weren't
1493 // an Instruction.
1494 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
1495
1496 // Require the generator to be immediately followed by the cast.
1497 if (generator->getNextNode() != bitcast)
1498 return 0;
1499
1500 insnsToKill.push_back(bitcast);
1501 }
1502
1503 // Look for:
1504 // %generator = call i8* @objc_retain(i8* %originalResult)
1505 // or
1506 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
1507 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
1508 if (!call) return 0;
1509
1510 bool doRetainAutorelease;
1511
1512 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
1513 doRetainAutorelease = true;
1514 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
1515 .objc_retainAutoreleasedReturnValue) {
1516 doRetainAutorelease = false;
1517
John McCallcfa4e9b2012-09-07 23:30:50 +00001518 // If we emitted an assembly marker for this call (and the
1519 // ARCEntrypoints field should have been set if so), go looking
1520 // for that call. If we can't find it, we can't do this
1521 // optimization. But it should always be the immediately previous
1522 // instruction, unless we needed bitcasts around the call.
1523 if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
1524 llvm::Instruction *prev = call->getPrevNode();
1525 assert(prev);
1526 if (isa<llvm::BitCastInst>(prev)) {
1527 prev = prev->getPrevNode();
1528 assert(prev);
1529 }
1530 assert(isa<llvm::CallInst>(prev));
1531 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
1532 CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
1533 insnsToKill.push_back(prev);
1534 }
John McCall31168b02011-06-15 23:02:42 +00001535 } else {
1536 return 0;
1537 }
1538
1539 result = call->getArgOperand(0);
1540 insnsToKill.push_back(call);
1541
1542 // Keep killing bitcasts, for sanity. Note that we no longer care
1543 // about precise ordering as long as there's exactly one use.
1544 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
1545 if (!bitcast->hasOneUse()) break;
1546 insnsToKill.push_back(bitcast);
1547 result = bitcast->getOperand(0);
1548 }
1549
1550 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001551 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00001552 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
1553 (*i)->eraseFromParent();
1554
1555 // Do the fused retain/autorelease if we were asked to.
1556 if (doRetainAutorelease)
1557 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
1558
1559 // Cast back to the result type.
1560 return CGF.Builder.CreateBitCast(result, resultType);
1561}
1562
John McCallffa2c1a2012-01-29 07:46:59 +00001563/// If this is a +1 of the value of an immutable 'self', remove it.
1564static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
1565 llvm::Value *result) {
1566 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00001567 const ObjCMethodDecl *method =
1568 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCallffa2c1a2012-01-29 07:46:59 +00001569 if (!method) return 0;
1570 const VarDecl *self = method->getSelfDecl();
1571 if (!self->getType().isConstQualified()) return 0;
1572
1573 // Look for a retain call.
1574 llvm::CallInst *retainCall =
1575 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
1576 if (!retainCall ||
1577 retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
1578 return 0;
1579
1580 // Look for an ordinary load of 'self'.
1581 llvm::Value *retainedValue = retainCall->getArgOperand(0);
1582 llvm::LoadInst *load =
1583 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
1584 if (!load || load->isAtomic() || load->isVolatile() ||
1585 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
1586 return 0;
1587
1588 // Okay! Burn it all down. This relies for correctness on the
1589 // assumption that the retain is emitted as part of the return and
1590 // that thereafter everything is used "linearly".
1591 llvm::Type *resultType = result->getType();
1592 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
1593 assert(retainCall->use_empty());
1594 retainCall->eraseFromParent();
1595 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
1596
1597 return CGF.Builder.CreateBitCast(load, resultType);
1598}
1599
John McCall31168b02011-06-15 23:02:42 +00001600/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00001601///
1602/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00001603static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
1604 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00001605 // If we're returning 'self', kill the initial retain. This is a
1606 // heuristic attempt to "encourage correctness" in the really unfortunate
1607 // case where we have a return of self during a dealloc and we desperately
1608 // need to avoid the possible autorelease.
1609 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
1610 return self;
1611
John McCall31168b02011-06-15 23:02:42 +00001612 // At -O0, try to emit a fused retain/autorelease.
1613 if (CGF.shouldUseFusedARCCalls())
1614 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
1615 return fused;
1616
1617 return CGF.EmitARCAutoreleaseReturnValue(result);
1618}
1619
John McCall6e1c0122012-01-29 02:35:02 +00001620/// Heuristically search for a dominating store to the return-value slot.
1621static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
1622 // If there are multiple uses of the return-value slot, just check
1623 // for something immediately preceding the IP. Sometimes this can
1624 // happen with how we generate implicit-returns; it can also happen
1625 // with noreturn cleanups.
1626 if (!CGF.ReturnValue->hasOneUse()) {
1627 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
1628 if (IP->empty()) return 0;
1629 llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back());
1630 if (!store) return 0;
1631 if (store->getPointerOperand() != CGF.ReturnValue) return 0;
1632 assert(!store->isAtomic() && !store->isVolatile()); // see below
1633 return store;
1634 }
1635
1636 llvm::StoreInst *store =
1637 dyn_cast<llvm::StoreInst>(CGF.ReturnValue->use_back());
1638 if (!store) return 0;
1639
1640 // These aren't actually possible for non-coerced returns, and we
1641 // only care about non-coerced returns on this code path.
1642 assert(!store->isAtomic() && !store->isVolatile());
1643
1644 // Now do a first-and-dirty dominance check: just walk up the
1645 // single-predecessors chain from the current insertion point.
1646 llvm::BasicBlock *StoreBB = store->getParent();
1647 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
1648 while (IP != StoreBB) {
1649 if (!(IP = IP->getSinglePredecessor()))
1650 return 0;
1651 }
1652
1653 // Okay, the store's basic block dominates the insertion point; we
1654 // can do our thing.
1655 return store;
1656}
1657
Adrian Prantl3be10542013-05-02 17:30:20 +00001658void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
1659 bool EmitRetDbgLoc) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001660 // Functions with no result always return void.
Chris Lattner726b3d02010-06-26 23:13:19 +00001661 if (ReturnValue == 0) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001662 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00001663 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001664 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00001665
Dan Gohman481e40c2010-07-20 20:13:52 +00001666 llvm::DebugLoc RetDbgLoc;
Chris Lattner726b3d02010-06-26 23:13:19 +00001667 llvm::Value *RV = 0;
1668 QualType RetTy = FI.getReturnType();
1669 const ABIArgInfo &RetAI = FI.getReturnInfo();
1670
1671 switch (RetAI.getKind()) {
Daniel Dunbar03816342010-08-21 02:24:36 +00001672 case ABIArgInfo::Indirect: {
John McCall47fb9502013-03-07 21:37:08 +00001673 switch (getEvaluationKind(RetTy)) {
1674 case TEK_Complex: {
1675 ComplexPairTy RT =
1676 EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy));
1677 EmitStoreOfComplex(RT,
1678 MakeNaturalAlignAddrLValue(CurFn->arg_begin(), RetTy),
1679 /*isInit*/ true);
1680 break;
1681 }
1682 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00001683 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00001684 break;
1685 case TEK_Scalar:
1686 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
1687 MakeNaturalAlignAddrLValue(CurFn->arg_begin(), RetTy),
1688 /*isInit*/ true);
1689 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00001690 }
1691 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00001692 }
Chris Lattner726b3d02010-06-26 23:13:19 +00001693
1694 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001695 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001696 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
1697 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001698 // The internal return value temp always will have pointer-to-return-type
1699 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001700
John McCall6e1c0122012-01-29 02:35:02 +00001701 // If there is a dominating store to ReturnValue, we can elide
1702 // the load, zap the store, and usually zap the alloca.
1703 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00001704 // Reuse the debug location from the store unless there is
1705 // cleanup code to be emitted between the store and return
1706 // instruction.
1707 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00001708 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001709 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001710 RV = SI->getValueOperand();
1711 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001712
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001713 // If that was the only use of the return value, nuke it as well now.
1714 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
1715 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
1716 ReturnValue = 0;
1717 }
John McCall6e1c0122012-01-29 02:35:02 +00001718
1719 // Otherwise, we have to do a simple load.
1720 } else {
1721 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00001722 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001723 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001724 llvm::Value *V = ReturnValue;
1725 // If the value is offset in memory, apply the offset now.
1726 if (unsigned Offs = RetAI.getDirectOffset()) {
1727 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
1728 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001729 V = Builder.CreateBitCast(V,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001730 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
1731 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001732
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001733 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00001734 }
John McCall31168b02011-06-15 23:02:42 +00001735
1736 // In ARC, end functions that return a retainable type with a call
1737 // to objc_autoreleaseReturnValue.
1738 if (AutoreleaseResult) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001739 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001740 !FI.isReturnsRetained() &&
1741 RetTy->isObjCRetainableType());
1742 RV = emitAutoreleaseOfResult(*this, RV);
1743 }
1744
Chris Lattner726b3d02010-06-26 23:13:19 +00001745 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00001746
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001747 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00001748 break;
1749
1750 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001751 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00001752 }
1753
Daniel Dunbar6696e222010-06-30 21:27:58 +00001754 llvm::Instruction *Ret = RV ? Builder.CreateRet(RV) : Builder.CreateRetVoid();
Devang Patel65497582010-07-21 18:08:50 +00001755 if (!RetDbgLoc.isUnknown())
1756 Ret->setDebugLoc(RetDbgLoc);
Daniel Dunbar613855c2008-09-09 23:27:19 +00001757}
1758
John McCall32ea9692011-03-11 20:59:21 +00001759void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
1760 const VarDecl *param) {
John McCall23f66262010-05-26 22:34:26 +00001761 // StartFunction converted the ABI-lowered parameter(s) into a
1762 // local alloca. We need to turn that into an r-value suitable
1763 // for EmitCall.
John McCall32ea9692011-03-11 20:59:21 +00001764 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00001765
John McCall32ea9692011-03-11 20:59:21 +00001766 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001767
John McCall23f66262010-05-26 22:34:26 +00001768 // For the most part, we just need to load the alloca, except:
1769 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall47fb9502013-03-07 21:37:08 +00001770 // 2) references to non-scalars are pointers directly to the aggregate.
1771 // I don't know why references to scalars are different here.
John McCall32ea9692011-03-11 20:59:21 +00001772 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall47fb9502013-03-07 21:37:08 +00001773 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall32ea9692011-03-11 20:59:21 +00001774 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00001775
1776 // Locals which are references to scalars are represented
1777 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00001778 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00001779 }
1780
John McCall47fb9502013-03-07 21:37:08 +00001781 args.add(convertTempToRValue(local, type), type);
John McCall23f66262010-05-26 22:34:26 +00001782}
1783
John McCall31168b02011-06-15 23:02:42 +00001784static bool isProvablyNull(llvm::Value *addr) {
1785 return isa<llvm::ConstantPointerNull>(addr);
1786}
1787
1788static bool isProvablyNonNull(llvm::Value *addr) {
1789 return isa<llvm::AllocaInst>(addr);
1790}
1791
1792/// Emit the actual writing-back of a writeback.
1793static void emitWriteback(CodeGenFunction &CGF,
1794 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00001795 const LValue &srcLV = writeback.Source;
1796 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00001797 assert(!isProvablyNull(srcAddr) &&
1798 "shouldn't have writeback for provably null argument");
1799
1800 llvm::BasicBlock *contBB = 0;
1801
1802 // If the argument wasn't provably non-null, we need to null check
1803 // before doing the store.
1804 bool provablyNonNull = isProvablyNonNull(srcAddr);
1805 if (!provablyNonNull) {
1806 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
1807 contBB = CGF.createBasicBlock("icr.done");
1808
1809 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
1810 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
1811 CGF.EmitBlock(writebackBB);
1812 }
1813
1814 // Load the value to writeback.
1815 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
1816
1817 // Cast it back, in case we're writing an id to a Foo* or something.
1818 value = CGF.Builder.CreateBitCast(value,
1819 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
1820 "icr.writeback-cast");
1821
1822 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00001823
1824 // If we have a "to use" value, it's something we need to emit a use
1825 // of. This has to be carefully threaded in: if it's done after the
1826 // release it's potentially undefined behavior (and the optimizer
1827 // will ignore it), and if it happens before the retain then the
1828 // optimizer could move the release there.
1829 if (writeback.ToUse) {
1830 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
1831
1832 // Retain the new value. No need to block-copy here: the block's
1833 // being passed up the stack.
1834 value = CGF.EmitARCRetainNonBlock(value);
1835
1836 // Emit the intrinsic use here.
1837 CGF.EmitARCIntrinsicUse(writeback.ToUse);
1838
1839 // Load the old value (primitively).
1840 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV);
1841
1842 // Put the new value in place (primitively).
1843 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
1844
1845 // Release the old value.
1846 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
1847
1848 // Otherwise, we can just do a normal lvalue store.
1849 } else {
1850 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
1851 }
John McCall31168b02011-06-15 23:02:42 +00001852
1853 // Jump to the continuation block.
1854 if (!provablyNonNull)
1855 CGF.EmitBlock(contBB);
1856}
1857
1858static void emitWritebacks(CodeGenFunction &CGF,
1859 const CallArgList &args) {
1860 for (CallArgList::writeback_iterator
1861 i = args.writeback_begin(), e = args.writeback_end(); i != e; ++i)
1862 emitWriteback(CGF, *i);
1863}
1864
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001865static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
1866 const CallArgList &CallArgs) {
1867 assert(CGF.getTarget().getCXXABI().isArgumentDestroyedByCallee());
1868 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
1869 CallArgs.getCleanupsToDeactivate();
1870 // Iterate in reverse to increase the likelihood of popping the cleanup.
1871 for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
1872 I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
1873 CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
1874 I->IsActiveIP->eraseFromParent();
1875 }
1876}
1877
John McCalleff18842013-03-23 02:35:54 +00001878static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
1879 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
1880 if (uop->getOpcode() == UO_AddrOf)
1881 return uop->getSubExpr();
1882 return 0;
1883}
1884
John McCall31168b02011-06-15 23:02:42 +00001885/// Emit an argument that's being passed call-by-writeback. That is,
1886/// we are passing the address of
1887static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
1888 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00001889 LValue srcLV;
1890
1891 // Make an optimistic effort to emit the address as an l-value.
1892 // This can fail if the the argument expression is more complicated.
1893 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
1894 srcLV = CGF.EmitLValue(lvExpr);
1895
1896 // Otherwise, just emit it as a scalar.
1897 } else {
1898 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
1899
1900 QualType srcAddrType =
1901 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
1902 srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
1903 }
1904 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00001905
1906 // The dest and src types don't necessarily match in LLVM terms
1907 // because of the crazy ObjC compatibility rules.
1908
Chris Lattner2192fe52011-07-18 04:24:23 +00001909 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00001910 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
1911
1912 // If the address is a constant null, just pass the appropriate null.
1913 if (isProvablyNull(srcAddr)) {
1914 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
1915 CRE->getType());
1916 return;
1917 }
1918
John McCall31168b02011-06-15 23:02:42 +00001919 // Create the temporary.
1920 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
1921 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001922 // Loading an l-value can introduce a cleanup if the l-value is __weak,
1923 // and that cleanup will be conditional if we can't prove that the l-value
1924 // isn't null, so we need to register a dominating point so that the cleanups
1925 // system will make valid IR.
1926 CodeGenFunction::ConditionalEvaluation condEval(CGF);
1927
John McCall31168b02011-06-15 23:02:42 +00001928 // Zero-initialize it if we're not doing a copy-initialization.
1929 bool shouldCopy = CRE->shouldCopy();
1930 if (!shouldCopy) {
1931 llvm::Value *null =
1932 llvm::ConstantPointerNull::get(
1933 cast<llvm::PointerType>(destType->getElementType()));
1934 CGF.Builder.CreateStore(null, temp);
1935 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001936
John McCall31168b02011-06-15 23:02:42 +00001937 llvm::BasicBlock *contBB = 0;
John McCalleff18842013-03-23 02:35:54 +00001938 llvm::BasicBlock *originBB = 0;
John McCall31168b02011-06-15 23:02:42 +00001939
1940 // If the address is *not* known to be non-null, we need to switch.
1941 llvm::Value *finalArgument;
1942
1943 bool provablyNonNull = isProvablyNonNull(srcAddr);
1944 if (provablyNonNull) {
1945 finalArgument = temp;
1946 } else {
1947 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
1948
1949 finalArgument = CGF.Builder.CreateSelect(isNull,
1950 llvm::ConstantPointerNull::get(destType),
1951 temp, "icr.argument");
1952
1953 // If we need to copy, then the load has to be conditional, which
1954 // means we need control flow.
1955 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00001956 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00001957 contBB = CGF.createBasicBlock("icr.cont");
1958 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
1959 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
1960 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001961 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00001962 }
1963 }
1964
John McCalleff18842013-03-23 02:35:54 +00001965 llvm::Value *valueToUse = 0;
1966
John McCall31168b02011-06-15 23:02:42 +00001967 // Perform a copy if necessary.
1968 if (shouldCopy) {
John McCall55e1fbc2011-06-25 02:11:03 +00001969 RValue srcRV = CGF.EmitLoadOfLValue(srcLV);
John McCall31168b02011-06-15 23:02:42 +00001970 assert(srcRV.isScalar());
1971
1972 llvm::Value *src = srcRV.getScalarVal();
1973 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
1974 "icr.cast");
1975
1976 // Use an ordinary store, not a store-to-lvalue.
1977 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00001978
1979 // If optimization is enabled, and the value was held in a
1980 // __strong variable, we need to tell the optimizer that this
1981 // value has to stay alive until we're doing the store back.
1982 // This is because the temporary is effectively unretained,
1983 // and so otherwise we can violate the high-level semantics.
1984 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
1985 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
1986 valueToUse = src;
1987 }
John McCall31168b02011-06-15 23:02:42 +00001988 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001989
John McCall31168b02011-06-15 23:02:42 +00001990 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001991 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00001992 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00001993 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00001994
1995 // Make a phi for the value to intrinsically use.
1996 if (valueToUse) {
1997 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
1998 "icr.to-use");
1999 phiToUse->addIncoming(valueToUse, copyBB);
2000 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2001 originBB);
2002 valueToUse = phiToUse;
2003 }
2004
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002005 condEval.end(CGF);
2006 }
John McCall31168b02011-06-15 23:02:42 +00002007
John McCalleff18842013-03-23 02:35:54 +00002008 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00002009 args.add(RValue::get(finalArgument), CRE->getType());
2010}
2011
John McCall32ea9692011-03-11 20:59:21 +00002012void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2013 QualType type) {
John McCall31168b02011-06-15 23:02:42 +00002014 if (const ObjCIndirectCopyRestoreExpr *CRE
2015 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002016 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00002017 assert(getContext().hasSameType(E->getType(), type));
2018 return emitWritebackArg(*this, args, CRE);
2019 }
2020
John McCall0a76c0c2011-08-26 18:42:59 +00002021 assert(type->isReferenceType() == E->isGLValue() &&
2022 "reference binding to unmaterialized r-value!");
2023
John McCall17054bd62011-08-26 21:08:13 +00002024 if (E->isGLValue()) {
2025 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00002026 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00002027 }
Mike Stump11289f42009-09-09 15:08:12 +00002028
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002029 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2030
2031 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2032 // However, we still have to push an EH-only cleanup in case we unwind before
2033 // we make it to the call.
2034 if (HasAggregateEvalKind &&
2035 CGM.getTarget().getCXXABI().isArgumentDestroyedByCallee()) {
2036 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2037 if (RD && RD->hasNonTrivialDestructor()) {
2038 AggValueSlot Slot = CreateAggTemp(type, "agg.arg.tmp");
2039 Slot.setExternallyDestructed();
2040 EmitAggExpr(E, Slot);
2041 RValue RV = Slot.asRValue();
2042 args.add(RV, type);
2043
2044 pushDestroy(EHCleanup, RV.getAggregateAddr(), type, destroyCXXObject,
2045 /*useEHCleanupForArray*/ true);
2046 // This unreachable is a temporary marker which will be removed later.
2047 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2048 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
2049 return;
2050 }
2051 }
2052
2053 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00002054 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2055 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2056 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00002057 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2058 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2059 } else {
2060 // We can't represent a misaligned lvalue in the CallArgList, so copy
2061 // to an aligned temporary now.
2062 llvm::Value *tmp = CreateMemTemp(type);
2063 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2064 L.getAlignment());
2065 args.add(RValue::getAggregate(tmp), type);
2066 }
Eli Friedmandf968192011-05-26 00:10:27 +00002067 return;
2068 }
2069
John McCall32ea9692011-03-11 20:59:21 +00002070 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00002071}
2072
Dan Gohman515a60d2012-02-16 00:57:37 +00002073// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2074// optimizer it can aggressively ignore unwind edges.
2075void
2076CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2077 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2078 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2079 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2080 CGM.getNoObjCARCExceptionsMetadata());
2081}
2082
John McCall882987f2013-02-28 19:01:20 +00002083/// Emits a call to the given no-arguments nounwind runtime function.
2084llvm::CallInst *
2085CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2086 const llvm::Twine &name) {
2087 return EmitNounwindRuntimeCall(callee, ArrayRef<llvm::Value*>(), name);
2088}
2089
2090/// Emits a call to the given nounwind runtime function.
2091llvm::CallInst *
2092CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2093 ArrayRef<llvm::Value*> args,
2094 const llvm::Twine &name) {
2095 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2096 call->setDoesNotThrow();
2097 return call;
2098}
2099
2100/// Emits a simple call (never an invoke) to the given no-arguments
2101/// runtime function.
2102llvm::CallInst *
2103CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2104 const llvm::Twine &name) {
2105 return EmitRuntimeCall(callee, ArrayRef<llvm::Value*>(), name);
2106}
2107
2108/// Emits a simple call (never an invoke) to the given runtime
2109/// function.
2110llvm::CallInst *
2111CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2112 ArrayRef<llvm::Value*> args,
2113 const llvm::Twine &name) {
2114 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2115 call->setCallingConv(getRuntimeCC());
2116 return call;
2117}
2118
2119/// Emits a call or invoke to the given noreturn runtime function.
2120void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2121 ArrayRef<llvm::Value*> args) {
2122 if (getInvokeDest()) {
2123 llvm::InvokeInst *invoke =
2124 Builder.CreateInvoke(callee,
2125 getUnreachableBlock(),
2126 getInvokeDest(),
2127 args);
2128 invoke->setDoesNotReturn();
2129 invoke->setCallingConv(getRuntimeCC());
2130 } else {
2131 llvm::CallInst *call = Builder.CreateCall(callee, args);
2132 call->setDoesNotReturn();
2133 call->setCallingConv(getRuntimeCC());
2134 Builder.CreateUnreachable();
2135 }
2136}
2137
2138/// Emits a call or invoke instruction to the given nullary runtime
2139/// function.
2140llvm::CallSite
2141CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2142 const Twine &name) {
2143 return EmitRuntimeCallOrInvoke(callee, ArrayRef<llvm::Value*>(), name);
2144}
2145
2146/// Emits a call or invoke instruction to the given runtime function.
2147llvm::CallSite
2148CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2149 ArrayRef<llvm::Value*> args,
2150 const Twine &name) {
2151 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2152 callSite.setCallingConv(getRuntimeCC());
2153 return callSite;
2154}
2155
2156llvm::CallSite
2157CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2158 const Twine &Name) {
2159 return EmitCallOrInvoke(Callee, ArrayRef<llvm::Value *>(), Name);
2160}
2161
John McCallbd309292010-07-06 01:34:17 +00002162/// Emits a call or invoke instruction to the given function, depending
2163/// on the current state of the EH stack.
2164llvm::CallSite
2165CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00002166 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002167 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00002168 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00002169
Dan Gohman515a60d2012-02-16 00:57:37 +00002170 llvm::Instruction *Inst;
2171 if (!InvokeDest)
2172 Inst = Builder.CreateCall(Callee, Args, Name);
2173 else {
2174 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
2175 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
2176 EmitBlock(ContBB);
2177 }
2178
2179 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2180 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002181 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00002182 AddObjCARCExceptionMetadata(Inst);
2183
2184 return Inst;
John McCallbd309292010-07-06 01:34:17 +00002185}
2186
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002187static void checkArgMatches(llvm::Value *Elt, unsigned &ArgNo,
2188 llvm::FunctionType *FTy) {
2189 if (ArgNo < FTy->getNumParams())
2190 assert(Elt->getType() == FTy->getParamType(ArgNo));
2191 else
2192 assert(FTy->isVarArg());
2193 ++ArgNo;
2194}
2195
Chris Lattnerd59d8672011-07-12 06:29:11 +00002196void CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV,
Craig Topper5603df42013-07-05 19:34:19 +00002197 SmallVectorImpl<llvm::Value *> &Args,
Chris Lattnerd59d8672011-07-12 06:29:11 +00002198 llvm::FunctionType *IRFuncTy) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002199 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2200 unsigned NumElts = AT->getSize().getZExtValue();
2201 QualType EltTy = AT->getElementType();
2202 llvm::Value *Addr = RV.getAggregateAddr();
2203 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
2204 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, Elt);
John McCall47fb9502013-03-07 21:37:08 +00002205 RValue EltRV = convertTempToRValue(EltAddr, EltTy);
Bob Wilsone826a2a2011-08-03 05:58:22 +00002206 ExpandTypeToArgs(EltTy, EltRV, Args, IRFuncTy);
Chris Lattnerd59d8672011-07-12 06:29:11 +00002207 }
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002208 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002209 RecordDecl *RD = RT->getDecl();
2210 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
Eli Friedman7f1ff602012-04-16 03:54:45 +00002211 LValue LV = MakeAddrLValue(RV.getAggregateAddr(), Ty);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002212
2213 if (RD->isUnion()) {
2214 const FieldDecl *LargestFD = 0;
2215 CharUnits UnionSize = CharUnits::Zero();
2216
2217 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2218 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00002219 const FieldDecl *FD = *i;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002220 assert(!FD->isBitField() &&
2221 "Cannot expand structure with bit-field members.");
2222 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
2223 if (UnionSize < FieldSize) {
2224 UnionSize = FieldSize;
2225 LargestFD = FD;
2226 }
2227 }
2228 if (LargestFD) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00002229 RValue FldRV = EmitRValueForField(LV, LargestFD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002230 ExpandTypeToArgs(LargestFD->getType(), FldRV, Args, IRFuncTy);
2231 }
2232 } else {
2233 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2234 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00002235 FieldDecl *FD = *i;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002236
Eli Friedman7f1ff602012-04-16 03:54:45 +00002237 RValue FldRV = EmitRValueForField(LV, FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002238 ExpandTypeToArgs(FD->getType(), FldRV, Args, IRFuncTy);
2239 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00002240 }
Eli Friedman95ff7002011-11-15 02:46:03 +00002241 } else if (Ty->isAnyComplexType()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002242 ComplexPairTy CV = RV.getComplexVal();
2243 Args.push_back(CV.first);
2244 Args.push_back(CV.second);
2245 } else {
Chris Lattnerd59d8672011-07-12 06:29:11 +00002246 assert(RV.isScalar() &&
2247 "Unexpected non-scalar rvalue during struct expansion.");
2248
2249 // Insert a bitcast as needed.
2250 llvm::Value *V = RV.getScalarVal();
2251 if (Args.size() < IRFuncTy->getNumParams() &&
2252 V->getType() != IRFuncTy->getParamType(Args.size()))
2253 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(Args.size()));
2254
2255 Args.push_back(V);
2256 }
2257}
2258
2259
Daniel Dunbard931a872009-02-02 22:03:45 +00002260RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00002261 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00002262 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002263 const CallArgList &CallArgs,
David Chisnall9eecafa2010-05-01 11:15:56 +00002264 const Decl *TargetDecl,
David Chisnallff5f88c2010-05-02 13:41:58 +00002265 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00002266 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002267 SmallVector<llvm::Value*, 16> Args;
Daniel Dunbar613855c2008-09-09 23:27:19 +00002268
2269 // Handle struct-return functions by passing a pointer to the
2270 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00002271 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002272 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002273
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002274 // IRArgNo - Keep track of the argument number in the callee we're looking at.
2275 unsigned IRArgNo = 0;
2276 llvm::FunctionType *IRFuncTy =
2277 cast<llvm::FunctionType>(
2278 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00002279
Chris Lattner4ca97c32009-06-13 00:26:38 +00002280 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00002281 // alloca to hold the result, unless one is given to us.
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00002282 if (CGM.ReturnTypeUsesSRet(CallInfo)) {
Anders Carlsson17490832009-12-24 20:40:36 +00002283 llvm::Value *Value = ReturnValue.getValue();
2284 if (!Value)
Daniel Dunbara7566f12010-02-09 02:48:28 +00002285 Value = CreateMemTemp(RetTy);
Anders Carlsson17490832009-12-24 20:40:36 +00002286 Args.push_back(Value);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002287 checkArgMatches(Value, IRArgNo, IRFuncTy);
Anders Carlsson17490832009-12-24 20:40:36 +00002288 }
Mike Stump11289f42009-09-09 15:08:12 +00002289
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002290 assert(CallInfo.arg_size() == CallArgs.size() &&
2291 "Mismatch between function signature & arguments.");
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002292 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002293 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002294 I != E; ++I, ++info_it) {
2295 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00002296 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002297
John McCall47fb9502013-03-07 21:37:08 +00002298 CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002299
2300 // Insert a padding argument to ensure proper alignment.
2301 if (llvm::Type *PaddingType = ArgInfo.getPaddingType()) {
2302 Args.push_back(llvm::UndefValue::get(PaddingType));
2303 ++IRArgNo;
2304 }
2305
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002306 switch (ArgInfo.getKind()) {
Daniel Dunbar03816342010-08-21 02:24:36 +00002307 case ABIArgInfo::Indirect: {
Daniel Dunbar747865a2009-02-05 09:16:39 +00002308 if (RV.isScalar() || RV.isComplex()) {
2309 // Make a temporary alloca to pass the argument.
Eli Friedman7e68c882011-06-15 18:26:32 +00002310 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2311 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
2312 AI->setAlignment(ArgInfo.getIndirectAlign());
2313 Args.push_back(AI);
John McCall47fb9502013-03-07 21:37:08 +00002314
2315 LValue argLV =
2316 MakeAddrLValue(Args.back(), I->Ty, TypeAlign);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002317
Daniel Dunbar747865a2009-02-05 09:16:39 +00002318 if (RV.isScalar())
John McCall47fb9502013-03-07 21:37:08 +00002319 EmitStoreOfScalar(RV.getScalarVal(), argLV, /*init*/ true);
Daniel Dunbar747865a2009-02-05 09:16:39 +00002320 else
John McCall47fb9502013-03-07 21:37:08 +00002321 EmitStoreOfComplex(RV.getComplexVal(), argLV, /*init*/ true);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002322
2323 // Validate argument match.
2324 checkArgMatches(AI, IRArgNo, IRFuncTy);
Daniel Dunbar747865a2009-02-05 09:16:39 +00002325 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002326 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00002327 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002328 // 1. If the argument is not byval, and we are required to copy the
2329 // source. (This case doesn't occur on any common architecture.)
2330 // 2. If the argument is byval, RV is not sufficiently aligned, and
2331 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00002332 // 3. If the argument is byval, but RV is located in an address space
2333 // different than that of the argument (0).
Eli Friedmanf7456192011-06-15 22:09:18 +00002334 llvm::Value *Addr = RV.getAggregateAddr();
2335 unsigned Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002336 const llvm::DataLayout *TD = &CGM.getDataLayout();
Guy Benyei3832bfd2013-03-10 12:59:00 +00002337 const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
2338 const unsigned ArgAddrSpace = (IRArgNo < IRFuncTy->getNumParams() ?
2339 IRFuncTy->getParamType(IRArgNo)->getPointerAddressSpace() : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00002340 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall47fb9502013-03-07 21:37:08 +00002341 (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
Guy Benyei3832bfd2013-03-10 12:59:00 +00002342 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align) ||
2343 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002344 // Create an aligned temporary, and copy to it.
Eli Friedmanf7456192011-06-15 22:09:18 +00002345 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2346 if (Align > AI->getAlignment())
2347 AI->setAlignment(Align);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002348 Args.push_back(AI);
Chad Rosier615ed1a2012-03-29 17:37:10 +00002349 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002350
2351 // Validate argument match.
2352 checkArgMatches(AI, IRArgNo, IRFuncTy);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002353 } else {
2354 // Skip the extra memcpy call.
Eli Friedmanf7456192011-06-15 22:09:18 +00002355 Args.push_back(Addr);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002356
2357 // Validate argument match.
2358 checkArgMatches(Addr, IRArgNo, IRFuncTy);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002359 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002360 }
2361 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002362 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002363
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002364 case ABIArgInfo::Ignore:
2365 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002366
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002367 case ABIArgInfo::Extend:
2368 case ABIArgInfo::Direct: {
2369 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002370 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
2371 ArgInfo.getDirectOffset() == 0) {
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002372 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002373 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002374 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002375 else
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002376 V = Builder.CreateLoad(RV.getAggregateAddr());
2377
Chris Lattner3ce86682011-07-12 04:53:39 +00002378 // If the argument doesn't match, perform a bitcast to coerce it. This
2379 // can happen due to trivial type mismatches.
2380 if (IRArgNo < IRFuncTy->getNumParams() &&
2381 V->getType() != IRFuncTy->getParamType(IRArgNo))
2382 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRArgNo));
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002383 Args.push_back(V);
2384
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002385 checkArgMatches(V, IRArgNo, IRFuncTy);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002386 break;
2387 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002388
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002389 // FIXME: Avoid the conversion through memory if possible.
2390 llvm::Value *SrcPtr;
John McCall47fb9502013-03-07 21:37:08 +00002391 if (RV.isScalar() || RV.isComplex()) {
Eli Friedmanf4258eb2011-05-02 18:05:27 +00002392 SrcPtr = CreateMemTemp(I->Ty, "coerce");
John McCall47fb9502013-03-07 21:37:08 +00002393 LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
2394 if (RV.isScalar()) {
2395 EmitStoreOfScalar(RV.getScalarVal(), SrcLV, /*init*/ true);
2396 } else {
2397 EmitStoreOfComplex(RV.getComplexVal(), SrcLV, /*init*/ true);
2398 }
Mike Stump11289f42009-09-09 15:08:12 +00002399 } else
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002400 SrcPtr = RV.getAggregateAddr();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002401
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002402 // If the value is offset in memory, apply the offset now.
2403 if (unsigned Offs = ArgInfo.getDirectOffset()) {
2404 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
2405 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002406 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002407 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
2408
2409 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002410
Chris Lattner3dd716c2010-06-28 23:44:11 +00002411 // If the coerce-to type is a first class aggregate, we flatten it and
2412 // pass the elements. Either way is semantically identical, but fast-isel
2413 // and the optimizer generally likes scalar values better than FCAs.
Chris Lattner2192fe52011-07-18 04:24:23 +00002414 if (llvm::StructType *STy =
Chris Lattner15ec3612010-06-29 00:06:42 +00002415 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType())) {
Chandler Carrutha6399a52012-10-10 11:29:08 +00002416 llvm::Type *SrcTy =
2417 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
2418 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
2419 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
2420
2421 // If the source type is smaller than the destination type of the
2422 // coerce-to logic, copy the source value into a temp alloca the size
2423 // of the destination type to allow loading all of it. The bits past
2424 // the source value are left undef.
2425 if (SrcSize < DstSize) {
2426 llvm::AllocaInst *TempAlloca
2427 = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
2428 Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
2429 SrcPtr = TempAlloca;
2430 } else {
2431 SrcPtr = Builder.CreateBitCast(SrcPtr,
2432 llvm::PointerType::getUnqual(STy));
2433 }
2434
Chris Lattnerceddafb2010-07-05 20:41:41 +00002435 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2436 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerff941a62010-07-28 18:24:28 +00002437 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
2438 // We don't know what we're loading from.
2439 LI->setAlignment(1);
2440 Args.push_back(LI);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002441
2442 // Validate argument match.
2443 checkArgMatches(LI, IRArgNo, IRFuncTy);
Chris Lattner15ec3612010-06-29 00:06:42 +00002444 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00002445 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00002446 // In the simple case, just pass the coerced loaded value.
2447 Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(),
2448 *this));
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002449
2450 // Validate argument match.
2451 checkArgMatches(Args.back(), IRArgNo, IRFuncTy);
Chris Lattner3dd716c2010-06-28 23:44:11 +00002452 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002453
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002454 break;
2455 }
2456
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002457 case ABIArgInfo::Expand:
Chris Lattnerd59d8672011-07-12 06:29:11 +00002458 ExpandTypeToArgs(I->Ty, RV, Args, IRFuncTy);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002459 IRArgNo = Args.size();
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002460 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00002461 }
2462 }
Mike Stump11289f42009-09-09 15:08:12 +00002463
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002464 if (!CallArgs.getCleanupsToDeactivate().empty())
2465 deactivateArgCleanupsBeforeCall(*this, CallArgs);
2466
Chris Lattner4ca97c32009-06-13 00:26:38 +00002467 // If the callee is a bitcast of a function to a varargs pointer to function
2468 // type, check to see if we can remove the bitcast. This handles some cases
2469 // with unprototyped functions.
2470 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
2471 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002472 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
2473 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00002474 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00002475 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00002476
Chris Lattner4ca97c32009-06-13 00:26:38 +00002477 if (CE->getOpcode() == llvm::Instruction::BitCast &&
2478 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00002479 ActualFT->getNumParams() == CurFT->getNumParams() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00002480 ActualFT->getNumParams() == Args.size() &&
2481 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00002482 bool ArgsMatch = true;
2483 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
2484 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
2485 ArgsMatch = false;
2486 break;
2487 }
Mike Stump11289f42009-09-09 15:08:12 +00002488
Chris Lattner4ca97c32009-06-13 00:26:38 +00002489 // Strip the cast if we can get away with it. This is a nice cleanup,
2490 // but also allows us to inline the function at -O0 if it is marked
2491 // always_inline.
2492 if (ArgsMatch)
2493 Callee = CalleeF;
2494 }
2495 }
Mike Stump11289f42009-09-09 15:08:12 +00002496
Daniel Dunbar0ef34792009-09-12 00:59:20 +00002497 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00002498 CodeGen::AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00002499 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
2500 CallingConv, true);
Bill Wendling3087d022012-12-07 23:17:26 +00002501 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00002502 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00002503
John McCallbd309292010-07-06 01:34:17 +00002504 llvm::BasicBlock *InvokeDest = 0;
Bill Wendling5e85be42012-12-30 10:32:17 +00002505 if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
2506 llvm::Attribute::NoUnwind))
John McCallbd309292010-07-06 01:34:17 +00002507 InvokeDest = getInvokeDest();
2508
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002509 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00002510 if (!InvokeDest) {
Jay Foad5bd375a2011-07-15 08:37:34 +00002511 CS = Builder.CreateCall(Callee, Args);
Daniel Dunbar12347492009-02-23 17:26:39 +00002512 } else {
2513 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Jay Foad5bd375a2011-07-15 08:37:34 +00002514 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, Args);
Daniel Dunbar12347492009-02-23 17:26:39 +00002515 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00002516 }
Chris Lattnere70a0072010-06-29 16:40:28 +00002517 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00002518 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00002519
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002520 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00002521 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002522
Dan Gohman515a60d2012-02-16 00:57:37 +00002523 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2524 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002525 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00002526 AddObjCARCExceptionMetadata(CS.getInstruction());
2527
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002528 // If the call doesn't return, finish the basic block and clear the
2529 // insertion point; this allows the rest of IRgen to discard
2530 // unreachable code.
2531 if (CS.doesNotReturn()) {
2532 Builder.CreateUnreachable();
2533 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00002534
Mike Stump18bb9282009-05-16 07:57:57 +00002535 // FIXME: For now, emit a dummy basic block because expr emitters in
2536 // generally are not ready to handle emitting expressions at unreachable
2537 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002538 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00002539
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002540 // Return a reasonable RValue.
2541 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00002542 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002543
2544 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00002545 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00002546 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002547
John McCall31168b02011-06-15 23:02:42 +00002548 // Emit any writebacks immediately. Arguably this should happen
2549 // after any return-value munging.
2550 if (CallArgs.hasWritebacks())
2551 emitWritebacks(*this, CallArgs);
2552
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002553 switch (RetAI.getKind()) {
John McCall47fb9502013-03-07 21:37:08 +00002554 case ABIArgInfo::Indirect:
2555 return convertTempToRValue(Args[0], RetTy);
Daniel Dunbard3674e62008-09-11 01:48:57 +00002556
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002557 case ABIArgInfo::Ignore:
Daniel Dunbar01362822009-02-03 06:30:17 +00002558 // If we are ignoring an argument that had a result, make sure to
2559 // construct the appropriate return value for our caller.
Daniel Dunbarc79407f2009-02-05 07:09:07 +00002560 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002561
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002562 case ABIArgInfo::Extend:
2563 case ABIArgInfo::Direct: {
Chris Lattner3517f142011-07-13 03:59:32 +00002564 llvm::Type *RetIRTy = ConvertType(RetTy);
2565 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
John McCall47fb9502013-03-07 21:37:08 +00002566 switch (getEvaluationKind(RetTy)) {
2567 case TEK_Complex: {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002568 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
2569 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
2570 return RValue::getComplex(std::make_pair(Real, Imag));
2571 }
John McCall47fb9502013-03-07 21:37:08 +00002572 case TEK_Aggregate: {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002573 llvm::Value *DestPtr = ReturnValue.getValue();
2574 bool DestIsVolatile = ReturnValue.isVolatile();
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002575
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002576 if (!DestPtr) {
2577 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
2578 DestIsVolatile = false;
2579 }
Eli Friedmanaf9b3252011-05-17 21:08:01 +00002580 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002581 return RValue::getAggregate(DestPtr);
2582 }
John McCall47fb9502013-03-07 21:37:08 +00002583 case TEK_Scalar: {
2584 // If the argument doesn't match, perform a bitcast to coerce it. This
2585 // can happen due to trivial type mismatches.
2586 llvm::Value *V = CI;
2587 if (V->getType() != RetIRTy)
2588 V = Builder.CreateBitCast(V, RetIRTy);
2589 return RValue::get(V);
2590 }
2591 }
2592 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002593 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002594
Anders Carlsson17490832009-12-24 20:40:36 +00002595 llvm::Value *DestPtr = ReturnValue.getValue();
2596 bool DestIsVolatile = ReturnValue.isVolatile();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002597
Anders Carlsson17490832009-12-24 20:40:36 +00002598 if (!DestPtr) {
Daniel Dunbara7566f12010-02-09 02:48:28 +00002599 DestPtr = CreateMemTemp(RetTy, "coerce");
Anders Carlsson17490832009-12-24 20:40:36 +00002600 DestIsVolatile = false;
2601 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002602
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002603 // If the value is offset in memory, apply the offset now.
2604 llvm::Value *StorePtr = DestPtr;
2605 if (unsigned Offs = RetAI.getDirectOffset()) {
2606 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
2607 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002608 StorePtr = Builder.CreateBitCast(StorePtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002609 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
2610 }
2611 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002612
John McCall47fb9502013-03-07 21:37:08 +00002613 return convertTempToRValue(DestPtr, RetTy);
Daniel Dunbar573884e2008-09-10 07:04:09 +00002614 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00002615
Daniel Dunbard3674e62008-09-11 01:48:57 +00002616 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002617 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar613855c2008-09-09 23:27:19 +00002618 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002619
David Blaikie83d382b2011-09-23 05:06:16 +00002620 llvm_unreachable("Unhandled ABIArgInfo::Kind");
Daniel Dunbar613855c2008-09-09 23:27:19 +00002621}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00002622
2623/* VarArg handling */
2624
2625llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
2626 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
2627}