blob: 32dbfab07d45446af0365dad8bdd82ff431057ff [file] [log] [blame]
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001//===--- CGCall.cpp - Encapsulate calling convention details ----*- C++ -*-===//
Daniel Dunbar0dbe2272008-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 Lattnerce933992010-06-29 16:40:28 +000016#include "ABIInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "CGCXXABI.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000018#include "CodeGenFunction.h"
Daniel Dunbarb7688072008-09-10 00:41:16 +000019#include "CodeGenModule.h"
John McCallde5d3c72012-02-17 03:33:10 +000020#include "TargetInfo.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000021#include "clang/AST/Decl.h"
Anders Carlssonf6f8ae52009-04-03 22:48:58 +000022#include "clang/AST/DeclCXX.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000023#include "clang/AST/DeclObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "clang/Basic/TargetInfo.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000025#include "clang/Frontend/CodeGenOptions.h"
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +000026#include "llvm/ADT/StringExtras.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000027#include "llvm/IR/Attributes.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/InlineAsm.h"
Bill Wendlingc0dcc2d2013-02-15 21:30:01 +000030#include "llvm/MC/SubtargetFeature.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "llvm/Support/CallSite.h"
Eli Friedman97cb5a42011-06-15 22:09:18 +000032#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000033using namespace clang;
34using namespace CodeGen;
35
36/***/
37
John McCall04a67a62010-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 Gregorf813a2c2010-05-18 16:57:00 +000043 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Anton Korobeynikov414d8962011-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 Benyei38980082012-12-25 08:53:55 +000046 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Dawn Perchik52fc3142010-09-03 01:29:35 +000047 // TODO: add support for CC_X86Pascal to llvm
John McCall04a67a62010-02-05 21:31:56 +000048 }
49}
50
John McCall0b0ef0a2010-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 McCallead608a2010-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 Dunbar45c25ba2008-09-10 04:01:49 +000057}
58
John McCall0b0ef0a2010-02-24 07:14:12 +000059/// Returns the canonical formal type of the given C++ method.
John McCallead608a2010-02-26 00:48:12 +000060static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
61 return MD->getType()->getCanonicalTypeUnqualified()
62 .getAs<FunctionProtoType>();
John McCall0b0ef0a2010-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 McCallead608a2010-02-26 00:48:12 +000069static CanQualType GetReturnType(QualType RetTy) {
70 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall0b0ef0a2010-02-24 07:14:12 +000071}
72
John McCall0f3d0972012-07-07 06:41:13 +000073/// Arrange the argument and result information for a value of the given
74/// unprototyped freestanding function type.
John McCall0b0ef0a2010-02-24 07:14:12 +000075const CGFunctionInfo &
John McCall0f3d0972012-07-07 06:41:13 +000076CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCallde5d3c72012-02-17 03:33:10 +000077 // When translating an unprototyped function type, always use a
78 // variadic type.
John McCall0f3d0972012-07-07 06:41:13 +000079 return arrangeLLVMFunctionInfo(FTNP->getResultType().getUnqualifiedType(),
Dmitri Gribenko55431692013-05-05 00:41:58 +000080 None, FTNP->getExtInfo(), RequiredArgs(0));
John McCall0b0ef0a2010-02-24 07:14:12 +000081}
82
John McCall0f3d0972012-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 Dunbar541b63b2009-02-02 23:23:47 +000091 // FIXME: Kill copy.
Daniel Dunbar45c25ba2008-09-10 04:01:49 +000092 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
John McCall0f3d0972012-07-07 06:41:13 +000093 prefix.push_back(FTP->getArgType(i));
John McCallde5d3c72012-02-17 03:33:10 +000094 CanQualType resultType = FTP->getResultType().getUnqualifiedType();
John McCall0f3d0972012-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 Iskhodzhanov8f88a1d2012-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 McCall0f3d0972012-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 Iskhodzhanov8f88a1d2012-07-12 09:50:54 +0000123 adjustCXXMethodInfo(CGT, extInfo, FTP->isVariadic());
John McCall0f3d0972012-07-07 06:41:13 +0000124 return arrangeLLVMFunctionInfo(CGT, prefix, FTP, extInfo);
John McCall0b0ef0a2010-02-24 07:14:12 +0000125}
126
John McCallde5d3c72012-02-17 03:33:10 +0000127/// Arrange the argument and result information for a value of the
John McCall0f3d0972012-07-07 06:41:13 +0000128/// given freestanding function type.
John McCall0b0ef0a2010-02-24 07:14:12 +0000129const CGFunctionInfo &
John McCall0f3d0972012-07-07 06:41:13 +0000130CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
John McCallde5d3c72012-02-17 03:33:10 +0000131 SmallVector<CanQualType, 16> argTypes;
John McCall0f3d0972012-07-07 06:41:13 +0000132 return ::arrangeFreeFunctionType(*this, argTypes, FTP);
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000133}
134
John McCall04a67a62010-02-05 21:31:56 +0000135static CallingConv getCallingConventionForDecl(const Decl *D) {
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000136 // Set the appropriate calling convention for the Function.
137 if (D->hasAttr<StdCallAttr>())
John McCall04a67a62010-02-05 21:31:56 +0000138 return CC_X86StdCall;
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000139
140 if (D->hasAttr<FastCallAttr>())
John McCall04a67a62010-02-05 21:31:56 +0000141 return CC_X86FastCall;
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000142
Douglas Gregorf813a2c2010-05-18 16:57:00 +0000143 if (D->hasAttr<ThisCallAttr>())
144 return CC_X86ThisCall;
145
Dawn Perchik52fc3142010-09-03 01:29:35 +0000146 if (D->hasAttr<PascalAttr>())
147 return CC_X86Pascal;
148
Anton Korobeynikov414d8962011-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 Schuff263366f2012-10-16 22:30:41 +0000152 if (D->hasAttr<PnaclCallAttr>())
153 return CC_PnaclCall;
154
Guy Benyei38980082012-12-25 08:53:55 +0000155 if (D->hasAttr<IntelOclBiccAttr>())
156 return CC_IntelOclBicc;
157
John McCall04a67a62010-02-05 21:31:56 +0000158 return CC_C;
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000159}
160
John McCallde5d3c72012-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 Iskhodzhanov8f189a92013-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 McCallde5d3c72012-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 McCall0b0ef0a2010-02-24 07:14:12 +0000171
Anders Carlsson375c31c2009-10-03 19:43:08 +0000172 // Add the 'this' pointer.
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000173 if (RD)
174 argTypes.push_back(GetThisType(Context, RD));
175 else
176 argTypes.push_back(Context.VoidPtrTy);
John McCall0b0ef0a2010-02-24 07:14:12 +0000177
John McCall0f3d0972012-07-07 06:41:13 +0000178 return ::arrangeCXXMethodType(*this, argTypes,
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000179 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
Anders Carlsson375c31c2009-10-03 19:43:08 +0000180}
181
John McCallde5d3c72012-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 McCallfc400282010-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 McCallde5d3c72012-02-17 03:33:10 +0000191 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000192
John McCallde5d3c72012-02-17 03:33:10 +0000193 if (MD->isInstance()) {
194 // The abstract case is perfectly fine.
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000195 const CXXRecordDecl *ThisType =
196 CGM.getCXXABI().getThisArgumentTypeForMethod(MD);
197 return arrangeCXXMethodType(ThisType, prototype.getTypePtr());
John McCallde5d3c72012-02-17 03:33:10 +0000198 }
199
John McCall0f3d0972012-07-07 06:41:13 +0000200 return arrangeFreeFunctionType(prototype);
Anders Carlssonf6f8ae52009-04-03 22:48:58 +0000201}
202
John McCallde5d3c72012-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 Lin3b50e8d2013-06-30 20:40:16 +0000210
211 GlobalDecl GD(D, ctorKind);
212 CanQualType resultType =
213 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000214
John McCallde5d3c72012-02-17 03:33:10 +0000215 TheCXXABI.BuildConstructorSignature(D, ctorKind, resultType, argTypes);
John McCall0b0ef0a2010-02-24 07:14:12 +0000216
John McCall4c40d982010-08-31 07:33:07 +0000217 CanQual<FunctionProtoType> FTP = GetFormalType(D);
218
John McCallde5d3c72012-02-17 03:33:10 +0000219 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, argTypes.size());
220
John McCall4c40d982010-08-31 07:33:07 +0000221 // Add the formal parameters.
222 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
John McCallde5d3c72012-02-17 03:33:10 +0000223 argTypes.push_back(FTP->getArgType(i));
John McCall4c40d982010-08-31 07:33:07 +0000224
John McCall0f3d0972012-07-07 06:41:13 +0000225 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +0000226 adjustCXXMethodInfo(*this, extInfo, FTP->isVariadic());
John McCall0f3d0972012-07-07 06:41:13 +0000227 return arrangeLLVMFunctionInfo(resultType, argTypes, extInfo, required);
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000228}
229
John McCallde5d3c72012-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 Lin3b50e8d2013-06-30 20:40:16 +0000238
239 GlobalDecl GD(D, dtorKind);
240 CanQualType resultType =
241 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
John McCall0b0ef0a2010-02-24 07:14:12 +0000242
John McCallde5d3c72012-02-17 03:33:10 +0000243 TheCXXABI.BuildDestructorSignature(D, dtorKind, resultType, argTypes);
John McCall4c40d982010-08-31 07:33:07 +0000244
245 CanQual<FunctionProtoType> FTP = GetFormalType(D);
246 assert(FTP->getNumArgs() == 0 && "dtor with formal parameters");
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +0000247 assert(FTP->isVariadic() == 0 && "dtor with formal parameters");
John McCall4c40d982010-08-31 07:33:07 +0000248
John McCall0f3d0972012-07-07 06:41:13 +0000249 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +0000250 adjustCXXMethodInfo(*this, extInfo, false);
John McCall0f3d0972012-07-07 06:41:13 +0000251 return arrangeLLVMFunctionInfo(resultType, argTypes, extInfo,
252 RequiredArgs::All);
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000253}
254
John McCallde5d3c72012-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 Lattner3eb67ca2009-05-12 20:27:19 +0000259 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonf6f8ae52009-04-03 22:48:58 +0000260 if (MD->isInstance())
John McCallde5d3c72012-02-17 03:33:10 +0000261 return arrangeCXXMethodDeclaration(MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000262
John McCallead608a2010-02-26 00:48:12 +0000263 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCallde5d3c72012-02-17 03:33:10 +0000264
John McCallead608a2010-02-26 00:48:12 +0000265 assert(isa<FunctionType>(FTy));
John McCallde5d3c72012-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 Gribenko55431692013-05-05 00:41:58 +0000271 return arrangeLLVMFunctionInfo(noProto->getResultType(), None,
272 noProto->getExtInfo(), RequiredArgs::All);
John McCallde5d3c72012-02-17 03:33:10 +0000273 }
274
John McCallead608a2010-02-26 00:48:12 +0000275 assert(isa<FunctionProtoType>(FTy));
John McCall0f3d0972012-07-07 06:41:13 +0000276 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>());
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000277}
278
John McCallde5d3c72012-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 Dunbar541b63b2009-02-02 23:23:47 +0000300 // FIXME: Kill copy?
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +0000301 for (ObjCMethodDecl::param_const_iterator i = MD->param_begin(),
John McCall0b0ef0a2010-02-24 07:14:12 +0000302 e = MD->param_end(); i != e; ++i) {
John McCallde5d3c72012-02-17 03:33:10 +0000303 argTys.push_back(Context.getCanonicalParamType((*i)->getType()));
John McCall0b0ef0a2010-02-24 07:14:12 +0000304 }
John McCallf85e1932011-06-15 23:02:42 +0000305
306 FunctionType::ExtInfo einfo;
307 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD));
308
David Blaikie4e4d0842012-03-11 07:00:24 +0000309 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +0000310 MD->hasAttr<NSReturnsRetainedAttr>())
311 einfo = einfo.withProducesResult(true);
312
John McCallde5d3c72012-02-17 03:33:10 +0000313 RequiredArgs required =
314 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
315
John McCall0f3d0972012-07-07 06:41:13 +0000316 return arrangeLLVMFunctionInfo(GetReturnType(MD->getResultType()), argTys,
317 einfo, required);
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000318}
319
John McCallde5d3c72012-02-17 03:33:10 +0000320const CGFunctionInfo &
321CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000322 // FIXME: Do we need to handle ObjCMethodDecl?
323 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000324
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000325 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
John McCallde5d3c72012-02-17 03:33:10 +0000326 return arrangeCXXConstructorDeclaration(CD, GD.getCtorType());
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000327
328 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
John McCallde5d3c72012-02-17 03:33:10 +0000329 return arrangeCXXDestructor(DD, GD.getDtorType());
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000330
John McCallde5d3c72012-02-17 03:33:10 +0000331 return arrangeFunctionDeclaration(FD);
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000332}
333
John McCalle56bb362012-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 McCallde5d3c72012-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 McCall0f3d0972012-07-07 06:41:13 +0000370CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
371 const FunctionType *fnType) {
John McCalle56bb362012-12-07 07:03:17 +0000372 return arrangeFreeFunctionLikeCall(*this, args, fnType, 0);
373}
John McCallde5d3c72012-02-17 03:33:10 +0000374
John McCalle56bb362012-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 McCallde5d3c72012-02-17 03:33:10 +0000381}
382
383const CGFunctionInfo &
John McCall0f3d0972012-07-07 06:41:13 +0000384CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
385 const CallArgList &args,
386 FunctionType::ExtInfo info,
387 RequiredArgs required) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000388 // FIXME: Kill copy.
John McCallde5d3c72012-02-17 03:33:10 +0000389 SmallVector<CanQualType, 16> argTypes;
390 for (CallArgList::const_iterator i = args.begin(), e = args.end();
Daniel Dunbar725ad312009-01-31 02:19:00 +0000391 i != e; ++i)
John McCallde5d3c72012-02-17 03:33:10 +0000392 argTypes.push_back(Context.getCanonicalParamType(i->Ty));
John McCall0f3d0972012-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 Iskhodzhanov8f88a1d2012-07-12 09:50:54 +0000409 adjustCXXMethodInfo(*this, info, FPT->isVariadic());
John McCall0f3d0972012-07-07 06:41:13 +0000410 return arrangeLLVMFunctionInfo(GetReturnType(FPT->getResultType()),
411 argTypes, info, required);
Daniel Dunbar725ad312009-01-31 02:19:00 +0000412}
413
John McCallde5d3c72012-02-17 03:33:10 +0000414const CGFunctionInfo &
415CodeGenTypes::arrangeFunctionDeclaration(QualType resultType,
416 const FunctionArgList &args,
417 const FunctionType::ExtInfo &info,
418 bool isVariadic) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000419 // FIXME: Kill copy.
John McCallde5d3c72012-02-17 03:33:10 +0000420 SmallVector<CanQualType, 16> argTypes;
421 for (FunctionArgList::const_iterator i = args.begin(), e = args.end();
Daniel Dunbarbb36d332009-02-02 21:43:58 +0000422 i != e; ++i)
John McCallde5d3c72012-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 McCall0f3d0972012-07-07 06:41:13 +0000427 return arrangeLLVMFunctionInfo(GetReturnType(resultType), argTypes, info,
428 required);
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000429}
430
John McCallde5d3c72012-02-17 03:33:10 +0000431const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Dmitri Gribenko55431692013-05-05 00:41:58 +0000432 return arrangeLLVMFunctionInfo(getContext().VoidTy, None,
John McCall0f3d0972012-07-07 06:41:13 +0000433 FunctionType::ExtInfo(), RequiredArgs::All);
John McCalld26bc762011-03-09 04:27:21 +0000434}
435
John McCallde5d3c72012-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 McCall0f3d0972012-07-07 06:41:13 +0000440CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
441 ArrayRef<CanQualType> argTypes,
442 FunctionType::ExtInfo info,
443 RequiredArgs required) {
John McCallead608a2010-02-26 00:48:12 +0000444#ifndef NDEBUG
John McCallde5d3c72012-02-17 03:33:10 +0000445 for (ArrayRef<CanQualType>::const_iterator
446 I = argTypes.begin(), E = argTypes.end(); I != E; ++I)
John McCallead608a2010-02-26 00:48:12 +0000447 assert(I->isCanonicalAsParam());
448#endif
449
John McCallde5d3c72012-02-17 03:33:10 +0000450 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
John McCall04a67a62010-02-05 21:31:56 +0000451
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000452 // Lookup or create unique function info.
453 llvm::FoldingSetNodeID ID;
John McCallde5d3c72012-02-17 03:33:10 +0000454 CGFunctionInfo::Profile(ID, info, required, resultType, argTypes);
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000455
John McCallde5d3c72012-02-17 03:33:10 +0000456 void *insertPos = 0;
457 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000458 if (FI)
459 return *FI;
460
John McCallde5d3c72012-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 Dunbar88c2fa92009-02-03 05:31:23 +0000464
John McCallde5d3c72012-02-17 03:33:10 +0000465 bool inserted = FunctionsBeingProcessed.insert(FI); (void)inserted;
466 assert(inserted && "Recursively being processed?");
Chris Lattner71305cc2011-07-15 05:16:14 +0000467
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000468 // Compute ABI information.
Chris Lattneree5dcd02010-07-29 02:31:05 +0000469 getABIInfo().computeInfo(*FI);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000470
Chris Lattner800588f2010-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 McCallde5d3c72012-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. Spencer9cac4942010-10-19 06:39:39 +0000477
Chris Lattner800588f2010-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 Lattner9cbe4f02011-07-09 17:41:47 +0000481 I->info.setCoerceToType(ConvertType(I->type));
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000482
John McCallde5d3c72012-02-17 03:33:10 +0000483 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
484 assert(erased && "Not in set?");
Chris Lattnerd26c0712011-07-15 06:41:05 +0000485
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000486 return *FI;
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000487}
488
John McCallde5d3c72012-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 Dunbar88c2fa92009-02-03 05:31:23 +0000510}
511
512/***/
513
John McCall42e06112011-05-15 02:19:42 +0000514void CodeGenTypes::GetExpandedTypes(QualType type,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000515 SmallVectorImpl<llvm::Type*> &expandedTypes) {
Bob Wilson194f06a2011-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 Korobeynikoveaf856d2012-04-13 11:22:00 +0000520 } else if (const RecordType *RT = type->getAs<RecordType>()) {
Bob Wilson194f06a2011-08-03 05:58:22 +0000521 const RecordDecl *RD = RT->getDecl();
522 assert(!RD->hasFlexibleArrayMember() &&
523 "Cannot expand structure with flexible array.");
Anton Korobeynikoveaf856d2012-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 Blaikie581deb32012-06-06 20:45:41 +0000532 const FieldDecl *FD = *i;
Anton Korobeynikoveaf856d2012-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 Blaikie581deb32012-06-06 20:45:41 +0000546 assert(!i->isBitField() &&
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000547 "Cannot expand structure with bit-field members.");
David Blaikie581deb32012-06-06 20:45:41 +0000548 GetExpandedTypes(i->getType(), expandedTypes);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000549 }
Bob Wilson194f06a2011-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 Dunbar56273772008-09-17 00:51:38 +0000557}
558
Mike Stump1eb44332009-09-09 15:08:12 +0000559llvm::Function::arg_iterator
Daniel Dunbar56273772008-09-17 00:51:38 +0000560CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
561 llvm::Function::arg_iterator AI) {
Mike Stump1eb44332009-09-09 15:08:12 +0000562 assert(LV.isSimple() &&
563 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar56273772008-09-17 00:51:38 +0000564
Bob Wilson194f06a2011-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 Friedman377ecc72012-04-16 03:54:45 +0000569 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, Elt);
Bob Wilson194f06a2011-08-03 05:58:22 +0000570 LValue LV = MakeAddrLValue(EltAddr, EltTy);
571 AI = ExpandTypeFromArgs(EltTy, LV, AI);
Daniel Dunbar56273772008-09-17 00:51:38 +0000572 }
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000573 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilson194f06a2011-08-03 05:58:22 +0000574 RecordDecl *RD = RT->getDecl();
Anton Korobeynikoveaf856d2012-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 Wilson194f06a2011-08-03 05:58:22 +0000580
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000581 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
582 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +0000583 const FieldDecl *FD = *i;
Anton Korobeynikoveaf856d2012-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 Friedman377ecc72012-04-16 03:54:45 +0000594 LValue SubLV = EmitLValueForField(LV, LargestFD);
595 AI = ExpandTypeFromArgs(LargestFD->getType(), SubLV, AI);
Anton Korobeynikoveaf856d2012-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 Blaikie581deb32012-06-06 20:45:41 +0000600 FieldDecl *FD = *i;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000601 QualType FT = FD->getType();
602
603 // FIXME: What are the right qualifiers here?
Eli Friedman377ecc72012-04-16 03:54:45 +0000604 LValue SubLV = EmitLValueForField(LV, FD);
605 AI = ExpandTypeFromArgs(FT, SubLV, AI);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000606 }
Bob Wilson194f06a2011-08-03 05:58:22 +0000607 }
608 } else if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
609 QualType EltTy = CT->getElementType();
Eli Friedman377ecc72012-04-16 03:54:45 +0000610 llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real");
Bob Wilson194f06a2011-08-03 05:58:22 +0000611 EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(RealAddr, EltTy));
Eli Friedman377ecc72012-04-16 03:54:45 +0000612 llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag");
Bob Wilson194f06a2011-08-03 05:58:22 +0000613 EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(ImagAddr, EltTy));
614 } else {
615 EmitStoreThroughLValue(RValue::get(AI), LV);
616 ++AI;
Daniel Dunbar56273772008-09-17 00:51:38 +0000617 }
618
619 return AI;
620}
621
Chris Lattnere7bb7772010-06-27 06:04:18 +0000622/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner08dd2a02010-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 Lattnere7bb7772010-06-27 06:04:18 +0000627EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000628 llvm::StructType *SrcSTy,
Chris Lattnere7bb7772010-06-27 06:04:18 +0000629 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner08dd2a02010-06-27 05:56:15 +0000630 // We can't dive into a zero-element struct.
631 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000632
Chris Lattner2acc6e32011-07-18 04:24:23 +0000633 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000634
Chris Lattner08dd2a02010-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. Spencer9cac4942010-10-19 06:39:39 +0000637 uint64_t FirstEltSize =
Micah Villmow25a6a842012-10-08 16:25:52 +0000638 CGF.CGM.getDataLayout().getTypeAllocSize(FirstElt);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000639 if (FirstEltSize < DstSize &&
Micah Villmow25a6a842012-10-08 16:25:52 +0000640 FirstEltSize < CGF.CGM.getDataLayout().getTypeAllocSize(SrcSTy))
Chris Lattner08dd2a02010-06-27 05:56:15 +0000641 return SrcPtr;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000642
Chris Lattner08dd2a02010-06-27 05:56:15 +0000643 // GEP into the first element.
644 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000645
Chris Lattner08dd2a02010-06-27 05:56:15 +0000646 // If the first element is a struct, recurse.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000647 llvm::Type *SrcTy =
Chris Lattner08dd2a02010-06-27 05:56:15 +0000648 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000649 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattnere7bb7772010-06-27 06:04:18 +0000650 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner08dd2a02010-06-27 05:56:15 +0000651
652 return SrcPtr;
653}
654
Chris Lattner6d11cdb2010-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 Olesen7e9f52f2013-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 Lattner6d11cdb2010-06-27 06:26:04 +0000662static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000663 llvm::Type *Ty,
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000664 CodeGenFunction &CGF) {
665 if (Val->getType() == Ty)
666 return Val;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000667
Chris Lattner6d11cdb2010-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. Spencer9cac4942010-10-19 06:39:39 +0000672
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000673 // Convert the pointer to an integer so we can play with its width.
Chris Lattner77b89b82010-06-27 07:15:29 +0000674 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000675 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000676
Chris Lattner2acc6e32011-07-18 04:24:23 +0000677 llvm::Type *DestIntTy = Ty;
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000678 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner77b89b82010-06-27 07:15:29 +0000679 DestIntTy = CGF.IntPtrTy;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000680
Jakob Stoklund Olesen7e9f52f2013-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. Spencer9cac4942010-10-19 06:39:39 +0000700
Chris Lattner6d11cdb2010-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 Lattner08dd2a02010-06-27 05:56:15 +0000706
707
Daniel Dunbar275e10d2009-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 Lattner2acc6e32011-07-18 04:24:23 +0000715 llvm::Type *Ty,
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000716 CodeGenFunction &CGF) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000717 llvm::Type *SrcTy =
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000718 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000719
Chris Lattner6ae00692010-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. Spencer9cac4942010-10-19 06:39:39 +0000723
Micah Villmow25a6a842012-10-08 16:25:52 +0000724 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000725
Chris Lattner2acc6e32011-07-18 04:24:23 +0000726 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattnere7bb7772010-06-27 06:04:18 +0000727 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner08dd2a02010-06-27 05:56:15 +0000728 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
729 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000730
Micah Villmow25a6a842012-10-08 16:25:52 +0000731 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000732
Chris Lattner6d11cdb2010-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. Spencer9cac4942010-10-19 06:39:39 +0000740
Daniel Dunbarb225be42009-02-03 05:59:18 +0000741 // If load is legal, just bitcast the src pointer.
Daniel Dunbar7ef455b2009-05-13 18:54:26 +0000742 if (SrcSize >= DstSize) {
Mike Stumpf5408fe2009-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 Dunbar7ef455b2009-05-13 18:54:26 +0000746 //
Mike Stumpf5408fe2009-05-16 07:57:57 +0000747 // FIXME: Assert that we aren't truncating non-padding bits when have access
748 // to that information.
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000749 llvm::Value *Casted =
750 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbar386621f2009-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 Dunbar275e10d2009-02-02 19:06:38 +0000755 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000756
Chris Lattner35b21b82010-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 Renf51c61c2012-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 Ren060f34d2012-11-28 22:29:41 +0000763 // FIXME: Use better alignment.
Manman Renf51c61c2012-11-28 22:08:52 +0000764 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
765 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
766 1, false);
Chris Lattner35b21b82010-06-27 01:06:27 +0000767 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000768}
769
Eli Friedmanbadea572011-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 Lattner2acc6e32011-07-18 04:24:23 +0000778 if (llvm::StructType *STy =
Eli Friedmanbadea572011-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 Wendling08212632012-03-16 21:45:12 +0000789 llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
790 if (LowAlignment)
791 SI->setAlignment(1);
Eli Friedmanbadea572011-05-17 21:08:01 +0000792 }
793}
794
Daniel Dunbar275e10d2009-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 Carlssond2490a92009-12-24 20:40:36 +0000802 bool DstIsVolatile,
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000803 CodeGenFunction &CGF) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000804 llvm::Type *SrcTy = Src->getType();
805 llvm::Type *DstTy =
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000806 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattner6ae00692010-06-28 22:51:39 +0000807 if (SrcTy == DstTy) {
808 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
809 return;
810 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000811
Micah Villmow25a6a842012-10-08 16:25:52 +0000812 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000813
Chris Lattner2acc6e32011-07-18 04:24:23 +0000814 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Chris Lattnere7bb7772010-06-27 06:04:18 +0000815 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
816 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
817 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000818
Chris Lattner6d11cdb2010-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. Spencer9cac4942010-10-19 06:39:39 +0000827
Micah Villmow25a6a842012-10-08 16:25:52 +0000828 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000829
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000830 // If store is legal, just bitcast the src pointer.
Daniel Dunbarfdf49862009-06-05 07:58:54 +0000831 if (SrcSize <= DstSize) {
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000832 llvm::Value *Casted =
833 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbar386621f2009-02-07 02:46:03 +0000834 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanbadea572011-05-17 21:08:01 +0000835 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000836 } else {
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000837 // Otherwise do coercion through memory. This is stupid, but
838 // simple.
Daniel Dunbarfdf49862009-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 Dunbar275e10d2009-02-02 19:06:38 +0000846 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
847 CGF.Builder.CreateStore(Src, Tmp);
Manman Renf51c61c2012-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 Ren060f34d2012-11-28 22:29:41 +0000851 // FIXME: Use better alignment.
Manman Renf51c61c2012-11-28 22:08:52 +0000852 CGF.Builder.CreateMemCpy(DstCasted, Casted,
853 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
854 1, false);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000855 }
856}
857
Daniel Dunbar56273772008-09-17 00:51:38 +0000858/***/
859
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000860bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000861 return FI.getReturnInfo().isIndirect();
Daniel Dunbarbb36d332009-02-02 21:43:58 +0000862}
863
Daniel Dunbardacf9dd2010-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 McCall64aa4b32013-04-16 22:48:15 +0000870 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000871 case BuiltinType::Double:
John McCall64aa4b32013-04-16 22:48:15 +0000872 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000873 case BuiltinType::LongDouble:
John McCall64aa4b32013-04-16 22:48:15 +0000874 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000875 }
876 }
877
878 return false;
879}
880
Anders Carlssoneea64802011-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 McCall64aa4b32013-04-16 22:48:15 +0000885 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlssoneea64802011-10-31 16:27:11 +0000886 }
887 }
888
889 return false;
890}
891
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000892llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCallde5d3c72012-02-17 03:33:10 +0000893 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
894 return GetFunctionType(FI);
John McCallc0bf4622010-02-23 00:48:20 +0000895}
896
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000897llvm::FunctionType *
John McCallde5d3c72012-02-17 03:33:10 +0000898CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Chris Lattner71305cc2011-07-15 05:16:14 +0000899
900 bool Inserted = FunctionsBeingProcessed.insert(&FI); (void)Inserted;
901 assert(Inserted && "Recursively being processed?");
902
Chris Lattner5f9e2722011-07-23 10:55:15 +0000903 SmallVector<llvm::Type*, 8> argTypes;
Chris Lattner2acc6e32011-07-18 04:24:23 +0000904 llvm::Type *resultType = 0;
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000905
John McCall42e06112011-05-15 02:19:42 +0000906 const ABIArgInfo &retAI = FI.getReturnInfo();
907 switch (retAI.getKind()) {
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000908 case ABIArgInfo::Expand:
John McCall42e06112011-05-15 02:19:42 +0000909 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000910
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000911 case ABIArgInfo::Extend:
Daniel Dunbar46327aa2009-02-03 06:17:37 +0000912 case ABIArgInfo::Direct:
John McCall42e06112011-05-15 02:19:42 +0000913 resultType = retAI.getCoerceToType();
Daniel Dunbar46327aa2009-02-03 06:17:37 +0000914 break;
915
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000916 case ABIArgInfo::Indirect: {
John McCall42e06112011-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 Lattner2acc6e32011-07-18 04:24:23 +0000921 llvm::Type *ty = ConvertType(ret);
John McCall42e06112011-05-15 02:19:42 +0000922 unsigned addressSpace = Context.getTargetAddressSpace(ret);
923 argTypes.push_back(llvm::PointerType::get(ty, addressSpace));
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000924 break;
925 }
926
Daniel Dunbar11434922009-01-26 21:26:08 +0000927 case ABIArgInfo::Ignore:
John McCall42e06112011-05-15 02:19:42 +0000928 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar11434922009-01-26 21:26:08 +0000929 break;
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000930 }
Mike Stump1eb44332009-09-09 15:08:12 +0000931
John McCalle56bb362012-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 McCall42e06112011-05-15 02:19:42 +0000940 const ABIArgInfo &argAI = it->info;
Mike Stump1eb44332009-09-09 15:08:12 +0000941
Rafael Espindolae4aeeaa2012-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 McCall42e06112011-05-15 02:19:42 +0000946 switch (argAI.getKind()) {
Daniel Dunbar11434922009-01-26 21:26:08 +0000947 case ABIArgInfo::Ignore:
948 break;
949
Chris Lattner800588f2010-07-29 06:26:06 +0000950 case ABIArgInfo::Indirect: {
951 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000952 llvm::Type *LTy = ConvertTypeForMem(it->type);
John McCall42e06112011-05-15 02:19:42 +0000953 argTypes.push_back(LTy->getPointerTo());
Chris Lattner800588f2010-07-29 06:26:06 +0000954 break;
955 }
956
957 case ABIArgInfo::Extend:
Chris Lattner1ed72672010-07-29 06:44:09 +0000958 case ABIArgInfo::Direct: {
Chris Lattnerce700162010-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 Lattner9cbe4f02011-07-09 17:41:47 +0000962 llvm::Type *argType = argAI.getCoerceToType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000963 if (llvm::StructType *st = dyn_cast<llvm::StructType>(argType)) {
John McCall42e06112011-05-15 02:19:42 +0000964 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
965 argTypes.push_back(st->getElementType(i));
Chris Lattnerce700162010-06-28 23:44:11 +0000966 } else {
John McCall42e06112011-05-15 02:19:42 +0000967 argTypes.push_back(argType);
Chris Lattnerce700162010-06-28 23:44:11 +0000968 }
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +0000969 break;
Chris Lattner1ed72672010-07-29 06:44:09 +0000970 }
Mike Stump1eb44332009-09-09 15:08:12 +0000971
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000972 case ABIArgInfo::Expand:
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000973 GetExpandedTypes(it->type, argTypes);
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000974 break;
975 }
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000976 }
977
Chris Lattner71305cc2011-07-15 05:16:14 +0000978 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
979 assert(Erased && "Not in set?");
980
John McCallde5d3c72012-02-17 03:33:10 +0000981 return llvm::FunctionType::get(resultType, argTypes, FI.isVariadic());
Daniel Dunbar3913f182008-09-09 23:48:28 +0000982}
983
Chris Lattner2acc6e32011-07-18 04:24:23 +0000984llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall4c40d982010-08-31 07:33:07 +0000985 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlssonecf282b2009-11-24 05:08:52 +0000986 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000987
Chris Lattnerf742eb02011-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 McCallde5d3c72012-02-17 03:33:10 +0000993 Info = &arrangeCXXDestructor(cast<CXXDestructorDecl>(MD), GD.getDtorType());
Chris Lattnerf742eb02011-07-10 00:18:59 +0000994 else
John McCallde5d3c72012-02-17 03:33:10 +0000995 Info = &arrangeCXXMethodDeclaration(MD);
996 return GetFunctionType(*Info);
Anders Carlssonecf282b2009-11-24 05:08:52 +0000997}
998
Daniel Dunbara0a99e02009-02-02 23:43:58 +0000999void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbar88b53962009-02-02 22:03:45 +00001000 const Decl *TargetDecl,
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001001 AttributeListType &PAL,
Bill Wendling94236e72013-02-22 00:13:35 +00001002 unsigned &CallingConv,
1003 bool AttrOnCallSite) {
Bill Wendling0d583392012-10-15 20:36:26 +00001004 llvm::AttrBuilder FuncAttrs;
1005 llvm::AttrBuilder RetAttrs;
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001006
Daniel Dunbarca6408c2009-09-12 00:59:20 +00001007 CallingConv = FI.getEffectiveCallingConvention();
1008
John McCall04a67a62010-02-05 21:31:56 +00001009 if (FI.isNoReturn())
Bill Wendling72390b32012-12-20 19:27:06 +00001010 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCall04a67a62010-02-05 21:31:56 +00001011
Anton Korobeynikov1102f422009-04-04 00:49:24 +00001012 // FIXME: handle sseregparm someday...
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001013 if (TargetDecl) {
Rafael Espindola67004152011-10-12 19:51:18 +00001014 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +00001015 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001016 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +00001017 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith7586a6e2013-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 McCall9c0c1f32010-07-08 06:48:12 +00001022 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001023 if (FPT && FPT->isNothrow(getContext()))
Bill Wendling72390b32012-12-20 19:27:06 +00001024 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith3c5cd152013-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 Smith7586a6e2013-01-30 05:45:05 +00001029 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCall9c0c1f32010-07-08 06:48:12 +00001030 }
1031
Eric Christopher041087c2011-08-15 22:38:22 +00001032 // 'const' and 'pure' attribute functions are also nounwind.
1033 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling72390b32012-12-20 19:27:06 +00001034 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1035 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopher041087c2011-08-15 22:38:22 +00001036 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling72390b32012-12-20 19:27:06 +00001037 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1038 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopher041087c2011-08-15 22:38:22 +00001039 }
Ryan Flynn76168e22009-08-09 20:07:29 +00001040 if (TargetDecl->hasAttr<MallocAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +00001041 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001042 }
1043
Chandler Carruth2811ccf2009-11-12 17:24:48 +00001044 if (CodeGenOpts.OptimizeSize)
Bill Wendling72390b32012-12-20 19:27:06 +00001045 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
Quentin Colombet90467682012-10-26 00:29:48 +00001046 if (CodeGenOpts.OptimizeSize == 2)
Bill Wendling72390b32012-12-20 19:27:06 +00001047 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
Chandler Carruth2811ccf2009-11-12 17:24:48 +00001048 if (CodeGenOpts.DisableRedZone)
Bill Wendling72390b32012-12-20 19:27:06 +00001049 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruth2811ccf2009-11-12 17:24:48 +00001050 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling72390b32012-12-20 19:27:06 +00001051 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Devang Patel24095da2009-06-04 23:32:02 +00001052
Bill Wendling93e4bff2013-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 Wendlingbe9e8bf2013-02-28 22:49:57 +00001057 } else {
1058 // Attributes that should go on the function, but not the call site.
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +00001059 if (!CodeGenOpts.DisableFPElim) {
Bill Wendling4159f052013-03-13 22:24:33 +00001060 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
1061 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf", "false");
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +00001062 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendling4159f052013-03-13 22:24:33 +00001063 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
1064 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf", "true");
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +00001065 } else {
Bill Wendling4159f052013-03-13 22:24:33 +00001066 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
1067 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf", "true");
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +00001068 }
1069
Bill Wendling4159f052013-03-13 22:24:33 +00001070 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendling52d08fe2013-07-26 21:51:11 +00001071 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendling4159f052013-03-13 22:24:33 +00001072 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendling52d08fe2013-07-26 21:51:11 +00001073 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendling4159f052013-03-13 22:24:33 +00001074 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendling52d08fe2013-07-26 21:51:11 +00001075 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendling4159f052013-03-13 22:24:33 +00001076 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendling52d08fe2013-07-26 21:51:11 +00001077 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendling4159f052013-03-13 22:24:33 +00001078 FuncAttrs.addAttribute("use-soft-float",
Bill Wendling52d08fe2013-07-26 21:51:11 +00001079 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendling45ccf282013-07-22 20:15:41 +00001080 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling8d230b42013-07-12 22:26:07 +00001081 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlingcab4a092013-07-25 00:32:41 +00001082
1083 bool NoFramePointerElimNonLeaf;
1084 if (!CodeGenOpts.DisableFPElim) {
1085 NoFramePointerElimNonLeaf = false;
1086 } else if (CodeGenOpts.OmitLeafFramePointer) {
1087 NoFramePointerElimNonLeaf = true;
1088 } else {
1089 NoFramePointerElimNonLeaf = true;
1090 }
1091
1092 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf",
Bill Wendling52d08fe2013-07-26 21:51:11 +00001093 llvm::toStringRef(NoFramePointerElimNonLeaf));
Bill Wendling1cf9ab82013-08-01 21:41:02 +00001094
1095 if (!CodeGenOpts.StackRealignment)
1096 FuncAttrs.addAttribute("no-realign-stack");
Bill Wendlingc0dcc2d2013-02-15 21:30:01 +00001097 }
1098
Daniel Dunbara0a99e02009-02-02 23:43:58 +00001099 QualType RetTy = FI.getReturnType();
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001100 unsigned Index = 1;
Daniel Dunbarb225be42009-02-03 05:59:18 +00001101 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001102 switch (RetAI.getKind()) {
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00001103 case ABIArgInfo::Extend:
Jakob Stoklund Olesen5baefa82013-05-29 03:57:23 +00001104 if (RetTy->hasSignedIntegerRepresentation())
1105 RetAttrs.addAttribute(llvm::Attribute::SExt);
1106 else if (RetTy->hasUnsignedIntegerRepresentation())
1107 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesen90f9ec02013-06-05 03:00:09 +00001108 // FALL THROUGH
Daniel Dunbar46327aa2009-02-03 06:17:37 +00001109 case ABIArgInfo::Direct:
Jakob Stoklund Olesen90f9ec02013-06-05 03:00:09 +00001110 if (RetAI.getInReg())
1111 RetAttrs.addAttribute(llvm::Attribute::InReg);
1112 break;
Chris Lattner800588f2010-07-29 06:26:06 +00001113 case ABIArgInfo::Ignore:
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001114 break;
1115
Rafael Espindolab48280b2012-07-31 02:44:24 +00001116 case ABIArgInfo::Indirect: {
Bill Wendling0d583392012-10-15 20:36:26 +00001117 llvm::AttrBuilder SRETAttrs;
Bill Wendling72390b32012-12-20 19:27:06 +00001118 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
Rafael Espindolab48280b2012-07-31 02:44:24 +00001119 if (RetAI.getInReg())
Bill Wendling72390b32012-12-20 19:27:06 +00001120 SRETAttrs.addAttribute(llvm::Attribute::InReg);
Bill Wendling603571a2012-10-10 07:36:56 +00001121 PAL.push_back(llvm::
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001122 AttributeSet::get(getLLVMContext(), Index, SRETAttrs));
Rafael Espindolab48280b2012-07-31 02:44:24 +00001123
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001124 ++Index;
Daniel Dunbar0ac86f02009-03-18 19:51:01 +00001125 // sret disables readnone and readonly
Bill Wendling72390b32012-12-20 19:27:06 +00001126 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1127 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001128 break;
Rafael Espindolab48280b2012-07-31 02:44:24 +00001129 }
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001130
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001131 case ABIArgInfo::Expand:
David Blaikieb219cfc2011-09-23 05:06:16 +00001132 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001133 }
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001134
Bill Wendling603571a2012-10-10 07:36:56 +00001135 if (RetAttrs.hasAttributes())
1136 PAL.push_back(llvm::
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001137 AttributeSet::get(getLLVMContext(),
1138 llvm::AttributeSet::ReturnIndex,
1139 RetAttrs));
Anton Korobeynikov1102f422009-04-04 00:49:24 +00001140
Mike Stump1eb44332009-09-09 15:08:12 +00001141 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
Daniel Dunbar88c2fa92009-02-03 05:31:23 +00001142 ie = FI.arg_end(); it != ie; ++it) {
1143 QualType ParamType = it->type;
1144 const ABIArgInfo &AI = it->info;
Bill Wendling0d583392012-10-15 20:36:26 +00001145 llvm::AttrBuilder Attrs;
Anton Korobeynikov1102f422009-04-04 00:49:24 +00001146
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00001147 if (AI.getPaddingType()) {
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001148 if (AI.getPaddingInReg())
1149 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index,
1150 llvm::Attribute::InReg));
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00001151 // Increment Index if there is padding.
1152 ++Index;
1153 }
1154
John McCalld8e10d22010-03-27 00:47:27 +00001155 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1156 // have the corresponding parameter variable. It doesn't make
Daniel Dunbar7f6890e2011-02-10 18:10:07 +00001157 // sense to do it here because parameters are so messed up.
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001158 switch (AI.getKind()) {
Chris Lattner800588f2010-07-29 06:26:06 +00001159 case ABIArgInfo::Extend:
Douglas Gregor575a1c92011-05-20 16:38:50 +00001160 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling72390b32012-12-20 19:27:06 +00001161 Attrs.addAttribute(llvm::Attribute::SExt);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001162 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Bill Wendling72390b32012-12-20 19:27:06 +00001163 Attrs.addAttribute(llvm::Attribute::ZExt);
Chris Lattner800588f2010-07-29 06:26:06 +00001164 // FALL THROUGH
1165 case ABIArgInfo::Direct:
Rafael Espindolab48280b2012-07-31 02:44:24 +00001166 if (AI.getInReg())
Bill Wendling72390b32012-12-20 19:27:06 +00001167 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindolab48280b2012-07-31 02:44:24 +00001168
Chris Lattner800588f2010-07-29 06:26:06 +00001169 // FIXME: handle sseregparm someday...
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001170
Chris Lattner2acc6e32011-07-18 04:24:23 +00001171 if (llvm::StructType *STy =
Rafael Espindolab48280b2012-07-31 02:44:24 +00001172 dyn_cast<llvm::StructType>(AI.getCoerceToType())) {
1173 unsigned Extra = STy->getNumElements()-1; // 1 will be added below.
Bill Wendling603571a2012-10-10 07:36:56 +00001174 if (Attrs.hasAttributes())
Rafael Espindolab48280b2012-07-31 02:44:24 +00001175 for (unsigned I = 0; I < Extra; ++I)
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001176 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index + I,
1177 Attrs));
Rafael Espindolab48280b2012-07-31 02:44:24 +00001178 Index += Extra;
1179 }
Chris Lattner800588f2010-07-29 06:26:06 +00001180 break;
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001181
Daniel Dunbar11e383a2009-02-05 08:00:50 +00001182 case ABIArgInfo::Indirect:
Rafael Espindola0b4cc952012-10-19 05:04:37 +00001183 if (AI.getInReg())
Bill Wendling72390b32012-12-20 19:27:06 +00001184 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola0b4cc952012-10-19 05:04:37 +00001185
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001186 if (AI.getIndirectByVal())
Bill Wendling72390b32012-12-20 19:27:06 +00001187 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001188
Bill Wendling603571a2012-10-10 07:36:56 +00001189 Attrs.addAlignmentAttr(AI.getIndirectAlign());
1190
Daniel Dunbar0ac86f02009-03-18 19:51:01 +00001191 // byval disables readnone and readonly.
Bill Wendling72390b32012-12-20 19:27:06 +00001192 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1193 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001194 break;
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00001195
Daniel Dunbar11434922009-01-26 21:26:08 +00001196 case ABIArgInfo::Ignore:
1197 // Skip increment, no matching LLVM parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00001198 continue;
Daniel Dunbar11434922009-01-26 21:26:08 +00001199
Daniel Dunbar56273772008-09-17 00:51:38 +00001200 case ABIArgInfo::Expand: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001201 SmallVector<llvm::Type*, 8> types;
Mike Stumpf5408fe2009-05-16 07:57:57 +00001202 // FIXME: This is rather inefficient. Do we ever actually need to do
1203 // anything here? The result should be just reconstructed on the other
1204 // side, so extension should be a non-issue.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001205 getTypes().GetExpandedTypes(ParamType, types);
John McCall42e06112011-05-15 02:19:42 +00001206 Index += types.size();
Daniel Dunbar56273772008-09-17 00:51:38 +00001207 continue;
1208 }
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001209 }
Mike Stump1eb44332009-09-09 15:08:12 +00001210
Bill Wendling603571a2012-10-10 07:36:56 +00001211 if (Attrs.hasAttributes())
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001212 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index, Attrs));
Daniel Dunbar56273772008-09-17 00:51:38 +00001213 ++Index;
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001214 }
Bill Wendling603571a2012-10-10 07:36:56 +00001215 if (FuncAttrs.hasAttributes())
Bill Wendling75d37b42012-10-15 07:31:59 +00001216 PAL.push_back(llvm::
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001217 AttributeSet::get(getLLVMContext(),
1218 llvm::AttributeSet::FunctionIndex,
1219 FuncAttrs));
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001220}
1221
John McCalld26bc762011-03-09 04:27:21 +00001222/// An argument came in as a promoted argument; demote it back to its
1223/// declared type.
1224static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1225 const VarDecl *var,
1226 llvm::Value *value) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001227 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalld26bc762011-03-09 04:27:21 +00001228
1229 // This can happen with promotions that actually don't change the
1230 // underlying type, like the enum promotions.
1231 if (value->getType() == varType) return value;
1232
1233 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1234 && "unexpected promotion type");
1235
1236 if (isa<llvm::IntegerType>(varType))
1237 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1238
1239 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1240}
1241
Daniel Dunbar88b53962009-02-02 22:03:45 +00001242void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1243 llvm::Function *Fn,
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001244 const FunctionArgList &Args) {
John McCall0cfeb632009-07-28 01:00:58 +00001245 // If this is an implicit-return-zero function, go ahead and
1246 // initialize the return value. TODO: it might be nice to have
1247 // a more general mechanism for this that didn't require synthesized
1248 // return statements.
John McCallf5ebf9b2013-05-03 07:33:41 +00001249 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCall0cfeb632009-07-28 01:00:58 +00001250 if (FD->hasImplicitReturnZero()) {
1251 QualType RetTy = FD->getResultType().getUnqualifiedType();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001252 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001253 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCall0cfeb632009-07-28 01:00:58 +00001254 Builder.CreateStore(Zero, ReturnValue);
1255 }
1256 }
1257
Mike Stumpf5408fe2009-05-16 07:57:57 +00001258 // FIXME: We no longer need the types from FunctionArgList; lift up and
1259 // simplify.
Daniel Dunbar5251afa2009-02-03 06:02:10 +00001260
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001261 // Emit allocs for param decls. Give the LLVM Argument nodes names.
1262 llvm::Function::arg_iterator AI = Fn->arg_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001263
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001264 // Name the struct return argument.
Daniel Dunbardacf9dd2010-07-14 23:39:36 +00001265 if (CGM.ReturnTypeUsesSRet(FI)) {
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001266 AI->setName("agg.result");
Bill Wendling89530e42013-01-23 06:15:10 +00001267 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1268 AI->getArgNo() + 1,
1269 llvm::Attribute::NoAlias));
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001270 ++AI;
1271 }
Mike Stump1eb44332009-09-09 15:08:12 +00001272
Daniel Dunbar4b5f0a42009-02-04 21:17:21 +00001273 assert(FI.arg_size() == Args.size() &&
1274 "Mismatch between function signature & arguments.");
Devang Patel093ac462011-03-03 20:13:15 +00001275 unsigned ArgNo = 1;
Daniel Dunbarb225be42009-02-03 05:59:18 +00001276 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Devang Patel093ac462011-03-03 20:13:15 +00001277 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
1278 i != e; ++i, ++info_it, ++ArgNo) {
John McCalld26bc762011-03-09 04:27:21 +00001279 const VarDecl *Arg = *i;
Daniel Dunbarb225be42009-02-03 05:59:18 +00001280 QualType Ty = info_it->type;
1281 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001282
John McCalld26bc762011-03-09 04:27:21 +00001283 bool isPromoted =
1284 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1285
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00001286 // Skip the dummy padding argument.
1287 if (ArgI.getPaddingType())
1288 ++AI;
1289
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001290 switch (ArgI.getKind()) {
Daniel Dunbar1f745982009-02-05 09:16:39 +00001291 case ABIArgInfo::Indirect: {
Chris Lattnerce700162010-06-28 23:44:11 +00001292 llvm::Value *V = AI;
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +00001293
John McCall9d232c82013-03-07 21:37:08 +00001294 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +00001295 // Aggregates and complex variables are accessed by reference. All we
1296 // need to do is realign the value, if requested
1297 if (ArgI.getIndirectRealign()) {
1298 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1299
1300 // Copy from the incoming argument pointer to the temporary with the
1301 // appropriate alignment.
1302 //
1303 // FIXME: We should have a common utility for generating an aggregate
1304 // copy.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001305 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyckfe710082011-01-19 01:58:38 +00001306 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumic95a8fc2011-03-10 14:02:21 +00001307 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1308 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1309 Builder.CreateMemCpy(Dst,
1310 Src,
Ken Dyckfe710082011-01-19 01:58:38 +00001311 llvm::ConstantInt::get(IntPtrTy,
1312 Size.getQuantity()),
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +00001313 ArgI.getIndirectAlign(),
1314 false);
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +00001315 V = AlignedTemp;
1316 }
Daniel Dunbar1f745982009-02-05 09:16:39 +00001317 } else {
1318 // Load scalar value from indirect argument.
Ken Dyckfe710082011-01-19 01:58:38 +00001319 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
1320 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty);
John McCalld26bc762011-03-09 04:27:21 +00001321
1322 if (isPromoted)
1323 V = emitArgumentDemotion(*this, Arg, V);
Daniel Dunbar1f745982009-02-05 09:16:39 +00001324 }
Devang Patel093ac462011-03-03 20:13:15 +00001325 EmitParmDecl(*Arg, V, ArgNo);
Daniel Dunbar1f745982009-02-05 09:16:39 +00001326 break;
1327 }
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00001328
1329 case ABIArgInfo::Extend:
Daniel Dunbar46327aa2009-02-03 06:17:37 +00001330 case ABIArgInfo::Direct: {
Akira Hatanaka4ba3fd42012-01-09 19:08:06 +00001331
Chris Lattner800588f2010-07-29 06:26:06 +00001332 // If we have the trivial case, handle it with no muss and fuss.
1333 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner117e3f42010-07-30 04:02:24 +00001334 ArgI.getCoerceToType() == ConvertType(Ty) &&
1335 ArgI.getDirectOffset() == 0) {
Chris Lattner800588f2010-07-29 06:26:06 +00001336 assert(AI != Fn->arg_end() && "Argument mismatch!");
1337 llvm::Value *V = AI;
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001338
Bill Wendlinga6375562012-10-16 05:23:44 +00001339 if (Arg->getType().isRestrictQualified())
Bill Wendling89530e42013-01-23 06:15:10 +00001340 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1341 AI->getArgNo() + 1,
1342 llvm::Attribute::NoAlias));
John McCalld8e10d22010-03-27 00:47:27 +00001343
Chris Lattnerb13eab92011-07-20 06:29:00 +00001344 // Ensure the argument is the correct type.
1345 if (V->getType() != ArgI.getCoerceToType())
1346 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1347
John McCalld26bc762011-03-09 04:27:21 +00001348 if (isPromoted)
1349 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00001350
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00001351 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
1352 if (MD->isVirtual() && Arg == CXXABIThisDecl)
1353 V = CGM.getCXXABI().adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
1354 }
1355
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00001356 // Because of merging of function types from multiple decls it is
1357 // possible for the type of an argument to not match the corresponding
1358 // type in the function type. Since we are codegening the callee
1359 // in here, add a cast to the argument type.
1360 llvm::Type *LTy = ConvertType(Arg->getType());
1361 if (V->getType() != LTy)
1362 V = Builder.CreateBitCast(V, LTy);
1363
Devang Patel093ac462011-03-03 20:13:15 +00001364 EmitParmDecl(*Arg, V, ArgNo);
Chris Lattner800588f2010-07-29 06:26:06 +00001365 break;
Daniel Dunbar8b979d92009-02-10 00:06:49 +00001366 }
Mike Stump1eb44332009-09-09 15:08:12 +00001367
Evgeniy Stepanova6ce20e2012-02-10 09:30:15 +00001368 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001369
Chris Lattnerdeabde22010-07-28 18:24:28 +00001370 // The alignment we need to use is the max of the requested alignment for
1371 // the argument plus the alignment required by our access code below.
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001372 unsigned AlignmentToUse =
Micah Villmow25a6a842012-10-08 16:25:52 +00001373 CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerdeabde22010-07-28 18:24:28 +00001374 AlignmentToUse = std::max(AlignmentToUse,
1375 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001376
Chris Lattnerdeabde22010-07-28 18:24:28 +00001377 Alloca->setAlignment(AlignmentToUse);
Chris Lattner121b3fa2010-07-05 20:21:00 +00001378 llvm::Value *V = Alloca;
Chris Lattner117e3f42010-07-30 04:02:24 +00001379 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001380
Chris Lattner117e3f42010-07-30 04:02:24 +00001381 // If the value is offset in memory, apply the offset now.
1382 if (unsigned Offs = ArgI.getDirectOffset()) {
1383 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1384 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001385 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner117e3f42010-07-30 04:02:24 +00001386 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1387 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001388
Chris Lattner309c59f2010-06-29 00:06:42 +00001389 // If the coerce-to type is a first class aggregate, we flatten it and
1390 // pass the elements. Either way is semantically identical, but fast-isel
1391 // and the optimizer generally likes scalar values better than FCAs.
Evgeniy Stepanova6ce20e2012-02-10 09:30:15 +00001392 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
1393 if (STy && STy->getNumElements() > 1) {
Micah Villmow25a6a842012-10-08 16:25:52 +00001394 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
Evgeniy Stepanova6ce20e2012-02-10 09:30:15 +00001395 llvm::Type *DstTy =
1396 cast<llvm::PointerType>(Ptr->getType())->getElementType();
Micah Villmow25a6a842012-10-08 16:25:52 +00001397 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001398
Evgeniy Stepanova6ce20e2012-02-10 09:30:15 +00001399 if (SrcSize <= DstSize) {
1400 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1401
1402 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1403 assert(AI != Fn->arg_end() && "Argument mismatch!");
1404 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1405 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
1406 Builder.CreateStore(AI++, EltPtr);
1407 }
1408 } else {
1409 llvm::AllocaInst *TempAlloca =
1410 CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1411 TempAlloca->setAlignment(AlignmentToUse);
1412 llvm::Value *TempV = TempAlloca;
1413
1414 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1415 assert(AI != Fn->arg_end() && "Argument mismatch!");
1416 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1417 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(TempV, 0, i);
1418 Builder.CreateStore(AI++, EltPtr);
1419 }
1420
1421 Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
Chris Lattner309c59f2010-06-29 00:06:42 +00001422 }
1423 } else {
1424 // Simple case, just do a coerced store of the argument into the alloca.
1425 assert(AI != Fn->arg_end() && "Argument mismatch!");
Chris Lattner225e2862010-06-29 00:14:52 +00001426 AI->setName(Arg->getName() + ".coerce");
Chris Lattner117e3f42010-07-30 04:02:24 +00001427 CreateCoercedStore(AI++, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner309c59f2010-06-29 00:06:42 +00001428 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001429
1430
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001431 // Match to what EmitParmDecl is expecting for this type.
John McCall9d232c82013-03-07 21:37:08 +00001432 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001433 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty);
John McCalld26bc762011-03-09 04:27:21 +00001434 if (isPromoted)
1435 V = emitArgumentDemotion(*this, Arg, V);
Daniel Dunbar8b29a382009-02-04 07:22:24 +00001436 }
Devang Patel093ac462011-03-03 20:13:15 +00001437 EmitParmDecl(*Arg, V, ArgNo);
Chris Lattnerce700162010-06-28 23:44:11 +00001438 continue; // Skip ++AI increment, already done.
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001439 }
Chris Lattner800588f2010-07-29 06:26:06 +00001440
1441 case ABIArgInfo::Expand: {
1442 // If this structure was expanded into multiple arguments then
1443 // we need to create a temporary and reconstruct it from the
1444 // arguments.
Eli Friedman1bb94a42011-11-03 21:39:02 +00001445 llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
Eli Friedman6da2c712011-12-03 04:14:32 +00001446 CharUnits Align = getContext().getDeclAlign(Arg);
1447 Alloca->setAlignment(Align.getQuantity());
1448 LValue LV = MakeAddrLValue(Alloca, Ty, Align);
Eli Friedman1bb94a42011-11-03 21:39:02 +00001449 llvm::Function::arg_iterator End = ExpandTypeFromArgs(Ty, LV, AI);
1450 EmitParmDecl(*Arg, Alloca, ArgNo);
Chris Lattner800588f2010-07-29 06:26:06 +00001451
1452 // Name the arguments used in expansion and increment AI.
1453 unsigned Index = 0;
1454 for (; AI != End; ++AI, ++Index)
Chris Lattner5f9e2722011-07-23 10:55:15 +00001455 AI->setName(Arg->getName() + "." + Twine(Index));
Chris Lattner800588f2010-07-29 06:26:06 +00001456 continue;
1457 }
1458
1459 case ABIArgInfo::Ignore:
1460 // Initialize the local variable appropriately.
John McCall9d232c82013-03-07 21:37:08 +00001461 if (!hasScalarEvaluationKind(Ty))
Devang Patel093ac462011-03-03 20:13:15 +00001462 EmitParmDecl(*Arg, CreateMemTemp(Ty), ArgNo);
Chris Lattner800588f2010-07-29 06:26:06 +00001463 else
Devang Patel093ac462011-03-03 20:13:15 +00001464 EmitParmDecl(*Arg, llvm::UndefValue::get(ConvertType(Arg->getType())),
1465 ArgNo);
Chris Lattner800588f2010-07-29 06:26:06 +00001466
1467 // Skip increment, no matching LLVM parameter.
1468 continue;
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001469 }
Daniel Dunbar56273772008-09-17 00:51:38 +00001470
1471 ++AI;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001472 }
1473 assert(AI == Fn->arg_end() && "Argument mismatch!");
1474}
1475
John McCall77fe6cd2012-01-29 07:46:59 +00001476static void eraseUnusedBitCasts(llvm::Instruction *insn) {
1477 while (insn->use_empty()) {
1478 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
1479 if (!bitcast) return;
1480
1481 // This is "safe" because we would have used a ConstantExpr otherwise.
1482 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
1483 bitcast->eraseFromParent();
1484 }
1485}
1486
John McCallf85e1932011-06-15 23:02:42 +00001487/// Try to emit a fused autorelease of a return result.
1488static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
1489 llvm::Value *result) {
1490 // We must be immediately followed the cast.
1491 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
1492 if (BB->empty()) return 0;
1493 if (&BB->back() != result) return 0;
1494
Chris Lattner2acc6e32011-07-18 04:24:23 +00001495 llvm::Type *resultType = result->getType();
John McCallf85e1932011-06-15 23:02:42 +00001496
1497 // result is in a BasicBlock and is therefore an Instruction.
1498 llvm::Instruction *generator = cast<llvm::Instruction>(result);
1499
Chris Lattner5f9e2722011-07-23 10:55:15 +00001500 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCallf85e1932011-06-15 23:02:42 +00001501
1502 // Look for:
1503 // %generator = bitcast %type1* %generator2 to %type2*
1504 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
1505 // We would have emitted this as a constant if the operand weren't
1506 // an Instruction.
1507 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
1508
1509 // Require the generator to be immediately followed by the cast.
1510 if (generator->getNextNode() != bitcast)
1511 return 0;
1512
1513 insnsToKill.push_back(bitcast);
1514 }
1515
1516 // Look for:
1517 // %generator = call i8* @objc_retain(i8* %originalResult)
1518 // or
1519 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
1520 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
1521 if (!call) return 0;
1522
1523 bool doRetainAutorelease;
1524
1525 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
1526 doRetainAutorelease = true;
1527 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
1528 .objc_retainAutoreleasedReturnValue) {
1529 doRetainAutorelease = false;
1530
John McCallf9fdcc02012-09-07 23:30:50 +00001531 // If we emitted an assembly marker for this call (and the
1532 // ARCEntrypoints field should have been set if so), go looking
1533 // for that call. If we can't find it, we can't do this
1534 // optimization. But it should always be the immediately previous
1535 // instruction, unless we needed bitcasts around the call.
1536 if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
1537 llvm::Instruction *prev = call->getPrevNode();
1538 assert(prev);
1539 if (isa<llvm::BitCastInst>(prev)) {
1540 prev = prev->getPrevNode();
1541 assert(prev);
1542 }
1543 assert(isa<llvm::CallInst>(prev));
1544 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
1545 CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
1546 insnsToKill.push_back(prev);
1547 }
John McCallf85e1932011-06-15 23:02:42 +00001548 } else {
1549 return 0;
1550 }
1551
1552 result = call->getArgOperand(0);
1553 insnsToKill.push_back(call);
1554
1555 // Keep killing bitcasts, for sanity. Note that we no longer care
1556 // about precise ordering as long as there's exactly one use.
1557 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
1558 if (!bitcast->hasOneUse()) break;
1559 insnsToKill.push_back(bitcast);
1560 result = bitcast->getOperand(0);
1561 }
1562
1563 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001564 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCallf85e1932011-06-15 23:02:42 +00001565 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
1566 (*i)->eraseFromParent();
1567
1568 // Do the fused retain/autorelease if we were asked to.
1569 if (doRetainAutorelease)
1570 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
1571
1572 // Cast back to the result type.
1573 return CGF.Builder.CreateBitCast(result, resultType);
1574}
1575
John McCall77fe6cd2012-01-29 07:46:59 +00001576/// If this is a +1 of the value of an immutable 'self', remove it.
1577static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
1578 llvm::Value *result) {
1579 // This is only applicable to a method with an immutable 'self'.
John McCallbd9b65a2012-07-31 00:33:55 +00001580 const ObjCMethodDecl *method =
1581 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCall77fe6cd2012-01-29 07:46:59 +00001582 if (!method) return 0;
1583 const VarDecl *self = method->getSelfDecl();
1584 if (!self->getType().isConstQualified()) return 0;
1585
1586 // Look for a retain call.
1587 llvm::CallInst *retainCall =
1588 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
1589 if (!retainCall ||
1590 retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
1591 return 0;
1592
1593 // Look for an ordinary load of 'self'.
1594 llvm::Value *retainedValue = retainCall->getArgOperand(0);
1595 llvm::LoadInst *load =
1596 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
1597 if (!load || load->isAtomic() || load->isVolatile() ||
1598 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
1599 return 0;
1600
1601 // Okay! Burn it all down. This relies for correctness on the
1602 // assumption that the retain is emitted as part of the return and
1603 // that thereafter everything is used "linearly".
1604 llvm::Type *resultType = result->getType();
1605 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
1606 assert(retainCall->use_empty());
1607 retainCall->eraseFromParent();
1608 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
1609
1610 return CGF.Builder.CreateBitCast(load, resultType);
1611}
1612
John McCallf85e1932011-06-15 23:02:42 +00001613/// Emit an ARC autorelease of the result of a function.
John McCall77fe6cd2012-01-29 07:46:59 +00001614///
1615/// \return the value to actually return from the function
John McCallf85e1932011-06-15 23:02:42 +00001616static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
1617 llvm::Value *result) {
John McCall77fe6cd2012-01-29 07:46:59 +00001618 // If we're returning 'self', kill the initial retain. This is a
1619 // heuristic attempt to "encourage correctness" in the really unfortunate
1620 // case where we have a return of self during a dealloc and we desperately
1621 // need to avoid the possible autorelease.
1622 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
1623 return self;
1624
John McCallf85e1932011-06-15 23:02:42 +00001625 // At -O0, try to emit a fused retain/autorelease.
1626 if (CGF.shouldUseFusedARCCalls())
1627 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
1628 return fused;
1629
1630 return CGF.EmitARCAutoreleaseReturnValue(result);
1631}
1632
John McCallf48f7962012-01-29 02:35:02 +00001633/// Heuristically search for a dominating store to the return-value slot.
1634static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
1635 // If there are multiple uses of the return-value slot, just check
1636 // for something immediately preceding the IP. Sometimes this can
1637 // happen with how we generate implicit-returns; it can also happen
1638 // with noreturn cleanups.
1639 if (!CGF.ReturnValue->hasOneUse()) {
1640 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
1641 if (IP->empty()) return 0;
1642 llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back());
1643 if (!store) return 0;
1644 if (store->getPointerOperand() != CGF.ReturnValue) return 0;
1645 assert(!store->isAtomic() && !store->isVolatile()); // see below
1646 return store;
1647 }
1648
1649 llvm::StoreInst *store =
1650 dyn_cast<llvm::StoreInst>(CGF.ReturnValue->use_back());
1651 if (!store) return 0;
1652
1653 // These aren't actually possible for non-coerced returns, and we
1654 // only care about non-coerced returns on this code path.
1655 assert(!store->isAtomic() && !store->isVolatile());
1656
1657 // Now do a first-and-dirty dominance check: just walk up the
1658 // single-predecessors chain from the current insertion point.
1659 llvm::BasicBlock *StoreBB = store->getParent();
1660 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
1661 while (IP != StoreBB) {
1662 if (!(IP = IP->getSinglePredecessor()))
1663 return 0;
1664 }
1665
1666 // Okay, the store's basic block dominates the insertion point; we
1667 // can do our thing.
1668 return store;
1669}
1670
Adrian Prantlfa6b0792013-05-02 17:30:20 +00001671void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
1672 bool EmitRetDbgLoc) {
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001673 // Functions with no result always return void.
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001674 if (ReturnValue == 0) {
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001675 Builder.CreateRetVoid();
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001676 return;
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001677 }
Daniel Dunbar21fcc8f2010-06-30 21:27:58 +00001678
Dan Gohman4751a532010-07-20 20:13:52 +00001679 llvm::DebugLoc RetDbgLoc;
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001680 llvm::Value *RV = 0;
1681 QualType RetTy = FI.getReturnType();
1682 const ABIArgInfo &RetAI = FI.getReturnInfo();
1683
1684 switch (RetAI.getKind()) {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001685 case ABIArgInfo::Indirect: {
John McCall9d232c82013-03-07 21:37:08 +00001686 switch (getEvaluationKind(RetTy)) {
1687 case TEK_Complex: {
1688 ComplexPairTy RT =
1689 EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy));
1690 EmitStoreOfComplex(RT,
1691 MakeNaturalAlignAddrLValue(CurFn->arg_begin(), RetTy),
1692 /*isInit*/ true);
1693 break;
1694 }
1695 case TEK_Aggregate:
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001696 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall9d232c82013-03-07 21:37:08 +00001697 break;
1698 case TEK_Scalar:
1699 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
1700 MakeNaturalAlignAddrLValue(CurFn->arg_begin(), RetTy),
1701 /*isInit*/ true);
1702 break;
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001703 }
1704 break;
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001705 }
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001706
1707 case ABIArgInfo::Extend:
Chris Lattner800588f2010-07-29 06:26:06 +00001708 case ABIArgInfo::Direct:
Chris Lattner117e3f42010-07-30 04:02:24 +00001709 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
1710 RetAI.getDirectOffset() == 0) {
Chris Lattner800588f2010-07-29 06:26:06 +00001711 // The internal return value temp always will have pointer-to-return-type
1712 // type, just do a load.
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001713
John McCallf48f7962012-01-29 02:35:02 +00001714 // If there is a dominating store to ReturnValue, we can elide
1715 // the load, zap the store, and usually zap the alloca.
1716 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
Adrian Prantl7c731f52013-05-30 18:12:23 +00001717 // Reuse the debug location from the store unless there is
1718 // cleanup code to be emitted between the store and return
1719 // instruction.
1720 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantlfa6b0792013-05-02 17:30:20 +00001721 RetDbgLoc = SI->getDebugLoc();
Chris Lattner800588f2010-07-29 06:26:06 +00001722 // Get the stored value and nuke the now-dead store.
Chris Lattner800588f2010-07-29 06:26:06 +00001723 RV = SI->getValueOperand();
1724 SI->eraseFromParent();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001725
Chris Lattner800588f2010-07-29 06:26:06 +00001726 // If that was the only use of the return value, nuke it as well now.
1727 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
1728 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
1729 ReturnValue = 0;
1730 }
John McCallf48f7962012-01-29 02:35:02 +00001731
1732 // Otherwise, we have to do a simple load.
1733 } else {
1734 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner35b21b82010-06-27 01:06:27 +00001735 }
Chris Lattner800588f2010-07-29 06:26:06 +00001736 } else {
Chris Lattner117e3f42010-07-30 04:02:24 +00001737 llvm::Value *V = ReturnValue;
1738 // If the value is offset in memory, apply the offset now.
1739 if (unsigned Offs = RetAI.getDirectOffset()) {
1740 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
1741 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001742 V = Builder.CreateBitCast(V,
Chris Lattner117e3f42010-07-30 04:02:24 +00001743 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
1744 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001745
Chris Lattner117e3f42010-07-30 04:02:24 +00001746 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner35b21b82010-06-27 01:06:27 +00001747 }
John McCallf85e1932011-06-15 23:02:42 +00001748
1749 // In ARC, end functions that return a retainable type with a call
1750 // to objc_autoreleaseReturnValue.
1751 if (AutoreleaseResult) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001752 assert(getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001753 !FI.isReturnsRetained() &&
1754 RetTy->isObjCRetainableType());
1755 RV = emitAutoreleaseOfResult(*this, RV);
1756 }
1757
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001758 break;
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001759
Chris Lattner800588f2010-07-29 06:26:06 +00001760 case ABIArgInfo::Ignore:
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001761 break;
1762
1763 case ABIArgInfo::Expand:
David Blaikieb219cfc2011-09-23 05:06:16 +00001764 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001765 }
1766
Daniel Dunbar21fcc8f2010-06-30 21:27:58 +00001767 llvm::Instruction *Ret = RV ? Builder.CreateRet(RV) : Builder.CreateRetVoid();
Devang Pateld3f265d2010-07-21 18:08:50 +00001768 if (!RetDbgLoc.isUnknown())
1769 Ret->setDebugLoc(RetDbgLoc);
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001770}
1771
John McCall413ebdb2011-03-11 20:59:21 +00001772void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
1773 const VarDecl *param) {
John McCall27360712010-05-26 22:34:26 +00001774 // StartFunction converted the ABI-lowered parameter(s) into a
1775 // local alloca. We need to turn that into an r-value suitable
1776 // for EmitCall.
John McCall413ebdb2011-03-11 20:59:21 +00001777 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall27360712010-05-26 22:34:26 +00001778
John McCall413ebdb2011-03-11 20:59:21 +00001779 QualType type = param->getType();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001780
John McCall27360712010-05-26 22:34:26 +00001781 // For the most part, we just need to load the alloca, except:
1782 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall9d232c82013-03-07 21:37:08 +00001783 // 2) references to non-scalars are pointers directly to the aggregate.
1784 // I don't know why references to scalars are different here.
John McCall413ebdb2011-03-11 20:59:21 +00001785 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall9d232c82013-03-07 21:37:08 +00001786 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall413ebdb2011-03-11 20:59:21 +00001787 return args.add(RValue::getAggregate(local), type);
John McCall27360712010-05-26 22:34:26 +00001788
1789 // Locals which are references to scalars are represented
1790 // with allocas holding the pointer.
John McCall413ebdb2011-03-11 20:59:21 +00001791 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall27360712010-05-26 22:34:26 +00001792 }
1793
John McCall9d232c82013-03-07 21:37:08 +00001794 args.add(convertTempToRValue(local, type), type);
John McCall27360712010-05-26 22:34:26 +00001795}
1796
John McCallf85e1932011-06-15 23:02:42 +00001797static bool isProvablyNull(llvm::Value *addr) {
1798 return isa<llvm::ConstantPointerNull>(addr);
1799}
1800
1801static bool isProvablyNonNull(llvm::Value *addr) {
1802 return isa<llvm::AllocaInst>(addr);
1803}
1804
1805/// Emit the actual writing-back of a writeback.
1806static void emitWriteback(CodeGenFunction &CGF,
1807 const CallArgList::Writeback &writeback) {
John McCallb6a60792013-03-23 02:35:54 +00001808 const LValue &srcLV = writeback.Source;
1809 llvm::Value *srcAddr = srcLV.getAddress();
John McCallf85e1932011-06-15 23:02:42 +00001810 assert(!isProvablyNull(srcAddr) &&
1811 "shouldn't have writeback for provably null argument");
1812
1813 llvm::BasicBlock *contBB = 0;
1814
1815 // If the argument wasn't provably non-null, we need to null check
1816 // before doing the store.
1817 bool provablyNonNull = isProvablyNonNull(srcAddr);
1818 if (!provablyNonNull) {
1819 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
1820 contBB = CGF.createBasicBlock("icr.done");
1821
1822 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
1823 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
1824 CGF.EmitBlock(writebackBB);
1825 }
1826
1827 // Load the value to writeback.
1828 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
1829
1830 // Cast it back, in case we're writing an id to a Foo* or something.
1831 value = CGF.Builder.CreateBitCast(value,
1832 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
1833 "icr.writeback-cast");
1834
1835 // Perform the writeback.
John McCallb6a60792013-03-23 02:35:54 +00001836
1837 // If we have a "to use" value, it's something we need to emit a use
1838 // of. This has to be carefully threaded in: if it's done after the
1839 // release it's potentially undefined behavior (and the optimizer
1840 // will ignore it), and if it happens before the retain then the
1841 // optimizer could move the release there.
1842 if (writeback.ToUse) {
1843 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
1844
1845 // Retain the new value. No need to block-copy here: the block's
1846 // being passed up the stack.
1847 value = CGF.EmitARCRetainNonBlock(value);
1848
1849 // Emit the intrinsic use here.
1850 CGF.EmitARCIntrinsicUse(writeback.ToUse);
1851
1852 // Load the old value (primitively).
1853 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV);
1854
1855 // Put the new value in place (primitively).
1856 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
1857
1858 // Release the old value.
1859 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
1860
1861 // Otherwise, we can just do a normal lvalue store.
1862 } else {
1863 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
1864 }
John McCallf85e1932011-06-15 23:02:42 +00001865
1866 // Jump to the continuation block.
1867 if (!provablyNonNull)
1868 CGF.EmitBlock(contBB);
1869}
1870
1871static void emitWritebacks(CodeGenFunction &CGF,
1872 const CallArgList &args) {
1873 for (CallArgList::writeback_iterator
1874 i = args.writeback_begin(), e = args.writeback_end(); i != e; ++i)
1875 emitWriteback(CGF, *i);
1876}
1877
Reid Kleckner9b601952013-06-21 12:45:15 +00001878static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
1879 const CallArgList &CallArgs) {
1880 assert(CGF.getTarget().getCXXABI().isArgumentDestroyedByCallee());
1881 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
1882 CallArgs.getCleanupsToDeactivate();
1883 // Iterate in reverse to increase the likelihood of popping the cleanup.
1884 for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
1885 I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
1886 CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
1887 I->IsActiveIP->eraseFromParent();
1888 }
1889}
1890
John McCallb6a60792013-03-23 02:35:54 +00001891static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
1892 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
1893 if (uop->getOpcode() == UO_AddrOf)
1894 return uop->getSubExpr();
1895 return 0;
1896}
1897
John McCallf85e1932011-06-15 23:02:42 +00001898/// Emit an argument that's being passed call-by-writeback. That is,
1899/// we are passing the address of
1900static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
1901 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCallb6a60792013-03-23 02:35:54 +00001902 LValue srcLV;
1903
1904 // Make an optimistic effort to emit the address as an l-value.
1905 // This can fail if the the argument expression is more complicated.
1906 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
1907 srcLV = CGF.EmitLValue(lvExpr);
1908
1909 // Otherwise, just emit it as a scalar.
1910 } else {
1911 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
1912
1913 QualType srcAddrType =
1914 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
1915 srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
1916 }
1917 llvm::Value *srcAddr = srcLV.getAddress();
John McCallf85e1932011-06-15 23:02:42 +00001918
1919 // The dest and src types don't necessarily match in LLVM terms
1920 // because of the crazy ObjC compatibility rules.
1921
Chris Lattner2acc6e32011-07-18 04:24:23 +00001922 llvm::PointerType *destType =
John McCallf85e1932011-06-15 23:02:42 +00001923 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
1924
1925 // If the address is a constant null, just pass the appropriate null.
1926 if (isProvablyNull(srcAddr)) {
1927 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
1928 CRE->getType());
1929 return;
1930 }
1931
John McCallf85e1932011-06-15 23:02:42 +00001932 // Create the temporary.
1933 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
1934 "icr.temp");
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00001935 // Loading an l-value can introduce a cleanup if the l-value is __weak,
1936 // and that cleanup will be conditional if we can't prove that the l-value
1937 // isn't null, so we need to register a dominating point so that the cleanups
1938 // system will make valid IR.
1939 CodeGenFunction::ConditionalEvaluation condEval(CGF);
1940
John McCallf85e1932011-06-15 23:02:42 +00001941 // Zero-initialize it if we're not doing a copy-initialization.
1942 bool shouldCopy = CRE->shouldCopy();
1943 if (!shouldCopy) {
1944 llvm::Value *null =
1945 llvm::ConstantPointerNull::get(
1946 cast<llvm::PointerType>(destType->getElementType()));
1947 CGF.Builder.CreateStore(null, temp);
1948 }
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00001949
John McCallf85e1932011-06-15 23:02:42 +00001950 llvm::BasicBlock *contBB = 0;
John McCallb6a60792013-03-23 02:35:54 +00001951 llvm::BasicBlock *originBB = 0;
John McCallf85e1932011-06-15 23:02:42 +00001952
1953 // If the address is *not* known to be non-null, we need to switch.
1954 llvm::Value *finalArgument;
1955
1956 bool provablyNonNull = isProvablyNonNull(srcAddr);
1957 if (provablyNonNull) {
1958 finalArgument = temp;
1959 } else {
1960 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
1961
1962 finalArgument = CGF.Builder.CreateSelect(isNull,
1963 llvm::ConstantPointerNull::get(destType),
1964 temp, "icr.argument");
1965
1966 // If we need to copy, then the load has to be conditional, which
1967 // means we need control flow.
1968 if (shouldCopy) {
John McCallb6a60792013-03-23 02:35:54 +00001969 originBB = CGF.Builder.GetInsertBlock();
John McCallf85e1932011-06-15 23:02:42 +00001970 contBB = CGF.createBasicBlock("icr.cont");
1971 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
1972 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
1973 CGF.EmitBlock(copyBB);
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00001974 condEval.begin(CGF);
John McCallf85e1932011-06-15 23:02:42 +00001975 }
1976 }
1977
John McCallb6a60792013-03-23 02:35:54 +00001978 llvm::Value *valueToUse = 0;
1979
John McCallf85e1932011-06-15 23:02:42 +00001980 // Perform a copy if necessary.
1981 if (shouldCopy) {
John McCall545d9962011-06-25 02:11:03 +00001982 RValue srcRV = CGF.EmitLoadOfLValue(srcLV);
John McCallf85e1932011-06-15 23:02:42 +00001983 assert(srcRV.isScalar());
1984
1985 llvm::Value *src = srcRV.getScalarVal();
1986 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
1987 "icr.cast");
1988
1989 // Use an ordinary store, not a store-to-lvalue.
1990 CGF.Builder.CreateStore(src, temp);
John McCallb6a60792013-03-23 02:35:54 +00001991
1992 // If optimization is enabled, and the value was held in a
1993 // __strong variable, we need to tell the optimizer that this
1994 // value has to stay alive until we're doing the store back.
1995 // This is because the temporary is effectively unretained,
1996 // and so otherwise we can violate the high-level semantics.
1997 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
1998 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
1999 valueToUse = src;
2000 }
John McCallf85e1932011-06-15 23:02:42 +00002001 }
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00002002
John McCallf85e1932011-06-15 23:02:42 +00002003 // Finish the control flow if we needed it.
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00002004 if (shouldCopy && !provablyNonNull) {
John McCallb6a60792013-03-23 02:35:54 +00002005 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCallf85e1932011-06-15 23:02:42 +00002006 CGF.EmitBlock(contBB);
John McCallb6a60792013-03-23 02:35:54 +00002007
2008 // Make a phi for the value to intrinsically use.
2009 if (valueToUse) {
2010 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2011 "icr.to-use");
2012 phiToUse->addIncoming(valueToUse, copyBB);
2013 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2014 originBB);
2015 valueToUse = phiToUse;
2016 }
2017
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00002018 condEval.end(CGF);
2019 }
John McCallf85e1932011-06-15 23:02:42 +00002020
John McCallb6a60792013-03-23 02:35:54 +00002021 args.addWriteback(srcLV, temp, valueToUse);
John McCallf85e1932011-06-15 23:02:42 +00002022 args.add(RValue::get(finalArgument), CRE->getType());
2023}
2024
John McCall413ebdb2011-03-11 20:59:21 +00002025void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2026 QualType type) {
John McCallf85e1932011-06-15 23:02:42 +00002027 if (const ObjCIndirectCopyRestoreExpr *CRE
2028 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith7edf9e32012-11-01 22:30:59 +00002029 assert(getLangOpts().ObjCAutoRefCount);
John McCallf85e1932011-06-15 23:02:42 +00002030 assert(getContext().hasSameType(E->getType(), type));
2031 return emitWritebackArg(*this, args, CRE);
2032 }
2033
John McCall8affed52011-08-26 18:42:59 +00002034 assert(type->isReferenceType() == E->isGLValue() &&
2035 "reference binding to unmaterialized r-value!");
2036
John McCallcec52f02011-08-26 21:08:13 +00002037 if (E->isGLValue()) {
2038 assert(E->getObjectKind() == OK_Ordinary);
Richard Smithd4ec5622013-06-12 23:38:09 +00002039 return args.add(EmitReferenceBindingToExpr(E), type);
John McCallcec52f02011-08-26 21:08:13 +00002040 }
Mike Stump1eb44332009-09-09 15:08:12 +00002041
Reid Kleckner9b601952013-06-21 12:45:15 +00002042 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2043
2044 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2045 // However, we still have to push an EH-only cleanup in case we unwind before
2046 // we make it to the call.
2047 if (HasAggregateEvalKind &&
2048 CGM.getTarget().getCXXABI().isArgumentDestroyedByCallee()) {
2049 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2050 if (RD && RD->hasNonTrivialDestructor()) {
2051 AggValueSlot Slot = CreateAggTemp(type, "agg.arg.tmp");
2052 Slot.setExternallyDestructed();
2053 EmitAggExpr(E, Slot);
2054 RValue RV = Slot.asRValue();
2055 args.add(RV, type);
2056
2057 pushDestroy(EHCleanup, RV.getAggregateAddr(), type, destroyCXXObject,
2058 /*useEHCleanupForArray*/ true);
2059 // This unreachable is a temporary marker which will be removed later.
2060 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2061 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
2062 return;
2063 }
2064 }
2065
2066 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedman55d48482011-05-26 00:10:27 +00002067 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2068 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2069 assert(L.isSimple());
Eli Friedmand39083d2013-06-11 01:08:22 +00002070 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2071 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2072 } else {
2073 // We can't represent a misaligned lvalue in the CallArgList, so copy
2074 // to an aligned temporary now.
2075 llvm::Value *tmp = CreateMemTemp(type);
2076 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2077 L.getAlignment());
2078 args.add(RValue::getAggregate(tmp), type);
2079 }
Eli Friedman55d48482011-05-26 00:10:27 +00002080 return;
2081 }
2082
John McCall413ebdb2011-03-11 20:59:21 +00002083 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson0139bb92009-04-08 20:47:54 +00002084}
2085
Dan Gohmanb49bd272012-02-16 00:57:37 +00002086// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2087// optimizer it can aggressively ignore unwind edges.
2088void
2089CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2090 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2091 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2092 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2093 CGM.getNoObjCARCExceptionsMetadata());
2094}
2095
John McCallbd7370a2013-02-28 19:01:20 +00002096/// Emits a call to the given no-arguments nounwind runtime function.
2097llvm::CallInst *
2098CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2099 const llvm::Twine &name) {
2100 return EmitNounwindRuntimeCall(callee, ArrayRef<llvm::Value*>(), name);
2101}
2102
2103/// Emits a call to the given nounwind runtime function.
2104llvm::CallInst *
2105CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2106 ArrayRef<llvm::Value*> args,
2107 const llvm::Twine &name) {
2108 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2109 call->setDoesNotThrow();
2110 return call;
2111}
2112
2113/// Emits a simple call (never an invoke) to the given no-arguments
2114/// runtime function.
2115llvm::CallInst *
2116CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2117 const llvm::Twine &name) {
2118 return EmitRuntimeCall(callee, ArrayRef<llvm::Value*>(), name);
2119}
2120
2121/// Emits a simple call (never an invoke) to the given runtime
2122/// function.
2123llvm::CallInst *
2124CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2125 ArrayRef<llvm::Value*> args,
2126 const llvm::Twine &name) {
2127 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2128 call->setCallingConv(getRuntimeCC());
2129 return call;
2130}
2131
2132/// Emits a call or invoke to the given noreturn runtime function.
2133void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2134 ArrayRef<llvm::Value*> args) {
2135 if (getInvokeDest()) {
2136 llvm::InvokeInst *invoke =
2137 Builder.CreateInvoke(callee,
2138 getUnreachableBlock(),
2139 getInvokeDest(),
2140 args);
2141 invoke->setDoesNotReturn();
2142 invoke->setCallingConv(getRuntimeCC());
2143 } else {
2144 llvm::CallInst *call = Builder.CreateCall(callee, args);
2145 call->setDoesNotReturn();
2146 call->setCallingConv(getRuntimeCC());
2147 Builder.CreateUnreachable();
2148 }
2149}
2150
2151/// Emits a call or invoke instruction to the given nullary runtime
2152/// function.
2153llvm::CallSite
2154CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2155 const Twine &name) {
2156 return EmitRuntimeCallOrInvoke(callee, ArrayRef<llvm::Value*>(), name);
2157}
2158
2159/// Emits a call or invoke instruction to the given runtime function.
2160llvm::CallSite
2161CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2162 ArrayRef<llvm::Value*> args,
2163 const Twine &name) {
2164 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2165 callSite.setCallingConv(getRuntimeCC());
2166 return callSite;
2167}
2168
2169llvm::CallSite
2170CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2171 const Twine &Name) {
2172 return EmitCallOrInvoke(Callee, ArrayRef<llvm::Value *>(), Name);
2173}
2174
John McCallf1549f62010-07-06 01:34:17 +00002175/// Emits a call or invoke instruction to the given function, depending
2176/// on the current state of the EH stack.
2177llvm::CallSite
2178CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner2d3ba4f2011-07-23 17:14:25 +00002179 ArrayRef<llvm::Value *> Args,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002180 const Twine &Name) {
John McCallf1549f62010-07-06 01:34:17 +00002181 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallf1549f62010-07-06 01:34:17 +00002182
Dan Gohmanb49bd272012-02-16 00:57:37 +00002183 llvm::Instruction *Inst;
2184 if (!InvokeDest)
2185 Inst = Builder.CreateCall(Callee, Args, Name);
2186 else {
2187 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
2188 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
2189 EmitBlock(ContBB);
2190 }
2191
2192 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2193 // optimizer it can aggressively ignore unwind edges.
David Blaikie4e4d0842012-03-11 07:00:24 +00002194 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohmanb49bd272012-02-16 00:57:37 +00002195 AddObjCARCExceptionMetadata(Inst);
2196
2197 return Inst;
John McCallf1549f62010-07-06 01:34:17 +00002198}
2199
Chris Lattner70855442011-07-12 04:46:18 +00002200static void checkArgMatches(llvm::Value *Elt, unsigned &ArgNo,
2201 llvm::FunctionType *FTy) {
2202 if (ArgNo < FTy->getNumParams())
2203 assert(Elt->getType() == FTy->getParamType(ArgNo));
2204 else
2205 assert(FTy->isVarArg());
2206 ++ArgNo;
2207}
2208
Chris Lattner811bf362011-07-12 06:29:11 +00002209void CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV,
Craig Topper6b9240e2013-07-05 19:34:19 +00002210 SmallVectorImpl<llvm::Value *> &Args,
Chris Lattner811bf362011-07-12 06:29:11 +00002211 llvm::FunctionType *IRFuncTy) {
Bob Wilson194f06a2011-08-03 05:58:22 +00002212 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2213 unsigned NumElts = AT->getSize().getZExtValue();
2214 QualType EltTy = AT->getElementType();
2215 llvm::Value *Addr = RV.getAggregateAddr();
2216 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
2217 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, Elt);
John McCall9d232c82013-03-07 21:37:08 +00002218 RValue EltRV = convertTempToRValue(EltAddr, EltTy);
Bob Wilson194f06a2011-08-03 05:58:22 +00002219 ExpandTypeToArgs(EltTy, EltRV, Args, IRFuncTy);
Chris Lattner811bf362011-07-12 06:29:11 +00002220 }
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002221 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilson194f06a2011-08-03 05:58:22 +00002222 RecordDecl *RD = RT->getDecl();
2223 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
Eli Friedman377ecc72012-04-16 03:54:45 +00002224 LValue LV = MakeAddrLValue(RV.getAggregateAddr(), Ty);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002225
2226 if (RD->isUnion()) {
2227 const FieldDecl *LargestFD = 0;
2228 CharUnits UnionSize = CharUnits::Zero();
2229
2230 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2231 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00002232 const FieldDecl *FD = *i;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002233 assert(!FD->isBitField() &&
2234 "Cannot expand structure with bit-field members.");
2235 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
2236 if (UnionSize < FieldSize) {
2237 UnionSize = FieldSize;
2238 LargestFD = FD;
2239 }
2240 }
2241 if (LargestFD) {
Eli Friedman377ecc72012-04-16 03:54:45 +00002242 RValue FldRV = EmitRValueForField(LV, LargestFD);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002243 ExpandTypeToArgs(LargestFD->getType(), FldRV, Args, IRFuncTy);
2244 }
2245 } else {
2246 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2247 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00002248 FieldDecl *FD = *i;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002249
Eli Friedman377ecc72012-04-16 03:54:45 +00002250 RValue FldRV = EmitRValueForField(LV, FD);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002251 ExpandTypeToArgs(FD->getType(), FldRV, Args, IRFuncTy);
2252 }
Bob Wilson194f06a2011-08-03 05:58:22 +00002253 }
Eli Friedmanca3d3fc2011-11-15 02:46:03 +00002254 } else if (Ty->isAnyComplexType()) {
Bob Wilson194f06a2011-08-03 05:58:22 +00002255 ComplexPairTy CV = RV.getComplexVal();
2256 Args.push_back(CV.first);
2257 Args.push_back(CV.second);
2258 } else {
Chris Lattner811bf362011-07-12 06:29:11 +00002259 assert(RV.isScalar() &&
2260 "Unexpected non-scalar rvalue during struct expansion.");
2261
2262 // Insert a bitcast as needed.
2263 llvm::Value *V = RV.getScalarVal();
2264 if (Args.size() < IRFuncTy->getNumParams() &&
2265 V->getType() != IRFuncTy->getParamType(Args.size()))
2266 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(Args.size()));
2267
2268 Args.push_back(V);
2269 }
2270}
2271
2272
Daniel Dunbar88b53962009-02-02 22:03:45 +00002273RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002274 llvm::Value *Callee,
Anders Carlssonf3c47c92009-12-24 19:25:24 +00002275 ReturnValueSlot ReturnValue,
Daniel Dunbarc0ef9f52009-02-20 18:06:48 +00002276 const CallArgList &CallArgs,
David Chisnalldd5c98f2010-05-01 11:15:56 +00002277 const Decl *TargetDecl,
David Chisnall4b02afc2010-05-02 13:41:58 +00002278 llvm::Instruction **callOrInvoke) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00002279 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002280 SmallVector<llvm::Value*, 16> Args;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002281
2282 // Handle struct-return functions by passing a pointer to the
2283 // location that we would like to return into.
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002284 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb225be42009-02-03 05:59:18 +00002285 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002286
Chris Lattner70855442011-07-12 04:46:18 +00002287 // IRArgNo - Keep track of the argument number in the callee we're looking at.
2288 unsigned IRArgNo = 0;
2289 llvm::FunctionType *IRFuncTy =
2290 cast<llvm::FunctionType>(
2291 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump1eb44332009-09-09 15:08:12 +00002292
Chris Lattner5db7ae52009-06-13 00:26:38 +00002293 // If the call returns a temporary with struct return, create a temporary
Anders Carlssond2490a92009-12-24 20:40:36 +00002294 // alloca to hold the result, unless one is given to us.
Daniel Dunbardacf9dd2010-07-14 23:39:36 +00002295 if (CGM.ReturnTypeUsesSRet(CallInfo)) {
Anders Carlssond2490a92009-12-24 20:40:36 +00002296 llvm::Value *Value = ReturnValue.getValue();
2297 if (!Value)
Daniel Dunbar195337d2010-02-09 02:48:28 +00002298 Value = CreateMemTemp(RetTy);
Anders Carlssond2490a92009-12-24 20:40:36 +00002299 Args.push_back(Value);
Chris Lattner70855442011-07-12 04:46:18 +00002300 checkArgMatches(Value, IRArgNo, IRFuncTy);
Anders Carlssond2490a92009-12-24 20:40:36 +00002301 }
Mike Stump1eb44332009-09-09 15:08:12 +00002302
Daniel Dunbar4b5f0a42009-02-04 21:17:21 +00002303 assert(CallInfo.arg_size() == CallArgs.size() &&
2304 "Mismatch between function signature & arguments.");
Daniel Dunbarb225be42009-02-03 05:59:18 +00002305 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00002306 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Daniel Dunbarb225be42009-02-03 05:59:18 +00002307 I != E; ++I, ++info_it) {
2308 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanc6d07822011-05-02 18:05:27 +00002309 RValue RV = I->RV;
Daniel Dunbar56273772008-09-17 00:51:38 +00002310
John McCall9d232c82013-03-07 21:37:08 +00002311 CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00002312
2313 // Insert a padding argument to ensure proper alignment.
2314 if (llvm::Type *PaddingType = ArgInfo.getPaddingType()) {
2315 Args.push_back(llvm::UndefValue::get(PaddingType));
2316 ++IRArgNo;
2317 }
2318
Daniel Dunbar56273772008-09-17 00:51:38 +00002319 switch (ArgInfo.getKind()) {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00002320 case ABIArgInfo::Indirect: {
Daniel Dunbar1f745982009-02-05 09:16:39 +00002321 if (RV.isScalar() || RV.isComplex()) {
2322 // Make a temporary alloca to pass the argument.
Eli Friedman70cbd2a2011-06-15 18:26:32 +00002323 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2324 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
2325 AI->setAlignment(ArgInfo.getIndirectAlign());
2326 Args.push_back(AI);
John McCall9d232c82013-03-07 21:37:08 +00002327
2328 LValue argLV =
2329 MakeAddrLValue(Args.back(), I->Ty, TypeAlign);
Chris Lattner70855442011-07-12 04:46:18 +00002330
Daniel Dunbar1f745982009-02-05 09:16:39 +00002331 if (RV.isScalar())
John McCall9d232c82013-03-07 21:37:08 +00002332 EmitStoreOfScalar(RV.getScalarVal(), argLV, /*init*/ true);
Daniel Dunbar1f745982009-02-05 09:16:39 +00002333 else
John McCall9d232c82013-03-07 21:37:08 +00002334 EmitStoreOfComplex(RV.getComplexVal(), argLV, /*init*/ true);
Chris Lattner70855442011-07-12 04:46:18 +00002335
2336 // Validate argument match.
2337 checkArgMatches(AI, IRArgNo, IRFuncTy);
Daniel Dunbar1f745982009-02-05 09:16:39 +00002338 } else {
Eli Friedmanea5e4da2011-06-14 01:37:52 +00002339 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyeid436c992013-03-10 12:59:00 +00002340 // however, we need one in three cases:
Eli Friedmanea5e4da2011-06-14 01:37:52 +00002341 // 1. If the argument is not byval, and we are required to copy the
2342 // source. (This case doesn't occur on any common architecture.)
2343 // 2. If the argument is byval, RV is not sufficiently aligned, and
2344 // we cannot force it to be sufficiently aligned.
Guy Benyeid436c992013-03-10 12:59:00 +00002345 // 3. If the argument is byval, but RV is located in an address space
2346 // different than that of the argument (0).
Eli Friedman97cb5a42011-06-15 22:09:18 +00002347 llvm::Value *Addr = RV.getAggregateAddr();
2348 unsigned Align = ArgInfo.getIndirectAlign();
Micah Villmow25a6a842012-10-08 16:25:52 +00002349 const llvm::DataLayout *TD = &CGM.getDataLayout();
Guy Benyeid436c992013-03-10 12:59:00 +00002350 const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
2351 const unsigned ArgAddrSpace = (IRArgNo < IRFuncTy->getNumParams() ?
2352 IRFuncTy->getParamType(IRArgNo)->getPointerAddressSpace() : 0);
Eli Friedman97cb5a42011-06-15 22:09:18 +00002353 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall9d232c82013-03-07 21:37:08 +00002354 (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
Guy Benyeid436c992013-03-10 12:59:00 +00002355 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align) ||
2356 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmanea5e4da2011-06-14 01:37:52 +00002357 // Create an aligned temporary, and copy to it.
Eli Friedman97cb5a42011-06-15 22:09:18 +00002358 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2359 if (Align > AI->getAlignment())
2360 AI->setAlignment(Align);
Eli Friedmanea5e4da2011-06-14 01:37:52 +00002361 Args.push_back(AI);
Chad Rosier649b4a12012-03-29 17:37:10 +00002362 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Chris Lattner70855442011-07-12 04:46:18 +00002363
2364 // Validate argument match.
2365 checkArgMatches(AI, IRArgNo, IRFuncTy);
Eli Friedmanea5e4da2011-06-14 01:37:52 +00002366 } else {
2367 // Skip the extra memcpy call.
Eli Friedman97cb5a42011-06-15 22:09:18 +00002368 Args.push_back(Addr);
Chris Lattner70855442011-07-12 04:46:18 +00002369
2370 // Validate argument match.
2371 checkArgMatches(Addr, IRArgNo, IRFuncTy);
Eli Friedmanea5e4da2011-06-14 01:37:52 +00002372 }
Daniel Dunbar1f745982009-02-05 09:16:39 +00002373 }
2374 break;
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00002375 }
Daniel Dunbar1f745982009-02-05 09:16:39 +00002376
Daniel Dunbar11434922009-01-26 21:26:08 +00002377 case ABIArgInfo::Ignore:
2378 break;
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002379
Chris Lattner800588f2010-07-29 06:26:06 +00002380 case ABIArgInfo::Extend:
2381 case ABIArgInfo::Direct: {
2382 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner117e3f42010-07-30 04:02:24 +00002383 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
2384 ArgInfo.getDirectOffset() == 0) {
Chris Lattner70855442011-07-12 04:46:18 +00002385 llvm::Value *V;
Chris Lattner800588f2010-07-29 06:26:06 +00002386 if (RV.isScalar())
Chris Lattner70855442011-07-12 04:46:18 +00002387 V = RV.getScalarVal();
Chris Lattner800588f2010-07-29 06:26:06 +00002388 else
Chris Lattner70855442011-07-12 04:46:18 +00002389 V = Builder.CreateLoad(RV.getAggregateAddr());
2390
Chris Lattner21ca1fd2011-07-12 04:53:39 +00002391 // If the argument doesn't match, perform a bitcast to coerce it. This
2392 // can happen due to trivial type mismatches.
2393 if (IRArgNo < IRFuncTy->getNumParams() &&
2394 V->getType() != IRFuncTy->getParamType(IRArgNo))
2395 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRArgNo));
Chris Lattner70855442011-07-12 04:46:18 +00002396 Args.push_back(V);
2397
Chris Lattner70855442011-07-12 04:46:18 +00002398 checkArgMatches(V, IRArgNo, IRFuncTy);
Chris Lattner800588f2010-07-29 06:26:06 +00002399 break;
2400 }
Daniel Dunbar11434922009-01-26 21:26:08 +00002401
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00002402 // FIXME: Avoid the conversion through memory if possible.
2403 llvm::Value *SrcPtr;
John McCall9d232c82013-03-07 21:37:08 +00002404 if (RV.isScalar() || RV.isComplex()) {
Eli Friedmanc6d07822011-05-02 18:05:27 +00002405 SrcPtr = CreateMemTemp(I->Ty, "coerce");
John McCall9d232c82013-03-07 21:37:08 +00002406 LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
2407 if (RV.isScalar()) {
2408 EmitStoreOfScalar(RV.getScalarVal(), SrcLV, /*init*/ true);
2409 } else {
2410 EmitStoreOfComplex(RV.getComplexVal(), SrcLV, /*init*/ true);
2411 }
Mike Stump1eb44332009-09-09 15:08:12 +00002412 } else
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00002413 SrcPtr = RV.getAggregateAddr();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002414
Chris Lattner117e3f42010-07-30 04:02:24 +00002415 // If the value is offset in memory, apply the offset now.
2416 if (unsigned Offs = ArgInfo.getDirectOffset()) {
2417 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
2418 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002419 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner117e3f42010-07-30 04:02:24 +00002420 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
2421
2422 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002423
Chris Lattnerce700162010-06-28 23:44:11 +00002424 // If the coerce-to type is a first class aggregate, we flatten it and
2425 // pass the elements. Either way is semantically identical, but fast-isel
2426 // and the optimizer generally likes scalar values better than FCAs.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002427 if (llvm::StructType *STy =
Chris Lattner309c59f2010-06-29 00:06:42 +00002428 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType())) {
Chandler Carruthf82232c2012-10-10 11:29:08 +00002429 llvm::Type *SrcTy =
2430 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
2431 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
2432 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
2433
2434 // If the source type is smaller than the destination type of the
2435 // coerce-to logic, copy the source value into a temp alloca the size
2436 // of the destination type to allow loading all of it. The bits past
2437 // the source value are left undef.
2438 if (SrcSize < DstSize) {
2439 llvm::AllocaInst *TempAlloca
2440 = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
2441 Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
2442 SrcPtr = TempAlloca;
2443 } else {
2444 SrcPtr = Builder.CreateBitCast(SrcPtr,
2445 llvm::PointerType::getUnqual(STy));
2446 }
2447
Chris Lattner92826882010-07-05 20:41:41 +00002448 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2449 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerdeabde22010-07-28 18:24:28 +00002450 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
2451 // We don't know what we're loading from.
2452 LI->setAlignment(1);
2453 Args.push_back(LI);
Chris Lattner70855442011-07-12 04:46:18 +00002454
2455 // Validate argument match.
2456 checkArgMatches(LI, IRArgNo, IRFuncTy);
Chris Lattner309c59f2010-06-29 00:06:42 +00002457 }
Chris Lattnerce700162010-06-28 23:44:11 +00002458 } else {
Chris Lattner309c59f2010-06-29 00:06:42 +00002459 // In the simple case, just pass the coerced loaded value.
2460 Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(),
2461 *this));
Chris Lattner70855442011-07-12 04:46:18 +00002462
2463 // Validate argument match.
2464 checkArgMatches(Args.back(), IRArgNo, IRFuncTy);
Chris Lattnerce700162010-06-28 23:44:11 +00002465 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002466
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00002467 break;
2468 }
2469
Daniel Dunbar56273772008-09-17 00:51:38 +00002470 case ABIArgInfo::Expand:
Chris Lattner811bf362011-07-12 06:29:11 +00002471 ExpandTypeToArgs(I->Ty, RV, Args, IRFuncTy);
Chris Lattner70855442011-07-12 04:46:18 +00002472 IRArgNo = Args.size();
Daniel Dunbar56273772008-09-17 00:51:38 +00002473 break;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002474 }
2475 }
Mike Stump1eb44332009-09-09 15:08:12 +00002476
Reid Kleckner9b601952013-06-21 12:45:15 +00002477 if (!CallArgs.getCleanupsToDeactivate().empty())
2478 deactivateArgCleanupsBeforeCall(*this, CallArgs);
2479
Chris Lattner5db7ae52009-06-13 00:26:38 +00002480 // If the callee is a bitcast of a function to a varargs pointer to function
2481 // type, check to see if we can remove the bitcast. This handles some cases
2482 // with unprototyped functions.
2483 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
2484 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002485 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
2486 llvm::FunctionType *CurFT =
Chris Lattner5db7ae52009-06-13 00:26:38 +00002487 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2acc6e32011-07-18 04:24:23 +00002488 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump1eb44332009-09-09 15:08:12 +00002489
Chris Lattner5db7ae52009-06-13 00:26:38 +00002490 if (CE->getOpcode() == llvm::Instruction::BitCast &&
2491 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattnerd6bebbf2009-06-23 01:38:41 +00002492 ActualFT->getNumParams() == CurFT->getNumParams() &&
Fariborz Jahanianc0ddef22011-03-01 17:28:13 +00002493 ActualFT->getNumParams() == Args.size() &&
2494 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner5db7ae52009-06-13 00:26:38 +00002495 bool ArgsMatch = true;
2496 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
2497 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
2498 ArgsMatch = false;
2499 break;
2500 }
Mike Stump1eb44332009-09-09 15:08:12 +00002501
Chris Lattner5db7ae52009-06-13 00:26:38 +00002502 // Strip the cast if we can get away with it. This is a nice cleanup,
2503 // but also allows us to inline the function at -O0 if it is marked
2504 // always_inline.
2505 if (ArgsMatch)
2506 Callee = CalleeF;
2507 }
2508 }
Mike Stump1eb44332009-09-09 15:08:12 +00002509
Daniel Dunbarca6408c2009-09-12 00:59:20 +00002510 unsigned CallingConv;
Devang Patel761d7f72008-09-25 21:02:23 +00002511 CodeGen::AttributeListType AttributeList;
Bill Wendling94236e72013-02-22 00:13:35 +00002512 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
2513 CallingConv, true);
Bill Wendling785b7782012-12-07 23:17:26 +00002514 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendling94236e72013-02-22 00:13:35 +00002515 AttributeList);
Mike Stump1eb44332009-09-09 15:08:12 +00002516
John McCallf1549f62010-07-06 01:34:17 +00002517 llvm::BasicBlock *InvokeDest = 0;
Bill Wendling01ad9542012-12-30 10:32:17 +00002518 if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
2519 llvm::Attribute::NoUnwind))
John McCallf1549f62010-07-06 01:34:17 +00002520 InvokeDest = getInvokeDest();
2521
Daniel Dunbard14151d2009-03-02 04:32:35 +00002522 llvm::CallSite CS;
John McCallf1549f62010-07-06 01:34:17 +00002523 if (!InvokeDest) {
Jay Foad4c7d9f12011-07-15 08:37:34 +00002524 CS = Builder.CreateCall(Callee, Args);
Daniel Dunbar9834ffb2009-02-23 17:26:39 +00002525 } else {
2526 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Jay Foad4c7d9f12011-07-15 08:37:34 +00002527 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, Args);
Daniel Dunbar9834ffb2009-02-23 17:26:39 +00002528 EmitBlock(Cont);
Daniel Dunbarf4fe0f02009-02-20 18:54:31 +00002529 }
Chris Lattnerce933992010-06-29 16:40:28 +00002530 if (callOrInvoke)
David Chisnall4b02afc2010-05-02 13:41:58 +00002531 *callOrInvoke = CS.getInstruction();
Daniel Dunbarf4fe0f02009-02-20 18:54:31 +00002532
Daniel Dunbard14151d2009-03-02 04:32:35 +00002533 CS.setAttributes(Attrs);
Daniel Dunbarca6408c2009-09-12 00:59:20 +00002534 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbard14151d2009-03-02 04:32:35 +00002535
Dan Gohmanb49bd272012-02-16 00:57:37 +00002536 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2537 // optimizer it can aggressively ignore unwind edges.
David Blaikie4e4d0842012-03-11 07:00:24 +00002538 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohmanb49bd272012-02-16 00:57:37 +00002539 AddObjCARCExceptionMetadata(CS.getInstruction());
2540
Daniel Dunbard14151d2009-03-02 04:32:35 +00002541 // If the call doesn't return, finish the basic block and clear the
2542 // insertion point; this allows the rest of IRgen to discard
2543 // unreachable code.
2544 if (CS.doesNotReturn()) {
2545 Builder.CreateUnreachable();
2546 Builder.ClearInsertionPoint();
Mike Stump1eb44332009-09-09 15:08:12 +00002547
Mike Stumpf5408fe2009-05-16 07:57:57 +00002548 // FIXME: For now, emit a dummy basic block because expr emitters in
2549 // generally are not ready to handle emitting expressions at unreachable
2550 // points.
Daniel Dunbard14151d2009-03-02 04:32:35 +00002551 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +00002552
Daniel Dunbard14151d2009-03-02 04:32:35 +00002553 // Return a reasonable RValue.
2554 return GetUndefRValue(RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002555 }
Daniel Dunbard14151d2009-03-02 04:32:35 +00002556
2557 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerffbb15e2009-10-05 13:47:21 +00002558 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002559 CI->setName("call");
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00002560
John McCallf85e1932011-06-15 23:02:42 +00002561 // Emit any writebacks immediately. Arguably this should happen
2562 // after any return-value munging.
2563 if (CallArgs.hasWritebacks())
2564 emitWritebacks(*this, CallArgs);
2565
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00002566 switch (RetAI.getKind()) {
John McCall9d232c82013-03-07 21:37:08 +00002567 case ABIArgInfo::Indirect:
2568 return convertTempToRValue(Args[0], RetTy);
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00002569
Daniel Dunbar11434922009-01-26 21:26:08 +00002570 case ABIArgInfo::Ignore:
Daniel Dunbar0bcc5212009-02-03 06:30:17 +00002571 // If we are ignoring an argument that had a result, make sure to
2572 // construct the appropriate return value for our caller.
Daniel Dunbar13e81732009-02-05 07:09:07 +00002573 return GetUndefRValue(RetTy);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002574
Chris Lattner800588f2010-07-29 06:26:06 +00002575 case ABIArgInfo::Extend:
2576 case ABIArgInfo::Direct: {
Chris Lattner6af13f32011-07-13 03:59:32 +00002577 llvm::Type *RetIRTy = ConvertType(RetTy);
2578 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
John McCall9d232c82013-03-07 21:37:08 +00002579 switch (getEvaluationKind(RetTy)) {
2580 case TEK_Complex: {
Chris Lattner800588f2010-07-29 06:26:06 +00002581 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
2582 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
2583 return RValue::getComplex(std::make_pair(Real, Imag));
2584 }
John McCall9d232c82013-03-07 21:37:08 +00002585 case TEK_Aggregate: {
Chris Lattner800588f2010-07-29 06:26:06 +00002586 llvm::Value *DestPtr = ReturnValue.getValue();
2587 bool DestIsVolatile = ReturnValue.isVolatile();
Daniel Dunbar11434922009-01-26 21:26:08 +00002588
Chris Lattner800588f2010-07-29 06:26:06 +00002589 if (!DestPtr) {
2590 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
2591 DestIsVolatile = false;
2592 }
Eli Friedmanbadea572011-05-17 21:08:01 +00002593 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
Chris Lattner800588f2010-07-29 06:26:06 +00002594 return RValue::getAggregate(DestPtr);
2595 }
John McCall9d232c82013-03-07 21:37:08 +00002596 case TEK_Scalar: {
2597 // If the argument doesn't match, perform a bitcast to coerce it. This
2598 // can happen due to trivial type mismatches.
2599 llvm::Value *V = CI;
2600 if (V->getType() != RetIRTy)
2601 V = Builder.CreateBitCast(V, RetIRTy);
2602 return RValue::get(V);
2603 }
2604 }
2605 llvm_unreachable("bad evaluation kind");
Chris Lattner800588f2010-07-29 06:26:06 +00002606 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002607
Anders Carlssond2490a92009-12-24 20:40:36 +00002608 llvm::Value *DestPtr = ReturnValue.getValue();
2609 bool DestIsVolatile = ReturnValue.isVolatile();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002610
Anders Carlssond2490a92009-12-24 20:40:36 +00002611 if (!DestPtr) {
Daniel Dunbar195337d2010-02-09 02:48:28 +00002612 DestPtr = CreateMemTemp(RetTy, "coerce");
Anders Carlssond2490a92009-12-24 20:40:36 +00002613 DestIsVolatile = false;
2614 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002615
Chris Lattner117e3f42010-07-30 04:02:24 +00002616 // If the value is offset in memory, apply the offset now.
2617 llvm::Value *StorePtr = DestPtr;
2618 if (unsigned Offs = RetAI.getDirectOffset()) {
2619 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
2620 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002621 StorePtr = Builder.CreateBitCast(StorePtr,
Chris Lattner117e3f42010-07-30 04:02:24 +00002622 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
2623 }
2624 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002625
John McCall9d232c82013-03-07 21:37:08 +00002626 return convertTempToRValue(DestPtr, RetTy);
Daniel Dunbar639ffe42008-09-10 07:04:09 +00002627 }
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00002628
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00002629 case ABIArgInfo::Expand:
David Blaikieb219cfc2011-09-23 05:06:16 +00002630 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002631 }
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00002632
David Blaikieb219cfc2011-09-23 05:06:16 +00002633 llvm_unreachable("Unhandled ABIArgInfo::Kind");
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002634}
Daniel Dunbarb4094ea2009-02-10 20:44:09 +00002635
2636/* VarArg handling */
2637
2638llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
2639 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
2640}