blob: 972a7c8dbb7778df8ae96d1bd34b2ad11477635c [file] [log] [blame]
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001//===--- CGCall.cpp - Encapsulate calling convention details --------------===//
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CGCall.h"
Chris Lattnere70a0072010-06-29 16:40:28 +000016#include "ABIInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CGCXXABI.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000018#include "CodeGenFunction.h"
Daniel Dunbarc68897d2008-09-10 00:41:16 +000019#include "CodeGenModule.h"
John McCalla729c622012-02-17 03:33:10 +000020#include "TargetInfo.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000021#include "clang/AST/Decl.h"
Anders Carlssonb15b55c2009-04-03 22:48:58 +000022#include "clang/AST/DeclCXX.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000023#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000025#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth85098242010-06-15 23:19:56 +000026#include "clang/Frontend/CodeGenOptions.h"
Bill Wendling706469b2013-02-28 22:49:57 +000027#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000028#include "llvm/IR/Attributes.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000029#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000030#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/InlineAsm.h"
Reid Kleckner314ef7b2014-02-01 00:04:45 +000032#include "llvm/IR/Intrinsics.h"
Eli Friedmanf7456192011-06-15 22:09:18 +000033#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000034using namespace clang;
35using namespace CodeGen;
36
37/***/
38
John McCallab26cfa2010-02-05 21:31:56 +000039static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) {
40 switch (CC) {
41 default: return llvm::CallingConv::C;
42 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
43 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
Douglas Gregora941dca2010-05-18 16:57:00 +000044 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Charles Davisb5a214e2013-08-30 04:39:01 +000045 case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64;
46 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
Anton Korobeynikov231e8752011-04-14 20:06:49 +000047 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
48 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Guy Benyeif0a014b2012-12-25 08:53:55 +000049 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Dawn Perchik335e16b2010-09-03 01:29:35 +000050 // TODO: add support for CC_X86Pascal to llvm
John McCallab26cfa2010-02-05 21:31:56 +000051 }
52}
53
John McCall8ee376f2010-02-24 07:14:12 +000054/// Derives the 'this' type for codegen purposes, i.e. ignoring method
55/// qualification.
56/// FIXME: address space qualification?
John McCall2da83a32010-02-26 00:48:12 +000057static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
58 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
59 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000060}
61
John McCall8ee376f2010-02-24 07:14:12 +000062/// Returns the canonical formal type of the given C++ method.
John McCall2da83a32010-02-26 00:48:12 +000063static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
64 return MD->getType()->getCanonicalTypeUnqualified()
65 .getAs<FunctionProtoType>();
John McCall8ee376f2010-02-24 07:14:12 +000066}
67
68/// Returns the "extra-canonicalized" return type, which discards
69/// qualifiers on the return type. Codegen doesn't care about them,
70/// and it makes ABI code a little easier to be able to assume that
71/// all parameter and return types are top-level unqualified.
John McCall2da83a32010-02-26 00:48:12 +000072static CanQualType GetReturnType(QualType RetTy) {
73 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall8ee376f2010-02-24 07:14:12 +000074}
75
John McCall8dda7b22012-07-07 06:41:13 +000076/// Arrange the argument and result information for a value of the given
77/// unprototyped freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +000078const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +000079CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCalla729c622012-02-17 03:33:10 +000080 // When translating an unprototyped function type, always use a
81 // variadic type.
Alp Toker314cc812014-01-25 16:55:45 +000082 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
Reid Kleckner4982b822014-01-31 22:54:50 +000083 false, None, FTNP->getExtInfo(),
84 RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +000085}
86
John McCall8dda7b22012-07-07 06:41:13 +000087/// Arrange the LLVM function layout for a value of the given function
88/// type, on top of any implicit parameters already stored. Use the
89/// given ExtInfo instead of the ExtInfo from the function type.
90static const CGFunctionInfo &arrangeLLVMFunctionInfo(CodeGenTypes &CGT,
Reid Kleckner4982b822014-01-31 22:54:50 +000091 bool IsInstanceMethod,
John McCall8dda7b22012-07-07 06:41:13 +000092 SmallVectorImpl<CanQualType> &prefix,
93 CanQual<FunctionProtoType> FTP,
94 FunctionType::ExtInfo extInfo) {
95 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +000096 // FIXME: Kill copy.
Alp Toker9cacbab2014-01-20 20:26:09 +000097 for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
98 prefix.push_back(FTP->getParamType(i));
Alp Toker314cc812014-01-25 16:55:45 +000099 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
Reid Kleckner4982b822014-01-31 22:54:50 +0000100 return CGT.arrangeLLVMFunctionInfo(resultType, IsInstanceMethod, prefix,
101 extInfo, required);
John McCall8dda7b22012-07-07 06:41:13 +0000102}
103
104/// Arrange the argument and result information for a free function (i.e.
105/// not a C++ or ObjC instance method) of the given type.
106static const CGFunctionInfo &arrangeFreeFunctionType(CodeGenTypes &CGT,
107 SmallVectorImpl<CanQualType> &prefix,
108 CanQual<FunctionProtoType> FTP) {
Reid Kleckner4982b822014-01-31 22:54:50 +0000109 return arrangeLLVMFunctionInfo(CGT, false, prefix, FTP, FTP->getExtInfo());
John McCall8dda7b22012-07-07 06:41:13 +0000110}
111
John McCall8dda7b22012-07-07 06:41:13 +0000112/// Arrange the argument and result information for a free function (i.e.
113/// not a C++ or ObjC instance method) of the given type.
114static const CGFunctionInfo &arrangeCXXMethodType(CodeGenTypes &CGT,
115 SmallVectorImpl<CanQualType> &prefix,
116 CanQual<FunctionProtoType> FTP) {
117 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
Reid Kleckner4982b822014-01-31 22:54:50 +0000118 return arrangeLLVMFunctionInfo(CGT, true, prefix, FTP, extInfo);
John McCall8ee376f2010-02-24 07:14:12 +0000119}
120
John McCalla729c622012-02-17 03:33:10 +0000121/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000122/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000123const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000124CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
John McCalla729c622012-02-17 03:33:10 +0000125 SmallVector<CanQualType, 16> argTypes;
John McCall8dda7b22012-07-07 06:41:13 +0000126 return ::arrangeFreeFunctionType(*this, argTypes, FTP);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000127}
128
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000129static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000130 // Set the appropriate calling convention for the Function.
131 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000132 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000133
134 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000135 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000136
Douglas Gregora941dca2010-05-18 16:57:00 +0000137 if (D->hasAttr<ThisCallAttr>())
138 return CC_X86ThisCall;
139
Dawn Perchik335e16b2010-09-03 01:29:35 +0000140 if (D->hasAttr<PascalAttr>())
141 return CC_X86Pascal;
142
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000143 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
144 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
145
Derek Schuffa2020962012-10-16 22:30:41 +0000146 if (D->hasAttr<PnaclCallAttr>())
147 return CC_PnaclCall;
148
Guy Benyeif0a014b2012-12-25 08:53:55 +0000149 if (D->hasAttr<IntelOclBiccAttr>())
150 return CC_IntelOclBicc;
151
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000152 if (D->hasAttr<MSABIAttr>())
153 return IsWindows ? CC_C : CC_X86_64Win64;
154
155 if (D->hasAttr<SysVABIAttr>())
156 return IsWindows ? CC_X86_64SysV : CC_C;
157
John McCallab26cfa2010-02-05 21:31:56 +0000158 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000159}
160
John McCalla729c622012-02-17 03:33:10 +0000161/// Arrange the argument and result information for a call to an
162/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000163/// (Zero value of RD means we don't have any meaningful "this" argument type,
164/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000165/// The member function must be an ordinary function, i.e. not a
166/// constructor or destructor.
167const CGFunctionInfo &
168CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
169 const FunctionProtoType *FTP) {
170 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000171
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000172 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000173 if (RD)
174 argTypes.push_back(GetThisType(Context, RD));
175 else
176 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000177
John McCall8dda7b22012-07-07 06:41:13 +0000178 return ::arrangeCXXMethodType(*this, argTypes,
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000179 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000180}
181
John McCalla729c622012-02-17 03:33:10 +0000182/// Arrange the argument and result information for a declaration or
183/// definition of the given C++ non-static member function. The
184/// member function must be an ordinary function, i.e. not a
185/// constructor or destructor.
186const CGFunctionInfo &
187CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000188 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000189 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
190
John McCalla729c622012-02-17 03:33:10 +0000191 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000192
John McCalla729c622012-02-17 03:33:10 +0000193 if (MD->isInstance()) {
194 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000195 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000196 return arrangeCXXMethodType(ThisType, prototype.getTypePtr());
John McCalla729c622012-02-17 03:33:10 +0000197 }
198
John McCall8dda7b22012-07-07 06:41:13 +0000199 return arrangeFreeFunctionType(prototype);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000200}
201
John McCalla729c622012-02-17 03:33:10 +0000202/// Arrange the argument and result information for a declaration
203/// or definition to the given constructor variant.
204const CGFunctionInfo &
205CodeGenTypes::arrangeCXXConstructorDeclaration(const CXXConstructorDecl *D,
206 CXXCtorType ctorKind) {
207 SmallVector<CanQualType, 16> argTypes;
208 argTypes.push_back(GetThisType(Context, D->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000209
210 GlobalDecl GD(D, ctorKind);
211 CanQualType resultType =
212 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000213
John McCall5d865c322010-08-31 07:33:07 +0000214 CanQual<FunctionProtoType> FTP = GetFormalType(D);
215
216 // Add the formal parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000217 for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
218 argTypes.push_back(FTP->getParamType(i));
John McCall5d865c322010-08-31 07:33:07 +0000219
Reid Kleckner89077a12013-12-17 19:46:40 +0000220 TheCXXABI.BuildConstructorSignature(D, ctorKind, resultType, argTypes);
221
222 RequiredArgs required =
223 (D->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All);
224
John McCall8dda7b22012-07-07 06:41:13 +0000225 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
Reid Kleckner4982b822014-01-31 22:54:50 +0000226 return arrangeLLVMFunctionInfo(resultType, true, argTypes, extInfo, required);
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000227}
228
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000229/// Arrange a call to a C++ method, passing the given arguments.
230const CGFunctionInfo &
231CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
232 const CXXConstructorDecl *D,
233 CXXCtorType CtorKind,
234 unsigned ExtraArgs) {
235 // FIXME: Kill copy.
236 SmallVector<CanQualType, 16> ArgTypes;
237 for (CallArgList::const_iterator i = args.begin(), e = args.end(); i != e;
238 ++i)
239 ArgTypes.push_back(Context.getCanonicalParamType(i->Ty));
240
241 CanQual<FunctionProtoType> FPT = GetFormalType(D);
242 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs);
243 GlobalDecl GD(D, CtorKind);
244 CanQualType ResultType =
245 TheCXXABI.HasThisReturn(GD) ? ArgTypes.front() : Context.VoidTy;
246
247 FunctionType::ExtInfo Info = FPT->getExtInfo();
248 return arrangeLLVMFunctionInfo(ResultType, true, ArgTypes, Info, Required);
249}
250
John McCalla729c622012-02-17 03:33:10 +0000251/// Arrange the argument and result information for a declaration,
252/// definition, or call to the given destructor variant. It so
253/// happens that all three cases produce the same information.
254const CGFunctionInfo &
255CodeGenTypes::arrangeCXXDestructor(const CXXDestructorDecl *D,
256 CXXDtorType dtorKind) {
257 SmallVector<CanQualType, 2> argTypes;
258 argTypes.push_back(GetThisType(Context, D->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000259
260 GlobalDecl GD(D, dtorKind);
261 CanQualType resultType =
262 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
John McCall8ee376f2010-02-24 07:14:12 +0000263
John McCalla729c622012-02-17 03:33:10 +0000264 TheCXXABI.BuildDestructorSignature(D, dtorKind, resultType, argTypes);
John McCall5d865c322010-08-31 07:33:07 +0000265
266 CanQual<FunctionProtoType> FTP = GetFormalType(D);
Alp Toker9cacbab2014-01-20 20:26:09 +0000267 assert(FTP->getNumParams() == 0 && "dtor with formal parameters");
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +0000268 assert(FTP->isVariadic() == 0 && "dtor with formal parameters");
John McCall5d865c322010-08-31 07:33:07 +0000269
John McCall8dda7b22012-07-07 06:41:13 +0000270 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
Reid Kleckner4982b822014-01-31 22:54:50 +0000271 return arrangeLLVMFunctionInfo(resultType, true, argTypes, extInfo,
John McCall8dda7b22012-07-07 06:41:13 +0000272 RequiredArgs::All);
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000273}
274
John McCalla729c622012-02-17 03:33:10 +0000275/// Arrange the argument and result information for the declaration or
276/// definition of the given function.
277const CGFunctionInfo &
278CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000279 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000280 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000281 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000282
John McCall2da83a32010-02-26 00:48:12 +0000283 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000284
John McCall2da83a32010-02-26 00:48:12 +0000285 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000286
287 // When declaring a function without a prototype, always use a
288 // non-variadic type.
289 if (isa<FunctionNoProtoType>(FTy)) {
290 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Reid Kleckner4982b822014-01-31 22:54:50 +0000291 return arrangeLLVMFunctionInfo(noProto->getReturnType(), false, None,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000292 noProto->getExtInfo(), RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000293 }
294
John McCall2da83a32010-02-26 00:48:12 +0000295 assert(isa<FunctionProtoType>(FTy));
John McCall8dda7b22012-07-07 06:41:13 +0000296 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>());
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000297}
298
John McCalla729c622012-02-17 03:33:10 +0000299/// Arrange the argument and result information for the declaration or
300/// definition of an Objective-C method.
301const CGFunctionInfo &
302CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
303 // It happens that this is the same as a call with no optional
304 // arguments, except also using the formal 'self' type.
305 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
306}
307
308/// Arrange the argument and result information for the function type
309/// through which to perform a send to the given Objective-C method,
310/// using the given receiver type. The receiver type is not always
311/// the 'self' type of the method or even an Objective-C pointer type.
312/// This is *not* the right method for actually performing such a
313/// message send, due to the possibility of optional arguments.
314const CGFunctionInfo &
315CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
316 QualType receiverType) {
317 SmallVector<CanQualType, 16> argTys;
318 argTys.push_back(Context.getCanonicalParamType(receiverType));
319 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000320 // FIXME: Kill copy?
Aaron Ballman43b68be2014-03-07 17:50:17 +0000321 for (const auto *I : MD->params()) {
322 argTys.push_back(Context.getCanonicalParamType(I->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000323 }
John McCall31168b02011-06-15 23:02:42 +0000324
325 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000326 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
327 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000328
David Blaikiebbafb8a2012-03-11 07:00:24 +0000329 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000330 MD->hasAttr<NSReturnsRetainedAttr>())
331 einfo = einfo.withProducesResult(true);
332
John McCalla729c622012-02-17 03:33:10 +0000333 RequiredArgs required =
334 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
335
Reid Kleckner4982b822014-01-31 22:54:50 +0000336 return arrangeLLVMFunctionInfo(GetReturnType(MD->getReturnType()), false,
337 argTys, einfo, required);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000338}
339
John McCalla729c622012-02-17 03:33:10 +0000340const CGFunctionInfo &
341CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000342 // FIXME: Do we need to handle ObjCMethodDecl?
343 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000344
Anders Carlsson6710c532010-02-06 02:44:09 +0000345 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
John McCalla729c622012-02-17 03:33:10 +0000346 return arrangeCXXConstructorDeclaration(CD, GD.getCtorType());
Anders Carlsson6710c532010-02-06 02:44:09 +0000347
348 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
John McCalla729c622012-02-17 03:33:10 +0000349 return arrangeCXXDestructor(DD, GD.getDtorType());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000350
John McCalla729c622012-02-17 03:33:10 +0000351 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000352}
353
John McCallc818bbb2012-12-07 07:03:17 +0000354/// Arrange a call as unto a free function, except possibly with an
355/// additional number of formal parameters considered required.
356static const CGFunctionInfo &
357arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000358 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000359 const CallArgList &args,
360 const FunctionType *fnType,
361 unsigned numExtraRequiredArgs) {
362 assert(args.size() >= numExtraRequiredArgs);
363
364 // In most cases, there are no optional arguments.
365 RequiredArgs required = RequiredArgs::All;
366
367 // If we have a variadic prototype, the required arguments are the
368 // extra prefix plus the arguments in the prototype.
369 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
370 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000371 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000372
373 // If we don't have a prototype at all, but we're supposed to
374 // explicitly use the variadic convention for unprototyped calls,
375 // treat all of the arguments as required but preserve the nominal
376 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000377 } else if (CGM.getTargetCodeGenInfo()
378 .isNoProtoCallVariadic(args,
379 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000380 required = RequiredArgs(args.size());
381 }
382
Alp Toker314cc812014-01-25 16:55:45 +0000383 return CGT.arrangeFreeFunctionCall(fnType->getReturnType(), args,
John McCallc818bbb2012-12-07 07:03:17 +0000384 fnType->getExtInfo(), required);
385}
386
John McCalla729c622012-02-17 03:33:10 +0000387/// Figure out the rules for calling a function with the given formal
388/// type using the given arguments. The arguments are necessary
389/// because the function might be unprototyped, in which case it's
390/// target-dependent in crazy ways.
391const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000392CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
393 const FunctionType *fnType) {
Mark Lacey23455752013-10-10 20:57:00 +0000394 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 0);
John McCallc818bbb2012-12-07 07:03:17 +0000395}
John McCalla729c622012-02-17 03:33:10 +0000396
John McCallc818bbb2012-12-07 07:03:17 +0000397/// A block function call is essentially a free-function call with an
398/// extra implicit argument.
399const CGFunctionInfo &
400CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
401 const FunctionType *fnType) {
Mark Lacey23455752013-10-10 20:57:00 +0000402 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1);
John McCalla729c622012-02-17 03:33:10 +0000403}
404
405const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000406CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
407 const CallArgList &args,
408 FunctionType::ExtInfo info,
409 RequiredArgs required) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000410 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000411 SmallVector<CanQualType, 16> argTypes;
412 for (CallArgList::const_iterator i = args.begin(), e = args.end();
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000413 i != e; ++i)
John McCalla729c622012-02-17 03:33:10 +0000414 argTypes.push_back(Context.getCanonicalParamType(i->Ty));
Reid Kleckner4982b822014-01-31 22:54:50 +0000415 return arrangeLLVMFunctionInfo(GetReturnType(resultType), false, argTypes,
416 info, required);
John McCall8dda7b22012-07-07 06:41:13 +0000417}
418
419/// Arrange a call to a C++ method, passing the given arguments.
420const CGFunctionInfo &
421CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
422 const FunctionProtoType *FPT,
423 RequiredArgs required) {
424 // FIXME: Kill copy.
425 SmallVector<CanQualType, 16> argTypes;
426 for (CallArgList::const_iterator i = args.begin(), e = args.end();
427 i != e; ++i)
428 argTypes.push_back(Context.getCanonicalParamType(i->Ty));
429
430 FunctionType::ExtInfo info = FPT->getExtInfo();
Reid Kleckner4982b822014-01-31 22:54:50 +0000431 return arrangeLLVMFunctionInfo(GetReturnType(FPT->getReturnType()), true,
432 argTypes, info, required);
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000433}
434
Reid Kleckner4982b822014-01-31 22:54:50 +0000435const CGFunctionInfo &CodeGenTypes::arrangeFreeFunctionDeclaration(
436 QualType resultType, const FunctionArgList &args,
437 const FunctionType::ExtInfo &info, bool isVariadic) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000438 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000439 SmallVector<CanQualType, 16> argTypes;
440 for (FunctionArgList::const_iterator i = args.begin(), e = args.end();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +0000441 i != e; ++i)
John McCalla729c622012-02-17 03:33:10 +0000442 argTypes.push_back(Context.getCanonicalParamType((*i)->getType()));
443
444 RequiredArgs required =
445 (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
Reid Kleckner4982b822014-01-31 22:54:50 +0000446 return arrangeLLVMFunctionInfo(GetReturnType(resultType), false, argTypes, info,
John McCall8dda7b22012-07-07 06:41:13 +0000447 required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000448}
449
John McCalla729c622012-02-17 03:33:10 +0000450const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Reid Kleckner4982b822014-01-31 22:54:50 +0000451 return arrangeLLVMFunctionInfo(getContext().VoidTy, false, None,
John McCall8dda7b22012-07-07 06:41:13 +0000452 FunctionType::ExtInfo(), RequiredArgs::All);
John McCalla738c252011-03-09 04:27:21 +0000453}
454
John McCalla729c622012-02-17 03:33:10 +0000455/// Arrange the argument and result information for an abstract value
456/// of a given function type. This is the method which all of the
457/// above functions ultimately defer to.
458const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000459CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Reid Kleckner4982b822014-01-31 22:54:50 +0000460 bool IsInstanceMethod,
John McCall8dda7b22012-07-07 06:41:13 +0000461 ArrayRef<CanQualType> argTypes,
462 FunctionType::ExtInfo info,
463 RequiredArgs required) {
John McCall2da83a32010-02-26 00:48:12 +0000464#ifndef NDEBUG
John McCalla729c622012-02-17 03:33:10 +0000465 for (ArrayRef<CanQualType>::const_iterator
466 I = argTypes.begin(), E = argTypes.end(); I != E; ++I)
John McCall2da83a32010-02-26 00:48:12 +0000467 assert(I->isCanonicalAsParam());
468#endif
469
John McCalla729c622012-02-17 03:33:10 +0000470 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
John McCallab26cfa2010-02-05 21:31:56 +0000471
Daniel Dunbare0be8292009-02-03 00:07:12 +0000472 // Lookup or create unique function info.
473 llvm::FoldingSetNodeID ID;
Reid Kleckner4982b822014-01-31 22:54:50 +0000474 CGFunctionInfo::Profile(ID, IsInstanceMethod, info, required, resultType,
475 argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000476
John McCalla729c622012-02-17 03:33:10 +0000477 void *insertPos = 0;
478 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000479 if (FI)
480 return *FI;
481
John McCalla729c622012-02-17 03:33:10 +0000482 // Construct the function info. We co-allocate the ArgInfos.
Reid Kleckner4982b822014-01-31 22:54:50 +0000483 FI = CGFunctionInfo::create(CC, IsInstanceMethod, info, resultType, argTypes,
484 required);
John McCalla729c622012-02-17 03:33:10 +0000485 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000486
John McCalla729c622012-02-17 03:33:10 +0000487 bool inserted = FunctionsBeingProcessed.insert(FI); (void)inserted;
488 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000489
Daniel Dunbar313321e2009-02-03 05:31:23 +0000490 // Compute ABI information.
Chris Lattner22326a12010-07-29 02:31:05 +0000491 getABIInfo().computeInfo(*FI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000492
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000493 // Loop over all of the computed argument and return value info. If any of
494 // them are direct or extend without a specified coerce type, specify the
495 // default now.
John McCalla729c622012-02-17 03:33:10 +0000496 ABIArgInfo &retInfo = FI->getReturnInfo();
497 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == 0)
498 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000499
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000500 for (auto &I : FI->arguments())
501 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == 0)
502 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000503
John McCalla729c622012-02-17 03:33:10 +0000504 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
505 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000506
Daniel Dunbare0be8292009-02-03 00:07:12 +0000507 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000508}
509
John McCalla729c622012-02-17 03:33:10 +0000510CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Reid Kleckner4982b822014-01-31 22:54:50 +0000511 bool IsInstanceMethod,
John McCalla729c622012-02-17 03:33:10 +0000512 const FunctionType::ExtInfo &info,
513 CanQualType resultType,
514 ArrayRef<CanQualType> argTypes,
515 RequiredArgs required) {
516 void *buffer = operator new(sizeof(CGFunctionInfo) +
517 sizeof(ArgInfo) * (argTypes.size() + 1));
518 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
519 FI->CallingConvention = llvmCC;
520 FI->EffectiveCallingConvention = llvmCC;
521 FI->ASTCallingConvention = info.getCC();
Reid Kleckner4982b822014-01-31 22:54:50 +0000522 FI->InstanceMethod = IsInstanceMethod;
John McCalla729c622012-02-17 03:33:10 +0000523 FI->NoReturn = info.getNoReturn();
524 FI->ReturnsRetained = info.getProducesResult();
525 FI->Required = required;
526 FI->HasRegParm = info.getHasRegParm();
527 FI->RegParm = info.getRegParm();
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000528 FI->ArgStruct = 0;
John McCalla729c622012-02-17 03:33:10 +0000529 FI->NumArgs = argTypes.size();
530 FI->getArgsBuffer()[0].type = resultType;
531 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
532 FI->getArgsBuffer()[i + 1].type = argTypes[i];
533 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000534}
535
536/***/
537
John McCall85dd2c52011-05-15 02:19:42 +0000538void CodeGenTypes::GetExpandedTypes(QualType type,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000539 SmallVectorImpl<llvm::Type*> &expandedTypes) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000540 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(type)) {
541 uint64_t NumElts = AT->getSize().getZExtValue();
542 for (uint64_t Elt = 0; Elt < NumElts; ++Elt)
543 GetExpandedTypes(AT->getElementType(), expandedTypes);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000544 } else if (const RecordType *RT = type->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000545 const RecordDecl *RD = RT->getDecl();
546 assert(!RD->hasFlexibleArrayMember() &&
547 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000548 if (RD->isUnion()) {
549 // Unions can be here only in degenerative cases - all the fields are same
550 // after flattening. Thus we have to use the "largest" field.
551 const FieldDecl *LargestFD = 0;
552 CharUnits UnionSize = CharUnits::Zero();
553
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000554 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000555 assert(!FD->isBitField() &&
556 "Cannot expand structure with bit-field members.");
557 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
558 if (UnionSize < FieldSize) {
559 UnionSize = FieldSize;
560 LargestFD = FD;
561 }
562 }
563 if (LargestFD)
564 GetExpandedTypes(LargestFD->getType(), expandedTypes);
565 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000566 for (const auto *I : RD->fields()) {
567 assert(!I->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000568 "Cannot expand structure with bit-field members.");
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000569 GetExpandedTypes(I->getType(), expandedTypes);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000570 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000571 }
572 } else if (const ComplexType *CT = type->getAs<ComplexType>()) {
573 llvm::Type *EltTy = ConvertType(CT->getElementType());
574 expandedTypes.push_back(EltTy);
575 expandedTypes.push_back(EltTy);
576 } else
577 expandedTypes.push_back(ConvertType(type));
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000578}
579
Mike Stump11289f42009-09-09 15:08:12 +0000580llvm::Function::arg_iterator
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000581CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
582 llvm::Function::arg_iterator AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000583 assert(LV.isSimple() &&
584 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000585
Bob Wilsone826a2a2011-08-03 05:58:22 +0000586 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
587 unsigned NumElts = AT->getSize().getZExtValue();
588 QualType EltTy = AT->getElementType();
589 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
Eli Friedman7f1ff602012-04-16 03:54:45 +0000590 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, Elt);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000591 LValue LV = MakeAddrLValue(EltAddr, EltTy);
592 AI = ExpandTypeFromArgs(EltTy, LV, AI);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000593 }
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000594 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +0000595 RecordDecl *RD = RT->getDecl();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000596 if (RD->isUnion()) {
597 // Unions can be here only in degenerative cases - all the fields are same
598 // after flattening. Thus we have to use the "largest" field.
599 const FieldDecl *LargestFD = 0;
600 CharUnits UnionSize = CharUnits::Zero();
Bob Wilsone826a2a2011-08-03 05:58:22 +0000601
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000602 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000603 assert(!FD->isBitField() &&
604 "Cannot expand structure with bit-field members.");
605 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
606 if (UnionSize < FieldSize) {
607 UnionSize = FieldSize;
608 LargestFD = FD;
609 }
610 }
611 if (LargestFD) {
612 // FIXME: What are the right qualifiers here?
Eli Friedman7f1ff602012-04-16 03:54:45 +0000613 LValue SubLV = EmitLValueForField(LV, LargestFD);
614 AI = ExpandTypeFromArgs(LargestFD->getType(), SubLV, AI);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000615 }
616 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000617 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000618 QualType FT = FD->getType();
619
620 // FIXME: What are the right qualifiers here?
Eli Friedman7f1ff602012-04-16 03:54:45 +0000621 LValue SubLV = EmitLValueForField(LV, FD);
622 AI = ExpandTypeFromArgs(FT, SubLV, AI);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000623 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000624 }
625 } else if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
626 QualType EltTy = CT->getElementType();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000627 llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real");
Bob Wilsone826a2a2011-08-03 05:58:22 +0000628 EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(RealAddr, EltTy));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000629 llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag");
Bob Wilsone826a2a2011-08-03 05:58:22 +0000630 EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(ImagAddr, EltTy));
631 } else {
632 EmitStoreThroughLValue(RValue::get(AI), LV);
633 ++AI;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000634 }
635
636 return AI;
637}
638
Chris Lattner895c52b2010-06-27 06:04:18 +0000639/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +0000640/// accessing some number of bytes out of it, try to gep into the struct to get
641/// at its inner goodness. Dive as deep as possible without entering an element
642/// with an in-memory size smaller than DstSize.
643static llvm::Value *
Chris Lattner895c52b2010-06-27 06:04:18 +0000644EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000645 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +0000646 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +0000647 // We can't dive into a zero-element struct.
648 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000649
Chris Lattner2192fe52011-07-18 04:24:23 +0000650 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000651
Chris Lattner1cd66982010-06-27 05:56:15 +0000652 // If the first elt is at least as large as what we're looking for, or if the
653 // first element is the same size as the whole struct, we can enter it.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000654 uint64_t FirstEltSize =
Micah Villmowdd31ca12012-10-08 16:25:52 +0000655 CGF.CGM.getDataLayout().getTypeAllocSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000656 if (FirstEltSize < DstSize &&
Micah Villmowdd31ca12012-10-08 16:25:52 +0000657 FirstEltSize < CGF.CGM.getDataLayout().getTypeAllocSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +0000658 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000659
Chris Lattner1cd66982010-06-27 05:56:15 +0000660 // GEP into the first element.
661 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000662
Chris Lattner1cd66982010-06-27 05:56:15 +0000663 // If the first element is a struct, recurse.
Chris Lattner2192fe52011-07-18 04:24:23 +0000664 llvm::Type *SrcTy =
Chris Lattner1cd66982010-06-27 05:56:15 +0000665 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000666 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +0000667 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000668
669 return SrcPtr;
670}
671
Chris Lattner055097f2010-06-27 06:26:04 +0000672/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
673/// are either integers or pointers. This does a truncation of the value if it
674/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000675///
676/// This behaves as if the value were coerced through memory, so on big-endian
677/// targets the high bits are preserved in a truncation, while little-endian
678/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +0000679static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +0000680 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +0000681 CodeGenFunction &CGF) {
682 if (Val->getType() == Ty)
683 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000684
Chris Lattner055097f2010-06-27 06:26:04 +0000685 if (isa<llvm::PointerType>(Val->getType())) {
686 // If this is Pointer->Pointer avoid conversion to and from int.
687 if (isa<llvm::PointerType>(Ty))
688 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000689
Chris Lattner055097f2010-06-27 06:26:04 +0000690 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +0000691 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +0000692 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000693
Chris Lattner2192fe52011-07-18 04:24:23 +0000694 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +0000695 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +0000696 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000697
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000698 if (Val->getType() != DestIntTy) {
699 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
700 if (DL.isBigEndian()) {
701 // Preserve the high bits on big-endian targets.
702 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +0000703 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
704 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
705
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000706 if (SrcSize > DstSize) {
707 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
708 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
709 } else {
710 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
711 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
712 }
713 } else {
714 // Little-endian targets preserve the low bits. No shifts required.
715 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
716 }
717 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000718
Chris Lattner055097f2010-06-27 06:26:04 +0000719 if (isa<llvm::PointerType>(Ty))
720 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
721 return Val;
722}
723
Chris Lattner1cd66982010-06-27 05:56:15 +0000724
725
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000726/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
727/// a pointer to an object of type \arg Ty.
728///
729/// This safely handles the case when the src type is smaller than the
730/// destination type; in this situation the values of bits which not
731/// present in the src are undefined.
732static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000733 llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000734 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000735 llvm::Type *SrcTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000736 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000737
Chris Lattnerd200eda2010-06-28 22:51:39 +0000738 // If SrcTy and Ty are the same, just do a load.
739 if (SrcTy == Ty)
740 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000741
Micah Villmowdd31ca12012-10-08 16:25:52 +0000742 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000743
Chris Lattner2192fe52011-07-18 04:24:23 +0000744 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000745 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000746 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
747 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000748
Micah Villmowdd31ca12012-10-08 16:25:52 +0000749 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000750
Chris Lattner055097f2010-06-27 06:26:04 +0000751 // If the source and destination are integer or pointer types, just do an
752 // extension or truncation to the desired type.
753 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
754 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
755 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
756 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
757 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000758
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000759 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000760 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +0000761 // Generally SrcSize is never greater than DstSize, since this means we are
762 // losing bits. However, this can happen in cases where the structure has
763 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000764 //
Mike Stump18bb9282009-05-16 07:57:57 +0000765 // FIXME: Assert that we aren't truncating non-padding bits when have access
766 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000767 llvm::Value *Casted =
768 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000769 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
770 // FIXME: Use better alignment / avoid requiring aligned load.
771 Load->setAlignment(1);
772 return Load;
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000773 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000774
Chris Lattner3fcc7902010-06-27 01:06:27 +0000775 // Otherwise do coercion through memory. This is stupid, but
776 // simple.
777 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
Manman Ren84b921f2012-11-28 22:08:52 +0000778 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
779 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
780 llvm::Value *SrcCasted = CGF.Builder.CreateBitCast(SrcPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000781 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000782 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
783 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
784 1, false);
Chris Lattner3fcc7902010-06-27 01:06:27 +0000785 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000786}
787
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000788// Function to store a first-class aggregate into memory. We prefer to
789// store the elements rather than the aggregate to be more friendly to
790// fast-isel.
791// FIXME: Do we need to recurse here?
792static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
793 llvm::Value *DestPtr, bool DestIsVolatile,
794 bool LowAlignment) {
795 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +0000796 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000797 dyn_cast<llvm::StructType>(Val->getType())) {
798 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
799 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
800 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
801 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
802 DestIsVolatile);
803 if (LowAlignment)
804 SI->setAlignment(1);
805 }
806 } else {
Bill Wendlingf6af30f2012-03-16 21:45:12 +0000807 llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
808 if (LowAlignment)
809 SI->setAlignment(1);
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000810 }
811}
812
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000813/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
814/// where the source and destination may have different types.
815///
816/// This safely handles the case when the src type is larger than the
817/// destination type; the upper bits of the src will be lost.
818static void CreateCoercedStore(llvm::Value *Src,
819 llvm::Value *DstPtr,
Anders Carlsson17490832009-12-24 20:40:36 +0000820 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000821 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000822 llvm::Type *SrcTy = Src->getType();
823 llvm::Type *DstTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000824 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +0000825 if (SrcTy == DstTy) {
826 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
827 return;
828 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000829
Micah Villmowdd31ca12012-10-08 16:25:52 +0000830 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000831
Chris Lattner2192fe52011-07-18 04:24:23 +0000832 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000833 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
834 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
835 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000836
Chris Lattner055097f2010-06-27 06:26:04 +0000837 // If the source and destination are integer or pointer types, just do an
838 // extension or truncation to the desired type.
839 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
840 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
841 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
842 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
843 return;
844 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000845
Micah Villmowdd31ca12012-10-08 16:25:52 +0000846 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000847
Daniel Dunbar313321e2009-02-03 05:31:23 +0000848 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000849 if (SrcSize <= DstSize) {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000850 llvm::Value *Casted =
851 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000852 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000853 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000854 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000855 // Otherwise do coercion through memory. This is stupid, but
856 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +0000857
858 // Generally SrcSize is never greater than DstSize, since this means we are
859 // losing bits. However, this can happen in cases where the structure has
860 // additional padding, for example due to a user specified alignment.
861 //
862 // FIXME: Assert that we aren't truncating non-padding bits when have access
863 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000864 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
865 CGF.Builder.CreateStore(Src, Tmp);
Manman Ren84b921f2012-11-28 22:08:52 +0000866 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
867 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
868 llvm::Value *DstCasted = CGF.Builder.CreateBitCast(DstPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000869 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000870 CGF.Builder.CreateMemCpy(DstCasted, Casted,
871 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
872 1, false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000873 }
874}
875
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000876/***/
877
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000878bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000879 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +0000880}
881
Tim Northovere77cc392014-03-29 13:28:05 +0000882bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
883 return ReturnTypeUsesSRet(FI) &&
884 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
885}
886
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000887bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
888 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
889 switch (BT->getKind()) {
890 default:
891 return false;
892 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +0000893 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000894 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +0000895 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000896 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +0000897 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +0000898 }
899 }
900
901 return false;
902}
903
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000904bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
905 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
906 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
907 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +0000908 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +0000909 }
910 }
911
912 return false;
913}
914
Chris Lattnera5f58b02011-07-09 17:41:47 +0000915llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +0000916 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
917 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +0000918}
919
Chris Lattnera5f58b02011-07-09 17:41:47 +0000920llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +0000921CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000922
923 bool Inserted = FunctionsBeingProcessed.insert(&FI); (void)Inserted;
924 assert(Inserted && "Recursively being processed?");
925
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000926 SmallVector<llvm::Type*, 8> argTypes;
Chris Lattner2192fe52011-07-18 04:24:23 +0000927 llvm::Type *resultType = 0;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000928
John McCall85dd2c52011-05-15 02:19:42 +0000929 const ABIArgInfo &retAI = FI.getReturnInfo();
930 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +0000931 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +0000932 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +0000933
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000934 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +0000935 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +0000936 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +0000937 break;
938
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000939 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +0000940 if (retAI.getInAllocaSRet()) {
941 // sret things on win32 aren't void, they return the sret pointer.
942 QualType ret = FI.getReturnType();
943 llvm::Type *ty = ConvertType(ret);
944 unsigned addressSpace = Context.getTargetAddressSpace(ret);
945 resultType = llvm::PointerType::get(ty, addressSpace);
946 } else {
947 resultType = llvm::Type::getVoidTy(getLLVMContext());
948 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000949 break;
950
Daniel Dunbarb8b1c672009-02-05 08:00:50 +0000951 case ABIArgInfo::Indirect: {
John McCall85dd2c52011-05-15 02:19:42 +0000952 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
953 resultType = llvm::Type::getVoidTy(getLLVMContext());
954
955 QualType ret = FI.getReturnType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000956 llvm::Type *ty = ConvertType(ret);
John McCall85dd2c52011-05-15 02:19:42 +0000957 unsigned addressSpace = Context.getTargetAddressSpace(ret);
958 argTypes.push_back(llvm::PointerType::get(ty, addressSpace));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000959 break;
960 }
961
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000962 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +0000963 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000964 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000965 }
Mike Stump11289f42009-09-09 15:08:12 +0000966
John McCallc818bbb2012-12-07 07:03:17 +0000967 // Add in all of the required arguments.
968 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), ie;
969 if (FI.isVariadic()) {
970 ie = it + FI.getRequiredArgs().getNumRequiredArgs();
971 } else {
972 ie = FI.arg_end();
973 }
974 for (; it != ie; ++it) {
John McCall85dd2c52011-05-15 02:19:42 +0000975 const ABIArgInfo &argAI = it->info;
Mike Stump11289f42009-09-09 15:08:12 +0000976
Rafael Espindolafad28de2012-10-24 01:59:00 +0000977 // Insert a padding type to ensure proper alignment.
978 if (llvm::Type *PaddingType = argAI.getPaddingType())
979 argTypes.push_back(PaddingType);
980
John McCall85dd2c52011-05-15 02:19:42 +0000981 switch (argAI.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000982 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000983 case ABIArgInfo::InAlloca:
Daniel Dunbar94a6f252009-01-26 21:26:08 +0000984 break;
985
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000986 case ABIArgInfo::Indirect: {
987 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +0000988 llvm::Type *LTy = ConvertTypeForMem(it->type);
John McCall85dd2c52011-05-15 02:19:42 +0000989 argTypes.push_back(LTy->getPointerTo());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000990 break;
991 }
992
993 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +0000994 case ABIArgInfo::Direct: {
Chris Lattner3dd716c2010-06-28 23:44:11 +0000995 // If the coerce-to type is a first class aggregate, flatten it. Either
996 // way is semantically identical, but fast-isel and the optimizer
997 // generally likes scalar values better than FCAs.
Chris Lattnera5f58b02011-07-09 17:41:47 +0000998 llvm::Type *argType = argAI.getCoerceToType();
James Molloy1aa0d5f2014-05-09 16:17:09 +0000999 if (llvm::StructType *st = dyn_cast<llvm::StructType>(argType)) {
John McCall85dd2c52011-05-15 02:19:42 +00001000 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
1001 argTypes.push_back(st->getElementType(i));
Chris Lattner3dd716c2010-06-28 23:44:11 +00001002 } else {
John McCall85dd2c52011-05-15 02:19:42 +00001003 argTypes.push_back(argType);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001004 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001005 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001006 }
Mike Stump11289f42009-09-09 15:08:12 +00001007
Daniel Dunbard3674e62008-09-11 01:48:57 +00001008 case ABIArgInfo::Expand:
Chris Lattnera5f58b02011-07-09 17:41:47 +00001009 GetExpandedTypes(it->type, argTypes);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001010 break;
1011 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001012 }
1013
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001014 // Add the inalloca struct as the last parameter type.
1015 if (llvm::StructType *ArgStruct = FI.getArgStruct())
1016 argTypes.push_back(ArgStruct->getPointerTo());
1017
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001018 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1019 assert(Erased && "Not in set?");
1020
John McCalla729c622012-02-17 03:33:10 +00001021 return llvm::FunctionType::get(resultType, argTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001022}
1023
Chris Lattner2192fe52011-07-18 04:24:23 +00001024llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001025 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001026 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001027
Chris Lattner8806e322011-07-10 00:18:59 +00001028 if (!isFuncTypeConvertible(FPT))
1029 return llvm::StructType::get(getLLVMContext());
1030
1031 const CGFunctionInfo *Info;
1032 if (isa<CXXDestructorDecl>(MD))
John McCalla729c622012-02-17 03:33:10 +00001033 Info = &arrangeCXXDestructor(cast<CXXDestructorDecl>(MD), GD.getDtorType());
Chris Lattner8806e322011-07-10 00:18:59 +00001034 else
John McCalla729c622012-02-17 03:33:10 +00001035 Info = &arrangeCXXMethodDeclaration(MD);
1036 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001037}
1038
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001039void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbard931a872009-02-02 22:03:45 +00001040 const Decl *TargetDecl,
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001041 AttributeListType &PAL,
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00001042 unsigned &CallingConv,
1043 bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001044 llvm::AttrBuilder FuncAttrs;
1045 llvm::AttrBuilder RetAttrs;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001046
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001047 CallingConv = FI.getEffectiveCallingConvention();
1048
John McCallab26cfa2010-02-05 21:31:56 +00001049 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001050 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001051
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001052 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001053 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001054 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001055 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001056 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001057 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001058 if (TargetDecl->hasAttr<NoReturnAttr>())
1059 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001060 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1061 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smithdebc59d2013-01-30 05:45:05 +00001062
1063 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
John McCallbe349de2010-07-08 06:48:12 +00001064 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl31ad7542011-03-13 17:09:40 +00001065 if (FPT && FPT->isNothrow(getContext()))
Bill Wendling207f0532012-12-20 19:27:06 +00001066 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith49af6292013-03-05 08:30:04 +00001067 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1068 // These attributes are not inherited by overloads.
1069 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1070 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001071 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001072 }
1073
Eric Christopherbf005ec2011-08-15 22:38:22 +00001074 // 'const' and 'pure' attribute functions are also nounwind.
1075 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001076 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1077 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001078 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001079 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1080 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001081 }
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001082 if (TargetDecl->hasAttr<MallocAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001083 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001084 }
1085
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001086 if (CodeGenOpts.OptimizeSize)
Bill Wendling207f0532012-12-20 19:27:06 +00001087 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
Quentin Colombet5ee5ca12012-10-26 00:29:48 +00001088 if (CodeGenOpts.OptimizeSize == 2)
Bill Wendling207f0532012-12-20 19:27:06 +00001089 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001090 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001091 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001092 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001093 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Reid Klecknerfb873af2014-04-10 22:59:13 +00001094 if (CodeGenOpts.EnableSegmentedStacks)
1095 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001096
Bill Wendling2f81db62013-02-22 20:53:29 +00001097 if (AttrOnCallSite) {
1098 // Attributes that should go on the call site only.
1099 if (!CodeGenOpts.SimplifyLibCalls)
1100 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Bill Wendling706469b2013-02-28 22:49:57 +00001101 } else {
1102 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001103 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001104 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001105 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001106 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001107 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001108 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001109 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001110 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001111 }
1112
Bill Wendlingdabafea2013-03-13 22:24:33 +00001113 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001114 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001115 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001116 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001117 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001118 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001119 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001120 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001121 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001122 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001123 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001124 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001125
Bill Wendlingd8f49502013-08-01 21:41:02 +00001126 if (!CodeGenOpts.StackRealignment)
1127 FuncAttrs.addAttribute("no-realign-stack");
Bill Wendling985d1c52013-02-15 21:30:01 +00001128 }
1129
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001130 QualType RetTy = FI.getReturnType();
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001131 unsigned Index = 1;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001132 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001133 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001134 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001135 if (RetTy->hasSignedIntegerRepresentation())
1136 RetAttrs.addAttribute(llvm::Attribute::SExt);
1137 else if (RetTy->hasUnsignedIntegerRepresentation())
1138 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001139 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001140 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001141 if (RetAI.getInReg())
1142 RetAttrs.addAttribute(llvm::Attribute::InReg);
1143 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001144 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001145 break;
1146
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001147 case ABIArgInfo::InAlloca: {
1148 // inalloca disables readnone and readonly
1149 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1150 .removeAttribute(llvm::Attribute::ReadNone);
1151 break;
1152 }
1153
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001154 case ABIArgInfo::Indirect: {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001155 llvm::AttrBuilder SRETAttrs;
Bill Wendling207f0532012-12-20 19:27:06 +00001156 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001157 if (RetAI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001158 SRETAttrs.addAttribute(llvm::Attribute::InReg);
Bill Wendlinga7912f82012-10-10 07:36:56 +00001159 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001160 AttributeSet::get(getLLVMContext(), Index, SRETAttrs));
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001161
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001162 ++Index;
Daniel Dunbarc2304432009-03-18 19:51:01 +00001163 // sret disables readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001164 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1165 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001166 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001167 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001168
Daniel Dunbard3674e62008-09-11 01:48:57 +00001169 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001170 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001171 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001172
Bill Wendlinga7912f82012-10-10 07:36:56 +00001173 if (RetAttrs.hasAttributes())
1174 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001175 AttributeSet::get(getLLVMContext(),
1176 llvm::AttributeSet::ReturnIndex,
1177 RetAttrs));
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001178
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001179 for (const auto &I : FI.arguments()) {
1180 QualType ParamType = I.type;
1181 const ABIArgInfo &AI = I.info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001182 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001183
Rafael Espindolafad28de2012-10-24 01:59:00 +00001184 if (AI.getPaddingType()) {
Bill Wendling290d9522013-01-27 02:46:53 +00001185 if (AI.getPaddingInReg())
1186 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index,
1187 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001188 // Increment Index if there is padding.
1189 ++Index;
1190 }
1191
John McCall39ec71f2010-03-27 00:47:27 +00001192 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1193 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001194 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001195 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001196 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001197 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001198 Attrs.addAttribute(llvm::Attribute::SExt);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001199 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001200 Attrs.addAttribute(llvm::Attribute::ZExt);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001201 // FALL THROUGH
James Molloy1aa0d5f2014-05-09 16:17:09 +00001202 case ABIArgInfo::Direct:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001203 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001204 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001205
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001206 // FIXME: handle sseregparm someday...
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001207
James Molloy1aa0d5f2014-05-09 16:17:09 +00001208 if (llvm::StructType *STy =
1209 dyn_cast<llvm::StructType>(AI.getCoerceToType())) {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001210 unsigned Extra = STy->getNumElements()-1; // 1 will be added below.
Bill Wendlinga7912f82012-10-10 07:36:56 +00001211 if (Attrs.hasAttributes())
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001212 for (unsigned I = 0; I < Extra; ++I)
Bill Wendling290d9522013-01-27 02:46:53 +00001213 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index + I,
1214 Attrs));
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001215 Index += Extra;
1216 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001217 break;
James Molloy1aa0d5f2014-05-09 16:17:09 +00001218
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001219 case ABIArgInfo::Indirect:
Rafael Espindola703c47f2012-10-19 05:04:37 +00001220 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001221 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001222
Anders Carlsson20759ad2009-09-16 15:53:40 +00001223 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001224 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001225
Bill Wendlinga7912f82012-10-10 07:36:56 +00001226 Attrs.addAlignmentAttr(AI.getIndirectAlign());
1227
Daniel Dunbarc2304432009-03-18 19:51:01 +00001228 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001229 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1230 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001231 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001232
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001233 case ABIArgInfo::Ignore:
1234 // Skip increment, no matching LLVM parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001235 continue;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001236
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001237 case ABIArgInfo::InAlloca:
1238 // inalloca disables readnone and readonly.
1239 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1240 .removeAttribute(llvm::Attribute::ReadNone);
1241 // Skip increment, no matching LLVM parameter.
1242 continue;
1243
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001244 case ABIArgInfo::Expand: {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001245 SmallVector<llvm::Type*, 8> types;
Mike Stump18bb9282009-05-16 07:57:57 +00001246 // FIXME: This is rather inefficient. Do we ever actually need to do
1247 // anything here? The result should be just reconstructed on the other
1248 // side, so extension should be a non-issue.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001249 getTypes().GetExpandedTypes(ParamType, types);
John McCall85dd2c52011-05-15 02:19:42 +00001250 Index += types.size();
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001251 continue;
1252 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001253 }
Mike Stump11289f42009-09-09 15:08:12 +00001254
Bill Wendlinga7912f82012-10-10 07:36:56 +00001255 if (Attrs.hasAttributes())
Bill Wendling290d9522013-01-27 02:46:53 +00001256 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index, Attrs));
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001257 ++Index;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001258 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001259
1260 // Add the inalloca attribute to the trailing inalloca parameter if present.
1261 if (FI.usesInAlloca()) {
1262 llvm::AttrBuilder Attrs;
1263 Attrs.addAttribute(llvm::Attribute::InAlloca);
1264 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index, Attrs));
1265 }
1266
Bill Wendlinga7912f82012-10-10 07:36:56 +00001267 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001268 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001269 AttributeSet::get(getLLVMContext(),
1270 llvm::AttributeSet::FunctionIndex,
1271 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001272}
1273
John McCalla738c252011-03-09 04:27:21 +00001274/// An argument came in as a promoted argument; demote it back to its
1275/// declared type.
1276static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1277 const VarDecl *var,
1278 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001279 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001280
1281 // This can happen with promotions that actually don't change the
1282 // underlying type, like the enum promotions.
1283 if (value->getType() == varType) return value;
1284
1285 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1286 && "unexpected promotion type");
1287
1288 if (isa<llvm::IntegerType>(varType))
1289 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1290
1291 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1292}
1293
Daniel Dunbard931a872009-02-02 22:03:45 +00001294void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1295 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00001296 const FunctionArgList &Args) {
John McCallcaa19452009-07-28 01:00:58 +00001297 // If this is an implicit-return-zero function, go ahead and
1298 // initialize the return value. TODO: it might be nice to have
1299 // a more general mechanism for this that didn't require synthesized
1300 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00001301 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00001302 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00001303 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001304 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00001305 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00001306 Builder.CreateStore(Zero, ReturnValue);
1307 }
1308 }
1309
Mike Stump18bb9282009-05-16 07:57:57 +00001310 // FIXME: We no longer need the types from FunctionArgList; lift up and
1311 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00001312
Daniel Dunbar613855c2008-09-09 23:27:19 +00001313 // Emit allocs for param decls. Give the LLVM Argument nodes names.
1314 llvm::Function::arg_iterator AI = Fn->arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00001315
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001316 // If we're using inalloca, all the memory arguments are GEPs off of the last
1317 // parameter, which is a pointer to the complete memory area.
1318 llvm::Value *ArgStruct = 0;
1319 if (FI.usesInAlloca()) {
1320 llvm::Function::arg_iterator EI = Fn->arg_end();
1321 --EI;
1322 ArgStruct = EI;
1323 assert(ArgStruct->getType() == FI.getArgStruct()->getPointerTo());
1324 }
1325
Daniel Dunbar613855c2008-09-09 23:27:19 +00001326 // Name the struct return argument.
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001327 if (CGM.ReturnTypeUsesSRet(FI)) {
Daniel Dunbar613855c2008-09-09 23:27:19 +00001328 AI->setName("agg.result");
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001329 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1330 AI->getArgNo() + 1,
1331 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00001332 ++AI;
1333 }
Mike Stump11289f42009-09-09 15:08:12 +00001334
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001335 // Track if we received the parameter as a pointer (indirect, byval, or
1336 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
1337 // into a local alloca for us.
1338 enum ValOrPointer { HaveValue = 0, HavePointer = 1 };
Reid Kleckner8ae16272014-02-01 00:23:22 +00001339 typedef llvm::PointerIntPair<llvm::Value *, 1> ValueAndIsPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001340 SmallVector<ValueAndIsPtr, 16> ArgVals;
1341 ArgVals.reserve(Args.size());
1342
Reid Kleckner739756c2013-12-04 19:23:12 +00001343 // Create a pointer value for every parameter declaration. This usually
1344 // entails copying one or more LLVM IR arguments into an alloca. Don't push
1345 // any cleanups or do anything that might unwind. We do that separately, so
1346 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00001347 assert(FI.arg_size() == Args.size() &&
1348 "Mismatch between function signature & arguments.");
Devang Patel68a15252011-03-03 20:13:15 +00001349 unsigned ArgNo = 1;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001350 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Devang Patel68a15252011-03-03 20:13:15 +00001351 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
1352 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00001353 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001354 QualType Ty = info_it->type;
1355 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001356
John McCalla738c252011-03-09 04:27:21 +00001357 bool isPromoted =
1358 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1359
Rafael Espindolafad28de2012-10-24 01:59:00 +00001360 // Skip the dummy padding argument.
1361 if (ArgI.getPaddingType())
1362 ++AI;
1363
Daniel Dunbard3674e62008-09-11 01:48:57 +00001364 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001365 case ABIArgInfo::InAlloca: {
1366 llvm::Value *V = Builder.CreateStructGEP(
1367 ArgStruct, ArgI.getInAllocaFieldIndex(), Arg->getName());
1368 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
1369 continue; // Don't increment AI!
1370 }
1371
Daniel Dunbar747865a2009-02-05 09:16:39 +00001372 case ABIArgInfo::Indirect: {
Chris Lattner3dd716c2010-06-28 23:44:11 +00001373 llvm::Value *V = AI;
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001374
John McCall47fb9502013-03-07 21:37:08 +00001375 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001376 // Aggregates and complex variables are accessed by reference. All we
1377 // need to do is realign the value, if requested
1378 if (ArgI.getIndirectRealign()) {
1379 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1380
1381 // Copy from the incoming argument pointer to the temporary with the
1382 // appropriate alignment.
1383 //
1384 // FIXME: We should have a common utility for generating an aggregate
1385 // copy.
Chris Lattner2192fe52011-07-18 04:24:23 +00001386 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyck705ba072011-01-19 01:58:38 +00001387 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumidd634362011-03-10 14:02:21 +00001388 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1389 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1390 Builder.CreateMemCpy(Dst,
1391 Src,
Ken Dyck705ba072011-01-19 01:58:38 +00001392 llvm::ConstantInt::get(IntPtrTy,
1393 Size.getQuantity()),
Benjamin Krameracc6b4e2010-12-30 00:13:21 +00001394 ArgI.getIndirectAlign(),
1395 false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001396 V = AlignedTemp;
1397 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001398 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001399 } else {
1400 // Load scalar value from indirect argument.
Ken Dyck705ba072011-01-19 01:58:38 +00001401 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
Nick Lewycky2d84e842013-10-02 02:29:49 +00001402 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty,
1403 Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001404
1405 if (isPromoted)
1406 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001407 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001408 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00001409 break;
1410 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001411
1412 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001413 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00001414
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001415 // If we have the trivial case, handle it with no muss and fuss.
1416 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001417 ArgI.getCoerceToType() == ConvertType(Ty) &&
1418 ArgI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001419 assert(AI != Fn->arg_end() && "Argument mismatch!");
1420 llvm::Value *V = AI;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001421
Bill Wendling507c3512012-10-16 05:23:44 +00001422 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001423 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1424 AI->getArgNo() + 1,
1425 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00001426
Chris Lattner7369c142011-07-20 06:29:00 +00001427 // Ensure the argument is the correct type.
1428 if (V->getType() != ArgI.getCoerceToType())
1429 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1430
John McCalla738c252011-03-09 04:27:21 +00001431 if (isPromoted)
1432 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00001433
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001434 if (const CXXMethodDecl *MD =
1435 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001436 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001437 V = CGM.getCXXABI().
1438 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001439 }
1440
Rafael Espindola8778c282012-11-29 16:09:03 +00001441 // Because of merging of function types from multiple decls it is
1442 // possible for the type of an argument to not match the corresponding
1443 // type in the function type. Since we are codegening the callee
1444 // in here, add a cast to the argument type.
1445 llvm::Type *LTy = ConvertType(Arg->getType());
1446 if (V->getType() != LTy)
1447 V = Builder.CreateBitCast(V, LTy);
1448
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001449 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001450 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00001451 }
Mike Stump11289f42009-09-09 15:08:12 +00001452
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001453 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001454
Chris Lattnerff941a62010-07-28 18:24:28 +00001455 // The alignment we need to use is the max of the requested alignment for
1456 // the argument plus the alignment required by our access code below.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001457 unsigned AlignmentToUse =
Micah Villmowdd31ca12012-10-08 16:25:52 +00001458 CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerff941a62010-07-28 18:24:28 +00001459 AlignmentToUse = std::max(AlignmentToUse,
1460 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001461
Chris Lattnerff941a62010-07-28 18:24:28 +00001462 Alloca->setAlignment(AlignmentToUse);
Chris Lattnerc401de92010-07-05 20:21:00 +00001463 llvm::Value *V = Alloca;
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001464 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001465
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001466 // If the value is offset in memory, apply the offset now.
1467 if (unsigned Offs = ArgI.getDirectOffset()) {
1468 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1469 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001470 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001471 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1472 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001473
Chris Lattner15ec3612010-06-29 00:06:42 +00001474 // If the coerce-to type is a first class aggregate, we flatten it and
1475 // pass the elements. Either way is semantically identical, but fast-isel
1476 // and the optimizer generally likes scalar values better than FCAs.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001477 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
James Molloy1aa0d5f2014-05-09 16:17:09 +00001478 if (STy && STy->getNumElements() > 1) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001479 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001480 llvm::Type *DstTy =
1481 cast<llvm::PointerType>(Ptr->getType())->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00001482 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001483
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001484 if (SrcSize <= DstSize) {
1485 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1486
1487 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1488 assert(AI != Fn->arg_end() && "Argument mismatch!");
1489 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1490 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
1491 Builder.CreateStore(AI++, EltPtr);
1492 }
1493 } else {
1494 llvm::AllocaInst *TempAlloca =
1495 CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1496 TempAlloca->setAlignment(AlignmentToUse);
1497 llvm::Value *TempV = TempAlloca;
1498
1499 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1500 assert(AI != Fn->arg_end() && "Argument mismatch!");
1501 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1502 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(TempV, 0, i);
1503 Builder.CreateStore(AI++, EltPtr);
1504 }
1505
1506 Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
Chris Lattner15ec3612010-06-29 00:06:42 +00001507 }
1508 } else {
1509 // Simple case, just do a coerced store of the argument into the alloca.
1510 assert(AI != Fn->arg_end() && "Argument mismatch!");
Chris Lattner9e748e92010-06-29 00:14:52 +00001511 AI->setName(Arg->getName() + ".coerce");
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001512 CreateCoercedStore(AI++, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00001513 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001514
1515
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001516 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00001517 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001518 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001519 if (isPromoted)
1520 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001521 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
1522 } else {
1523 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00001524 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00001525 continue; // Skip ++AI increment, already done.
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001526 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001527
1528 case ABIArgInfo::Expand: {
1529 // If this structure was expanded into multiple arguments then
1530 // we need to create a temporary and reconstruct it from the
1531 // arguments.
Eli Friedman3d9f47f2011-11-03 21:39:02 +00001532 llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
Eli Friedmana0544d62011-12-03 04:14:32 +00001533 CharUnits Align = getContext().getDeclAlign(Arg);
1534 Alloca->setAlignment(Align.getQuantity());
1535 LValue LV = MakeAddrLValue(Alloca, Ty, Align);
Eli Friedman3d9f47f2011-11-03 21:39:02 +00001536 llvm::Function::arg_iterator End = ExpandTypeFromArgs(Ty, LV, AI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001537 ArgVals.push_back(ValueAndIsPtr(Alloca, HavePointer));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001538
1539 // Name the arguments used in expansion and increment AI.
1540 unsigned Index = 0;
1541 for (; AI != End; ++AI, ++Index)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001542 AI->setName(Arg->getName() + "." + Twine(Index));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001543 continue;
1544 }
1545
1546 case ABIArgInfo::Ignore:
1547 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001548 if (!hasScalarEvaluationKind(Ty)) {
1549 ArgVals.push_back(ValueAndIsPtr(CreateMemTemp(Ty), HavePointer));
1550 } else {
1551 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
1552 ArgVals.push_back(ValueAndIsPtr(U, HaveValue));
1553 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001554
1555 // Skip increment, no matching LLVM parameter.
1556 continue;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001557 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001558
1559 ++AI;
Daniel Dunbar613855c2008-09-09 23:27:19 +00001560 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001561
1562 if (FI.usesInAlloca())
1563 ++AI;
Daniel Dunbar613855c2008-09-09 23:27:19 +00001564 assert(AI == Fn->arg_end() && "Argument mismatch!");
Reid Kleckner739756c2013-12-04 19:23:12 +00001565
1566 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1567 for (int I = Args.size() - 1; I >= 0; --I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001568 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1569 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00001570 } else {
1571 for (unsigned I = 0, E = Args.size(); I != E; ++I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001572 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1573 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00001574 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00001575}
1576
John McCallffa2c1a2012-01-29 07:46:59 +00001577static void eraseUnusedBitCasts(llvm::Instruction *insn) {
1578 while (insn->use_empty()) {
1579 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
1580 if (!bitcast) return;
1581
1582 // This is "safe" because we would have used a ConstantExpr otherwise.
1583 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
1584 bitcast->eraseFromParent();
1585 }
1586}
1587
John McCall31168b02011-06-15 23:02:42 +00001588/// Try to emit a fused autorelease of a return result.
1589static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
1590 llvm::Value *result) {
1591 // We must be immediately followed the cast.
1592 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
1593 if (BB->empty()) return 0;
1594 if (&BB->back() != result) return 0;
1595
Chris Lattner2192fe52011-07-18 04:24:23 +00001596 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00001597
1598 // result is in a BasicBlock and is therefore an Instruction.
1599 llvm::Instruction *generator = cast<llvm::Instruction>(result);
1600
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001601 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00001602
1603 // Look for:
1604 // %generator = bitcast %type1* %generator2 to %type2*
1605 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
1606 // We would have emitted this as a constant if the operand weren't
1607 // an Instruction.
1608 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
1609
1610 // Require the generator to be immediately followed by the cast.
1611 if (generator->getNextNode() != bitcast)
1612 return 0;
1613
1614 insnsToKill.push_back(bitcast);
1615 }
1616
1617 // Look for:
1618 // %generator = call i8* @objc_retain(i8* %originalResult)
1619 // or
1620 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
1621 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
1622 if (!call) return 0;
1623
1624 bool doRetainAutorelease;
1625
1626 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
1627 doRetainAutorelease = true;
1628 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
1629 .objc_retainAutoreleasedReturnValue) {
1630 doRetainAutorelease = false;
1631
John McCallcfa4e9b2012-09-07 23:30:50 +00001632 // If we emitted an assembly marker for this call (and the
1633 // ARCEntrypoints field should have been set if so), go looking
1634 // for that call. If we can't find it, we can't do this
1635 // optimization. But it should always be the immediately previous
1636 // instruction, unless we needed bitcasts around the call.
1637 if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
1638 llvm::Instruction *prev = call->getPrevNode();
1639 assert(prev);
1640 if (isa<llvm::BitCastInst>(prev)) {
1641 prev = prev->getPrevNode();
1642 assert(prev);
1643 }
1644 assert(isa<llvm::CallInst>(prev));
1645 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
1646 CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
1647 insnsToKill.push_back(prev);
1648 }
John McCall31168b02011-06-15 23:02:42 +00001649 } else {
1650 return 0;
1651 }
1652
1653 result = call->getArgOperand(0);
1654 insnsToKill.push_back(call);
1655
1656 // Keep killing bitcasts, for sanity. Note that we no longer care
1657 // about precise ordering as long as there's exactly one use.
1658 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
1659 if (!bitcast->hasOneUse()) break;
1660 insnsToKill.push_back(bitcast);
1661 result = bitcast->getOperand(0);
1662 }
1663
1664 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001665 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00001666 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
1667 (*i)->eraseFromParent();
1668
1669 // Do the fused retain/autorelease if we were asked to.
1670 if (doRetainAutorelease)
1671 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
1672
1673 // Cast back to the result type.
1674 return CGF.Builder.CreateBitCast(result, resultType);
1675}
1676
John McCallffa2c1a2012-01-29 07:46:59 +00001677/// If this is a +1 of the value of an immutable 'self', remove it.
1678static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
1679 llvm::Value *result) {
1680 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00001681 const ObjCMethodDecl *method =
1682 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCallffa2c1a2012-01-29 07:46:59 +00001683 if (!method) return 0;
1684 const VarDecl *self = method->getSelfDecl();
1685 if (!self->getType().isConstQualified()) return 0;
1686
1687 // Look for a retain call.
1688 llvm::CallInst *retainCall =
1689 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
1690 if (!retainCall ||
1691 retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
1692 return 0;
1693
1694 // Look for an ordinary load of 'self'.
1695 llvm::Value *retainedValue = retainCall->getArgOperand(0);
1696 llvm::LoadInst *load =
1697 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
1698 if (!load || load->isAtomic() || load->isVolatile() ||
1699 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
1700 return 0;
1701
1702 // Okay! Burn it all down. This relies for correctness on the
1703 // assumption that the retain is emitted as part of the return and
1704 // that thereafter everything is used "linearly".
1705 llvm::Type *resultType = result->getType();
1706 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
1707 assert(retainCall->use_empty());
1708 retainCall->eraseFromParent();
1709 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
1710
1711 return CGF.Builder.CreateBitCast(load, resultType);
1712}
1713
John McCall31168b02011-06-15 23:02:42 +00001714/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00001715///
1716/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00001717static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
1718 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00001719 // If we're returning 'self', kill the initial retain. This is a
1720 // heuristic attempt to "encourage correctness" in the really unfortunate
1721 // case where we have a return of self during a dealloc and we desperately
1722 // need to avoid the possible autorelease.
1723 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
1724 return self;
1725
John McCall31168b02011-06-15 23:02:42 +00001726 // At -O0, try to emit a fused retain/autorelease.
1727 if (CGF.shouldUseFusedARCCalls())
1728 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
1729 return fused;
1730
1731 return CGF.EmitARCAutoreleaseReturnValue(result);
1732}
1733
John McCall6e1c0122012-01-29 02:35:02 +00001734/// Heuristically search for a dominating store to the return-value slot.
1735static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
1736 // If there are multiple uses of the return-value slot, just check
1737 // for something immediately preceding the IP. Sometimes this can
1738 // happen with how we generate implicit-returns; it can also happen
1739 // with noreturn cleanups.
1740 if (!CGF.ReturnValue->hasOneUse()) {
1741 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
1742 if (IP->empty()) return 0;
1743 llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back());
1744 if (!store) return 0;
1745 if (store->getPointerOperand() != CGF.ReturnValue) return 0;
1746 assert(!store->isAtomic() && !store->isVolatile()); // see below
1747 return store;
1748 }
1749
1750 llvm::StoreInst *store =
Chandler Carruth4d01fff2014-03-09 03:16:50 +00001751 dyn_cast<llvm::StoreInst>(CGF.ReturnValue->user_back());
John McCall6e1c0122012-01-29 02:35:02 +00001752 if (!store) return 0;
1753
1754 // These aren't actually possible for non-coerced returns, and we
1755 // only care about non-coerced returns on this code path.
1756 assert(!store->isAtomic() && !store->isVolatile());
1757
1758 // Now do a first-and-dirty dominance check: just walk up the
1759 // single-predecessors chain from the current insertion point.
1760 llvm::BasicBlock *StoreBB = store->getParent();
1761 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
1762 while (IP != StoreBB) {
1763 if (!(IP = IP->getSinglePredecessor()))
1764 return 0;
1765 }
1766
1767 // Okay, the store's basic block dominates the insertion point; we
1768 // can do our thing.
1769 return store;
1770}
1771
Adrian Prantl3be10542013-05-02 17:30:20 +00001772void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001773 bool EmitRetDbgLoc,
1774 SourceLocation EndLoc) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001775 // Functions with no result always return void.
Chris Lattner726b3d02010-06-26 23:13:19 +00001776 if (ReturnValue == 0) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001777 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00001778 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001779 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00001780
Dan Gohman481e40c2010-07-20 20:13:52 +00001781 llvm::DebugLoc RetDbgLoc;
Chris Lattner726b3d02010-06-26 23:13:19 +00001782 llvm::Value *RV = 0;
1783 QualType RetTy = FI.getReturnType();
1784 const ABIArgInfo &RetAI = FI.getReturnInfo();
1785
1786 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001787 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001788 // Aggregrates get evaluated directly into the destination. Sometimes we
1789 // need to return the sret value in a register, though.
1790 assert(hasAggregateEvaluationKind(RetTy));
1791 if (RetAI.getInAllocaSRet()) {
1792 llvm::Function::arg_iterator EI = CurFn->arg_end();
1793 --EI;
1794 llvm::Value *ArgStruct = EI;
1795 llvm::Value *SRet =
1796 Builder.CreateStructGEP(ArgStruct, RetAI.getInAllocaFieldIndex());
1797 RV = Builder.CreateLoad(SRet, "sret");
1798 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001799 break;
1800
Daniel Dunbar03816342010-08-21 02:24:36 +00001801 case ABIArgInfo::Indirect: {
John McCall47fb9502013-03-07 21:37:08 +00001802 switch (getEvaluationKind(RetTy)) {
1803 case TEK_Complex: {
1804 ComplexPairTy RT =
Nick Lewycky2d84e842013-10-02 02:29:49 +00001805 EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
1806 EndLoc);
John McCall47fb9502013-03-07 21:37:08 +00001807 EmitStoreOfComplex(RT,
1808 MakeNaturalAlignAddrLValue(CurFn->arg_begin(), RetTy),
1809 /*isInit*/ true);
1810 break;
1811 }
1812 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00001813 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00001814 break;
1815 case TEK_Scalar:
1816 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
1817 MakeNaturalAlignAddrLValue(CurFn->arg_begin(), RetTy),
1818 /*isInit*/ true);
1819 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00001820 }
1821 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00001822 }
Chris Lattner726b3d02010-06-26 23:13:19 +00001823
1824 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001825 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001826 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
1827 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001828 // The internal return value temp always will have pointer-to-return-type
1829 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001830
John McCall6e1c0122012-01-29 02:35:02 +00001831 // If there is a dominating store to ReturnValue, we can elide
1832 // the load, zap the store, and usually zap the alloca.
1833 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00001834 // Reuse the debug location from the store unless there is
1835 // cleanup code to be emitted between the store and return
1836 // instruction.
1837 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00001838 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001839 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001840 RV = SI->getValueOperand();
1841 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001842
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001843 // If that was the only use of the return value, nuke it as well now.
1844 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
1845 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
1846 ReturnValue = 0;
1847 }
John McCall6e1c0122012-01-29 02:35:02 +00001848
1849 // Otherwise, we have to do a simple load.
1850 } else {
1851 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00001852 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001853 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001854 llvm::Value *V = ReturnValue;
1855 // If the value is offset in memory, apply the offset now.
1856 if (unsigned Offs = RetAI.getDirectOffset()) {
1857 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
1858 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001859 V = Builder.CreateBitCast(V,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001860 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
1861 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001862
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001863 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00001864 }
John McCall31168b02011-06-15 23:02:42 +00001865
1866 // In ARC, end functions that return a retainable type with a call
1867 // to objc_autoreleaseReturnValue.
1868 if (AutoreleaseResult) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001869 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001870 !FI.isReturnsRetained() &&
1871 RetTy->isObjCRetainableType());
1872 RV = emitAutoreleaseOfResult(*this, RV);
1873 }
1874
Chris Lattner726b3d02010-06-26 23:13:19 +00001875 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00001876
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001877 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00001878 break;
1879
1880 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001881 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00001882 }
1883
Daniel Dunbar6696e222010-06-30 21:27:58 +00001884 llvm::Instruction *Ret = RV ? Builder.CreateRet(RV) : Builder.CreateRetVoid();
Devang Patel65497582010-07-21 18:08:50 +00001885 if (!RetDbgLoc.isUnknown())
1886 Ret->setDebugLoc(RetDbgLoc);
Daniel Dunbar613855c2008-09-09 23:27:19 +00001887}
1888
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001889static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
1890 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
1891 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
1892}
1893
1894static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty) {
1895 // FIXME: Generate IR in one pass, rather than going back and fixing up these
1896 // placeholders.
1897 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
1898 llvm::Value *Placeholder =
1899 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
1900 Placeholder = CGF.Builder.CreateLoad(Placeholder);
1901 return AggValueSlot::forAddr(Placeholder, CharUnits::Zero(),
1902 Ty.getQualifiers(),
1903 AggValueSlot::IsNotDestructed,
1904 AggValueSlot::DoesNotNeedGCBarriers,
1905 AggValueSlot::IsNotAliased);
1906}
1907
John McCall32ea9692011-03-11 20:59:21 +00001908void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001909 const VarDecl *param,
1910 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00001911 // StartFunction converted the ABI-lowered parameter(s) into a
1912 // local alloca. We need to turn that into an r-value suitable
1913 // for EmitCall.
John McCall32ea9692011-03-11 20:59:21 +00001914 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00001915
John McCall32ea9692011-03-11 20:59:21 +00001916 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001917
John McCall23f66262010-05-26 22:34:26 +00001918 // For the most part, we just need to load the alloca, except:
1919 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall47fb9502013-03-07 21:37:08 +00001920 // 2) references to non-scalars are pointers directly to the aggregate.
1921 // I don't know why references to scalars are different here.
John McCall32ea9692011-03-11 20:59:21 +00001922 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall47fb9502013-03-07 21:37:08 +00001923 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall32ea9692011-03-11 20:59:21 +00001924 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00001925
1926 // Locals which are references to scalars are represented
1927 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00001928 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00001929 }
1930
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001931 if (isInAllocaArgument(CGM.getCXXABI(), type)) {
1932 AggValueSlot Slot = createPlaceholderSlot(*this, type);
1933 Slot.setExternallyDestructed();
1934
1935 // FIXME: Either emit a copy constructor call, or figure out how to do
1936 // guaranteed tail calls with perfect forwarding in LLVM.
1937 CGM.ErrorUnsupported(param, "non-trivial argument copy for thunk");
1938 EmitNullInitialization(Slot.getAddr(), type);
1939
1940 RValue RV = Slot.asRValue();
1941 args.add(RV, type);
1942 return;
1943 }
1944
Nick Lewycky2d84e842013-10-02 02:29:49 +00001945 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00001946}
1947
John McCall31168b02011-06-15 23:02:42 +00001948static bool isProvablyNull(llvm::Value *addr) {
1949 return isa<llvm::ConstantPointerNull>(addr);
1950}
1951
1952static bool isProvablyNonNull(llvm::Value *addr) {
1953 return isa<llvm::AllocaInst>(addr);
1954}
1955
1956/// Emit the actual writing-back of a writeback.
1957static void emitWriteback(CodeGenFunction &CGF,
1958 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00001959 const LValue &srcLV = writeback.Source;
1960 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00001961 assert(!isProvablyNull(srcAddr) &&
1962 "shouldn't have writeback for provably null argument");
1963
1964 llvm::BasicBlock *contBB = 0;
1965
1966 // If the argument wasn't provably non-null, we need to null check
1967 // before doing the store.
1968 bool provablyNonNull = isProvablyNonNull(srcAddr);
1969 if (!provablyNonNull) {
1970 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
1971 contBB = CGF.createBasicBlock("icr.done");
1972
1973 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
1974 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
1975 CGF.EmitBlock(writebackBB);
1976 }
1977
1978 // Load the value to writeback.
1979 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
1980
1981 // Cast it back, in case we're writing an id to a Foo* or something.
1982 value = CGF.Builder.CreateBitCast(value,
1983 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
1984 "icr.writeback-cast");
1985
1986 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00001987
1988 // If we have a "to use" value, it's something we need to emit a use
1989 // of. This has to be carefully threaded in: if it's done after the
1990 // release it's potentially undefined behavior (and the optimizer
1991 // will ignore it), and if it happens before the retain then the
1992 // optimizer could move the release there.
1993 if (writeback.ToUse) {
1994 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
1995
1996 // Retain the new value. No need to block-copy here: the block's
1997 // being passed up the stack.
1998 value = CGF.EmitARCRetainNonBlock(value);
1999
2000 // Emit the intrinsic use here.
2001 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2002
2003 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00002004 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00002005
2006 // Put the new value in place (primitively).
2007 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2008
2009 // Release the old value.
2010 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2011
2012 // Otherwise, we can just do a normal lvalue store.
2013 } else {
2014 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2015 }
John McCall31168b02011-06-15 23:02:42 +00002016
2017 // Jump to the continuation block.
2018 if (!provablyNonNull)
2019 CGF.EmitBlock(contBB);
2020}
2021
2022static void emitWritebacks(CodeGenFunction &CGF,
2023 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00002024 for (const auto &I : args.writebacks())
2025 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00002026}
2027
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002028static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2029 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002030 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002031 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2032 CallArgs.getCleanupsToDeactivate();
2033 // Iterate in reverse to increase the likelihood of popping the cleanup.
2034 for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
2035 I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
2036 CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
2037 I->IsActiveIP->eraseFromParent();
2038 }
2039}
2040
John McCalleff18842013-03-23 02:35:54 +00002041static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2042 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2043 if (uop->getOpcode() == UO_AddrOf)
2044 return uop->getSubExpr();
2045 return 0;
2046}
2047
John McCall31168b02011-06-15 23:02:42 +00002048/// Emit an argument that's being passed call-by-writeback. That is,
2049/// we are passing the address of
2050static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2051 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00002052 LValue srcLV;
2053
2054 // Make an optimistic effort to emit the address as an l-value.
2055 // This can fail if the the argument expression is more complicated.
2056 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2057 srcLV = CGF.EmitLValue(lvExpr);
2058
2059 // Otherwise, just emit it as a scalar.
2060 } else {
2061 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
2062
2063 QualType srcAddrType =
2064 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
2065 srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
2066 }
2067 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002068
2069 // The dest and src types don't necessarily match in LLVM terms
2070 // because of the crazy ObjC compatibility rules.
2071
Chris Lattner2192fe52011-07-18 04:24:23 +00002072 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00002073 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
2074
2075 // If the address is a constant null, just pass the appropriate null.
2076 if (isProvablyNull(srcAddr)) {
2077 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
2078 CRE->getType());
2079 return;
2080 }
2081
John McCall31168b02011-06-15 23:02:42 +00002082 // Create the temporary.
2083 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
2084 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002085 // Loading an l-value can introduce a cleanup if the l-value is __weak,
2086 // and that cleanup will be conditional if we can't prove that the l-value
2087 // isn't null, so we need to register a dominating point so that the cleanups
2088 // system will make valid IR.
2089 CodeGenFunction::ConditionalEvaluation condEval(CGF);
2090
John McCall31168b02011-06-15 23:02:42 +00002091 // Zero-initialize it if we're not doing a copy-initialization.
2092 bool shouldCopy = CRE->shouldCopy();
2093 if (!shouldCopy) {
2094 llvm::Value *null =
2095 llvm::ConstantPointerNull::get(
2096 cast<llvm::PointerType>(destType->getElementType()));
2097 CGF.Builder.CreateStore(null, temp);
2098 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002099
John McCall31168b02011-06-15 23:02:42 +00002100 llvm::BasicBlock *contBB = 0;
John McCalleff18842013-03-23 02:35:54 +00002101 llvm::BasicBlock *originBB = 0;
John McCall31168b02011-06-15 23:02:42 +00002102
2103 // If the address is *not* known to be non-null, we need to switch.
2104 llvm::Value *finalArgument;
2105
2106 bool provablyNonNull = isProvablyNonNull(srcAddr);
2107 if (provablyNonNull) {
2108 finalArgument = temp;
2109 } else {
2110 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2111
2112 finalArgument = CGF.Builder.CreateSelect(isNull,
2113 llvm::ConstantPointerNull::get(destType),
2114 temp, "icr.argument");
2115
2116 // If we need to copy, then the load has to be conditional, which
2117 // means we need control flow.
2118 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00002119 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002120 contBB = CGF.createBasicBlock("icr.cont");
2121 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
2122 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
2123 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002124 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00002125 }
2126 }
2127
John McCalleff18842013-03-23 02:35:54 +00002128 llvm::Value *valueToUse = 0;
2129
John McCall31168b02011-06-15 23:02:42 +00002130 // Perform a copy if necessary.
2131 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002132 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002133 assert(srcRV.isScalar());
2134
2135 llvm::Value *src = srcRV.getScalarVal();
2136 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
2137 "icr.cast");
2138
2139 // Use an ordinary store, not a store-to-lvalue.
2140 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00002141
2142 // If optimization is enabled, and the value was held in a
2143 // __strong variable, we need to tell the optimizer that this
2144 // value has to stay alive until we're doing the store back.
2145 // This is because the temporary is effectively unretained,
2146 // and so otherwise we can violate the high-level semantics.
2147 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2148 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
2149 valueToUse = src;
2150 }
John McCall31168b02011-06-15 23:02:42 +00002151 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002152
John McCall31168b02011-06-15 23:02:42 +00002153 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002154 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00002155 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002156 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00002157
2158 // Make a phi for the value to intrinsically use.
2159 if (valueToUse) {
2160 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2161 "icr.to-use");
2162 phiToUse->addIncoming(valueToUse, copyBB);
2163 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2164 originBB);
2165 valueToUse = phiToUse;
2166 }
2167
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002168 condEval.end(CGF);
2169 }
John McCall31168b02011-06-15 23:02:42 +00002170
John McCalleff18842013-03-23 02:35:54 +00002171 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00002172 args.add(RValue::get(finalArgument), CRE->getType());
2173}
2174
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002175void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
2176 assert(!StackBase && !StackCleanup.isValid());
2177
2178 // Save the stack.
2179 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
2180 StackBase = CGF.Builder.CreateCall(F, "inalloca.save");
2181
2182 // Control gets really tied up in landing pads, so we have to spill the
2183 // stacksave to an alloca to avoid violating SSA form.
2184 // TODO: This is dead if we never emit the cleanup. We should create the
2185 // alloca and store lazily on the first cleanup emission.
2186 StackBaseMem = CGF.CreateTempAlloca(CGF.Int8PtrTy, "inalloca.spmem");
2187 CGF.Builder.CreateStore(StackBase, StackBaseMem);
2188 CGF.pushStackRestore(EHCleanup, StackBaseMem);
2189 StackCleanup = CGF.EHStack.getInnermostEHScope();
2190 assert(StackCleanup.isValid());
2191}
2192
2193void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
2194 if (StackBase) {
2195 CGF.DeactivateCleanupBlock(StackCleanup, StackBase);
2196 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
2197 // We could load StackBase from StackBaseMem, but in the non-exceptional
2198 // case we can skip it.
2199 CGF.Builder.CreateCall(F, StackBase);
2200 }
2201}
2202
Reid Kleckner739756c2013-12-04 19:23:12 +00002203void CodeGenFunction::EmitCallArgs(CallArgList &Args,
2204 ArrayRef<QualType> ArgTypes,
2205 CallExpr::const_arg_iterator ArgBeg,
2206 CallExpr::const_arg_iterator ArgEnd,
2207 bool ForceColumnInfo) {
2208 CGDebugInfo *DI = getDebugInfo();
2209 SourceLocation CallLoc;
2210 if (DI) CallLoc = DI->getLocation();
2211
2212 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
2213 // because arguments are destroyed left to right in the callee.
2214 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002215 // Insert a stack save if we're going to need any inalloca args.
2216 bool HasInAllocaArgs = false;
2217 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
2218 I != E && !HasInAllocaArgs; ++I)
2219 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
2220 if (HasInAllocaArgs) {
2221 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2222 Args.allocateArgumentMemory(*this);
2223 }
2224
2225 // Evaluate each argument.
Reid Kleckner739756c2013-12-04 19:23:12 +00002226 size_t CallArgsStart = Args.size();
2227 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
2228 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2229 EmitCallArg(Args, *Arg, ArgTypes[I]);
2230 // Restore the debug location.
2231 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2232 }
2233
2234 // Un-reverse the arguments we just evaluated so they match up with the LLVM
2235 // IR function.
2236 std::reverse(Args.begin() + CallArgsStart, Args.end());
2237 return;
2238 }
2239
2240 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
2241 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2242 assert(Arg != ArgEnd);
2243 EmitCallArg(Args, *Arg, ArgTypes[I]);
2244 // Restore the debug location.
2245 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2246 }
2247}
2248
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002249namespace {
2250
2251struct DestroyUnpassedArg : EHScopeStack::Cleanup {
2252 DestroyUnpassedArg(llvm::Value *Addr, QualType Ty)
2253 : Addr(Addr), Ty(Ty) {}
2254
2255 llvm::Value *Addr;
2256 QualType Ty;
2257
Craig Topper4f12f102014-03-12 06:41:41 +00002258 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002259 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
2260 assert(!Dtor->isTrivial());
2261 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
2262 /*Delegating=*/false, Addr);
2263 }
2264};
2265
2266}
2267
John McCall32ea9692011-03-11 20:59:21 +00002268void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2269 QualType type) {
John McCall31168b02011-06-15 23:02:42 +00002270 if (const ObjCIndirectCopyRestoreExpr *CRE
2271 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002272 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00002273 assert(getContext().hasSameType(E->getType(), type));
2274 return emitWritebackArg(*this, args, CRE);
2275 }
2276
John McCall0a76c0c2011-08-26 18:42:59 +00002277 assert(type->isReferenceType() == E->isGLValue() &&
2278 "reference binding to unmaterialized r-value!");
2279
John McCall17054bd62011-08-26 21:08:13 +00002280 if (E->isGLValue()) {
2281 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00002282 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00002283 }
Mike Stump11289f42009-09-09 15:08:12 +00002284
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002285 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2286
2287 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2288 // However, we still have to push an EH-only cleanup in case we unwind before
2289 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00002290 if (HasAggregateEvalKind &&
2291 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2292 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00002293 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00002294 AggValueSlot Slot;
2295 if (args.isUsingInAlloca())
2296 Slot = createPlaceholderSlot(*this, type);
2297 else
2298 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00002299
2300 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2301 bool DestroyedInCallee =
2302 RD && RD->hasNonTrivialDestructor() &&
2303 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
2304 if (DestroyedInCallee)
2305 Slot.setExternallyDestructed();
2306
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002307 EmitAggExpr(E, Slot);
2308 RValue RV = Slot.asRValue();
2309 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002310
Reid Klecknere39ee212014-05-03 00:33:28 +00002311 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002312 // Create a no-op GEP between the placeholder and the cleanup so we can
2313 // RAUW it successfully. It also serves as a marker of the first
2314 // instruction where the cleanup is active.
2315 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddr(), type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002316 // This unreachable is a temporary marker which will be removed later.
2317 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2318 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002319 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002320 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002321 }
2322
2323 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00002324 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2325 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2326 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00002327 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2328 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2329 } else {
2330 // We can't represent a misaligned lvalue in the CallArgList, so copy
2331 // to an aligned temporary now.
2332 llvm::Value *tmp = CreateMemTemp(type);
2333 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2334 L.getAlignment());
2335 args.add(RValue::getAggregate(tmp), type);
2336 }
Eli Friedmandf968192011-05-26 00:10:27 +00002337 return;
2338 }
2339
John McCall32ea9692011-03-11 20:59:21 +00002340 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00002341}
2342
Dan Gohman515a60d2012-02-16 00:57:37 +00002343// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2344// optimizer it can aggressively ignore unwind edges.
2345void
2346CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2347 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2348 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2349 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2350 CGM.getNoObjCARCExceptionsMetadata());
2351}
2352
John McCall882987f2013-02-28 19:01:20 +00002353/// Emits a call to the given no-arguments nounwind runtime function.
2354llvm::CallInst *
2355CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2356 const llvm::Twine &name) {
2357 return EmitNounwindRuntimeCall(callee, ArrayRef<llvm::Value*>(), name);
2358}
2359
2360/// Emits a call to the given nounwind runtime function.
2361llvm::CallInst *
2362CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2363 ArrayRef<llvm::Value*> args,
2364 const llvm::Twine &name) {
2365 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2366 call->setDoesNotThrow();
2367 return call;
2368}
2369
2370/// Emits a simple call (never an invoke) to the given no-arguments
2371/// runtime function.
2372llvm::CallInst *
2373CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2374 const llvm::Twine &name) {
2375 return EmitRuntimeCall(callee, ArrayRef<llvm::Value*>(), name);
2376}
2377
2378/// Emits a simple call (never an invoke) to the given runtime
2379/// function.
2380llvm::CallInst *
2381CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2382 ArrayRef<llvm::Value*> args,
2383 const llvm::Twine &name) {
2384 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2385 call->setCallingConv(getRuntimeCC());
2386 return call;
2387}
2388
2389/// Emits a call or invoke to the given noreturn runtime function.
2390void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2391 ArrayRef<llvm::Value*> args) {
2392 if (getInvokeDest()) {
2393 llvm::InvokeInst *invoke =
2394 Builder.CreateInvoke(callee,
2395 getUnreachableBlock(),
2396 getInvokeDest(),
2397 args);
2398 invoke->setDoesNotReturn();
2399 invoke->setCallingConv(getRuntimeCC());
2400 } else {
2401 llvm::CallInst *call = Builder.CreateCall(callee, args);
2402 call->setDoesNotReturn();
2403 call->setCallingConv(getRuntimeCC());
2404 Builder.CreateUnreachable();
2405 }
Justin Bogner06bd6d02014-01-13 21:24:18 +00002406 PGO.setCurrentRegionUnreachable();
John McCall882987f2013-02-28 19:01:20 +00002407}
2408
2409/// Emits a call or invoke instruction to the given nullary runtime
2410/// function.
2411llvm::CallSite
2412CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2413 const Twine &name) {
2414 return EmitRuntimeCallOrInvoke(callee, ArrayRef<llvm::Value*>(), name);
2415}
2416
2417/// Emits a call or invoke instruction to the given runtime function.
2418llvm::CallSite
2419CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2420 ArrayRef<llvm::Value*> args,
2421 const Twine &name) {
2422 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2423 callSite.setCallingConv(getRuntimeCC());
2424 return callSite;
2425}
2426
2427llvm::CallSite
2428CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2429 const Twine &Name) {
2430 return EmitCallOrInvoke(Callee, ArrayRef<llvm::Value *>(), Name);
2431}
2432
John McCallbd309292010-07-06 01:34:17 +00002433/// Emits a call or invoke instruction to the given function, depending
2434/// on the current state of the EH stack.
2435llvm::CallSite
2436CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00002437 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002438 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00002439 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00002440
Dan Gohman515a60d2012-02-16 00:57:37 +00002441 llvm::Instruction *Inst;
2442 if (!InvokeDest)
2443 Inst = Builder.CreateCall(Callee, Args, Name);
2444 else {
2445 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
2446 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
2447 EmitBlock(ContBB);
2448 }
2449
2450 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2451 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002452 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00002453 AddObjCARCExceptionMetadata(Inst);
2454
2455 return Inst;
John McCallbd309292010-07-06 01:34:17 +00002456}
2457
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002458static void checkArgMatches(llvm::Value *Elt, unsigned &ArgNo,
2459 llvm::FunctionType *FTy) {
2460 if (ArgNo < FTy->getNumParams())
2461 assert(Elt->getType() == FTy->getParamType(ArgNo));
2462 else
2463 assert(FTy->isVarArg());
2464 ++ArgNo;
2465}
2466
Chris Lattnerd59d8672011-07-12 06:29:11 +00002467void CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV,
Craig Topper5603df42013-07-05 19:34:19 +00002468 SmallVectorImpl<llvm::Value *> &Args,
Chris Lattnerd59d8672011-07-12 06:29:11 +00002469 llvm::FunctionType *IRFuncTy) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002470 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2471 unsigned NumElts = AT->getSize().getZExtValue();
2472 QualType EltTy = AT->getElementType();
2473 llvm::Value *Addr = RV.getAggregateAddr();
2474 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
2475 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, Elt);
Nick Lewycky2d84e842013-10-02 02:29:49 +00002476 RValue EltRV = convertTempToRValue(EltAddr, EltTy, SourceLocation());
Bob Wilsone826a2a2011-08-03 05:58:22 +00002477 ExpandTypeToArgs(EltTy, EltRV, Args, IRFuncTy);
Chris Lattnerd59d8672011-07-12 06:29:11 +00002478 }
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002479 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002480 RecordDecl *RD = RT->getDecl();
2481 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
Eli Friedman7f1ff602012-04-16 03:54:45 +00002482 LValue LV = MakeAddrLValue(RV.getAggregateAddr(), Ty);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002483
2484 if (RD->isUnion()) {
2485 const FieldDecl *LargestFD = 0;
2486 CharUnits UnionSize = CharUnits::Zero();
2487
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002488 for (const auto *FD : RD->fields()) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002489 assert(!FD->isBitField() &&
2490 "Cannot expand structure with bit-field members.");
2491 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
2492 if (UnionSize < FieldSize) {
2493 UnionSize = FieldSize;
2494 LargestFD = FD;
2495 }
2496 }
2497 if (LargestFD) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002498 RValue FldRV = EmitRValueForField(LV, LargestFD, SourceLocation());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002499 ExpandTypeToArgs(LargestFD->getType(), FldRV, Args, IRFuncTy);
2500 }
2501 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002502 for (const auto *FD : RD->fields()) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002503 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002504 ExpandTypeToArgs(FD->getType(), FldRV, Args, IRFuncTy);
2505 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00002506 }
Eli Friedman95ff7002011-11-15 02:46:03 +00002507 } else if (Ty->isAnyComplexType()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00002508 ComplexPairTy CV = RV.getComplexVal();
2509 Args.push_back(CV.first);
2510 Args.push_back(CV.second);
2511 } else {
Chris Lattnerd59d8672011-07-12 06:29:11 +00002512 assert(RV.isScalar() &&
2513 "Unexpected non-scalar rvalue during struct expansion.");
2514
2515 // Insert a bitcast as needed.
2516 llvm::Value *V = RV.getScalarVal();
2517 if (Args.size() < IRFuncTy->getNumParams() &&
2518 V->getType() != IRFuncTy->getParamType(Args.size()))
2519 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(Args.size()));
2520
2521 Args.push_back(V);
2522 }
2523}
2524
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002525/// \brief Store a non-aggregate value to an address to initialize it. For
2526/// initialization, a non-atomic store will be used.
2527static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
2528 LValue Dst) {
2529 if (Src.isScalar())
2530 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
2531 else
2532 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
2533}
2534
2535void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
2536 llvm::Value *New) {
2537 DeferredReplacements.push_back(std::make_pair(Old, New));
2538}
Chris Lattnerd59d8672011-07-12 06:29:11 +00002539
Daniel Dunbard931a872009-02-02 22:03:45 +00002540RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00002541 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00002542 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002543 const CallArgList &CallArgs,
David Chisnall9eecafa2010-05-01 11:15:56 +00002544 const Decl *TargetDecl,
David Chisnallff5f88c2010-05-02 13:41:58 +00002545 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00002546 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002547 SmallVector<llvm::Value*, 16> Args;
Daniel Dunbar613855c2008-09-09 23:27:19 +00002548
2549 // Handle struct-return functions by passing a pointer to the
2550 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00002551 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002552 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002553
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002554 // IRArgNo - Keep track of the argument number in the callee we're looking at.
2555 unsigned IRArgNo = 0;
2556 llvm::FunctionType *IRFuncTy =
2557 cast<llvm::FunctionType>(
2558 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00002559
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002560 // If we're using inalloca, insert the allocation after the stack save.
2561 // FIXME: Do this earlier rather than hacking it in here!
2562 llvm::Value *ArgMemory = 0;
2563 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
Reid Kleckner9df1d972014-04-10 01:40:15 +00002564 llvm::Instruction *IP = CallArgs.getStackBase();
2565 llvm::AllocaInst *AI;
2566 if (IP) {
2567 IP = IP->getNextNode();
2568 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
2569 } else {
2570 AI = Builder.CreateAlloca(ArgStruct, nullptr, "argmem");
2571 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002572 AI->setUsedWithInAlloca(true);
2573 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
2574 ArgMemory = AI;
2575 }
2576
Chris Lattner4ca97c32009-06-13 00:26:38 +00002577 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00002578 // alloca to hold the result, unless one is given to us.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002579 llvm::Value *SRetPtr = 0;
2580 if (CGM.ReturnTypeUsesSRet(CallInfo) || RetAI.isInAlloca()) {
2581 SRetPtr = ReturnValue.getValue();
2582 if (!SRetPtr)
2583 SRetPtr = CreateMemTemp(RetTy);
2584 if (CGM.ReturnTypeUsesSRet(CallInfo)) {
2585 Args.push_back(SRetPtr);
2586 checkArgMatches(SRetPtr, IRArgNo, IRFuncTy);
2587 } else {
2588 llvm::Value *Addr =
2589 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
2590 Builder.CreateStore(SRetPtr, Addr);
2591 }
Anders Carlsson17490832009-12-24 20:40:36 +00002592 }
Mike Stump11289f42009-09-09 15:08:12 +00002593
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002594 assert(CallInfo.arg_size() == CallArgs.size() &&
2595 "Mismatch between function signature & arguments.");
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002596 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002597 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002598 I != E; ++I, ++info_it) {
2599 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00002600 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002601
John McCall47fb9502013-03-07 21:37:08 +00002602 CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002603
2604 // Insert a padding argument to ensure proper alignment.
2605 if (llvm::Type *PaddingType = ArgInfo.getPaddingType()) {
2606 Args.push_back(llvm::UndefValue::get(PaddingType));
2607 ++IRArgNo;
2608 }
2609
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002610 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002611 case ABIArgInfo::InAlloca: {
2612 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2613 if (RV.isAggregate()) {
2614 // Replace the placeholder with the appropriate argument slot GEP.
2615 llvm::Instruction *Placeholder =
2616 cast<llvm::Instruction>(RV.getAggregateAddr());
2617 CGBuilderTy::InsertPoint IP = Builder.saveIP();
2618 Builder.SetInsertPoint(Placeholder);
2619 llvm::Value *Addr = Builder.CreateStructGEP(
2620 ArgMemory, ArgInfo.getInAllocaFieldIndex());
2621 Builder.restoreIP(IP);
2622 deferPlaceholderReplacement(Placeholder, Addr);
2623 } else {
2624 // Store the RValue into the argument struct.
2625 llvm::Value *Addr =
2626 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
David Majnemer32b57b02014-03-31 16:12:47 +00002627 unsigned AS = Addr->getType()->getPointerAddressSpace();
2628 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
2629 // There are some cases where a trivial bitcast is not avoidable. The
2630 // definition of a type later in a translation unit may change it's type
2631 // from {}* to (%struct.foo*)*.
2632 if (Addr->getType() != MemType)
2633 Addr = Builder.CreateBitCast(Addr, MemType);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002634 LValue argLV = MakeAddrLValue(Addr, I->Ty, TypeAlign);
2635 EmitInitStoreOfNonAggregate(*this, RV, argLV);
2636 }
2637 break; // Don't increment IRArgNo!
2638 }
2639
Daniel Dunbar03816342010-08-21 02:24:36 +00002640 case ABIArgInfo::Indirect: {
Daniel Dunbar747865a2009-02-05 09:16:39 +00002641 if (RV.isScalar() || RV.isComplex()) {
2642 // Make a temporary alloca to pass the argument.
Eli Friedman7e68c882011-06-15 18:26:32 +00002643 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2644 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
2645 AI->setAlignment(ArgInfo.getIndirectAlign());
2646 Args.push_back(AI);
John McCall47fb9502013-03-07 21:37:08 +00002647
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002648 LValue argLV = MakeAddrLValue(Args.back(), I->Ty, TypeAlign);
2649 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002650
2651 // Validate argument match.
2652 checkArgMatches(AI, IRArgNo, IRFuncTy);
Daniel Dunbar747865a2009-02-05 09:16:39 +00002653 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002654 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00002655 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002656 // 1. If the argument is not byval, and we are required to copy the
2657 // source. (This case doesn't occur on any common architecture.)
2658 // 2. If the argument is byval, RV is not sufficiently aligned, and
2659 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00002660 // 3. If the argument is byval, but RV is located in an address space
2661 // different than that of the argument (0).
Eli Friedmanf7456192011-06-15 22:09:18 +00002662 llvm::Value *Addr = RV.getAggregateAddr();
2663 unsigned Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002664 const llvm::DataLayout *TD = &CGM.getDataLayout();
Guy Benyei3832bfd2013-03-10 12:59:00 +00002665 const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
2666 const unsigned ArgAddrSpace = (IRArgNo < IRFuncTy->getNumParams() ?
2667 IRFuncTy->getParamType(IRArgNo)->getPointerAddressSpace() : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00002668 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall47fb9502013-03-07 21:37:08 +00002669 (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
Guy Benyei3832bfd2013-03-10 12:59:00 +00002670 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align) ||
2671 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002672 // Create an aligned temporary, and copy to it.
Eli Friedmanf7456192011-06-15 22:09:18 +00002673 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2674 if (Align > AI->getAlignment())
2675 AI->setAlignment(Align);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002676 Args.push_back(AI);
Chad Rosier615ed1a2012-03-29 17:37:10 +00002677 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002678
2679 // Validate argument match.
2680 checkArgMatches(AI, IRArgNo, IRFuncTy);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002681 } else {
2682 // Skip the extra memcpy call.
Eli Friedmanf7456192011-06-15 22:09:18 +00002683 Args.push_back(Addr);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002684
2685 // Validate argument match.
2686 checkArgMatches(Addr, IRArgNo, IRFuncTy);
Eli Friedmaneb7fab62011-06-14 01:37:52 +00002687 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002688 }
2689 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002690 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002691
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002692 case ABIArgInfo::Ignore:
2693 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002694
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002695 case ABIArgInfo::Extend:
2696 case ABIArgInfo::Direct: {
2697 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002698 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
2699 ArgInfo.getDirectOffset() == 0) {
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002700 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002701 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002702 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002703 else
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002704 V = Builder.CreateLoad(RV.getAggregateAddr());
2705
Chris Lattner3ce86682011-07-12 04:53:39 +00002706 // If the argument doesn't match, perform a bitcast to coerce it. This
2707 // can happen due to trivial type mismatches.
2708 if (IRArgNo < IRFuncTy->getNumParams() &&
2709 V->getType() != IRFuncTy->getParamType(IRArgNo))
2710 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRArgNo));
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002711 Args.push_back(V);
2712
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002713 checkArgMatches(V, IRArgNo, IRFuncTy);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002714 break;
2715 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002716
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002717 // FIXME: Avoid the conversion through memory if possible.
2718 llvm::Value *SrcPtr;
John McCall47fb9502013-03-07 21:37:08 +00002719 if (RV.isScalar() || RV.isComplex()) {
Eli Friedmanf4258eb2011-05-02 18:05:27 +00002720 SrcPtr = CreateMemTemp(I->Ty, "coerce");
John McCall47fb9502013-03-07 21:37:08 +00002721 LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002722 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Mike Stump11289f42009-09-09 15:08:12 +00002723 } else
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002724 SrcPtr = RV.getAggregateAddr();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002725
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002726 // If the value is offset in memory, apply the offset now.
2727 if (unsigned Offs = ArgInfo.getDirectOffset()) {
2728 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
2729 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002730 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002731 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
2732
2733 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002734
Chris Lattner3dd716c2010-06-28 23:44:11 +00002735 // If the coerce-to type is a first class aggregate, we flatten it and
2736 // pass the elements. Either way is semantically identical, but fast-isel
2737 // and the optimizer generally likes scalar values better than FCAs.
James Molloy1aa0d5f2014-05-09 16:17:09 +00002738 if (llvm::StructType *STy =
2739 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType())) {
Chandler Carrutha6399a52012-10-10 11:29:08 +00002740 llvm::Type *SrcTy =
2741 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
2742 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
2743 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
2744
2745 // If the source type is smaller than the destination type of the
2746 // coerce-to logic, copy the source value into a temp alloca the size
2747 // of the destination type to allow loading all of it. The bits past
2748 // the source value are left undef.
2749 if (SrcSize < DstSize) {
2750 llvm::AllocaInst *TempAlloca
2751 = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
2752 Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
2753 SrcPtr = TempAlloca;
2754 } else {
2755 SrcPtr = Builder.CreateBitCast(SrcPtr,
2756 llvm::PointerType::getUnqual(STy));
2757 }
2758
Chris Lattnerceddafb2010-07-05 20:41:41 +00002759 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2760 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerff941a62010-07-28 18:24:28 +00002761 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
2762 // We don't know what we're loading from.
2763 LI->setAlignment(1);
2764 Args.push_back(LI);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002765
2766 // Validate argument match.
2767 checkArgMatches(LI, IRArgNo, IRFuncTy);
Chris Lattner15ec3612010-06-29 00:06:42 +00002768 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00002769 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00002770 // In the simple case, just pass the coerced loaded value.
2771 Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(),
2772 *this));
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002773
2774 // Validate argument match.
2775 checkArgMatches(Args.back(), IRArgNo, IRFuncTy);
Chris Lattner3dd716c2010-06-28 23:44:11 +00002776 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002777
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002778 break;
2779 }
2780
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002781 case ABIArgInfo::Expand:
Chris Lattnerd59d8672011-07-12 06:29:11 +00002782 ExpandTypeToArgs(I->Ty, RV, Args, IRFuncTy);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002783 IRArgNo = Args.size();
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00002784 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00002785 }
2786 }
Mike Stump11289f42009-09-09 15:08:12 +00002787
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002788 if (ArgMemory) {
2789 llvm::Value *Arg = ArgMemory;
2790 llvm::Type *LastParamTy =
2791 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
2792 if (Arg->getType() != LastParamTy) {
2793#ifndef NDEBUG
2794 // Assert that these structs have equivalent element types.
2795 llvm::StructType *FullTy = CallInfo.getArgStruct();
2796 llvm::StructType *Prefix = cast<llvm::StructType>(
2797 cast<llvm::PointerType>(LastParamTy)->getElementType());
2798
2799 // For variadic functions, the caller might supply a larger struct than
2800 // the callee expects, and that's OK.
2801 assert(Prefix->getNumElements() == FullTy->getNumElements() ||
2802 (CallInfo.isVariadic() &&
2803 Prefix->getNumElements() <= FullTy->getNumElements()));
2804
2805 for (llvm::StructType::element_iterator PI = Prefix->element_begin(),
2806 PE = Prefix->element_end(),
2807 FI = FullTy->element_begin();
2808 PI != PE; ++PI, ++FI)
2809 assert(*PI == *FI);
2810#endif
2811 Arg = Builder.CreateBitCast(Arg, LastParamTy);
2812 }
2813 Args.push_back(Arg);
2814 }
2815
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002816 if (!CallArgs.getCleanupsToDeactivate().empty())
2817 deactivateArgCleanupsBeforeCall(*this, CallArgs);
2818
Chris Lattner4ca97c32009-06-13 00:26:38 +00002819 // If the callee is a bitcast of a function to a varargs pointer to function
2820 // type, check to see if we can remove the bitcast. This handles some cases
2821 // with unprototyped functions.
2822 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
2823 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002824 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
2825 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00002826 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00002827 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00002828
Chris Lattner4ca97c32009-06-13 00:26:38 +00002829 if (CE->getOpcode() == llvm::Instruction::BitCast &&
2830 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00002831 ActualFT->getNumParams() == CurFT->getNumParams() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00002832 ActualFT->getNumParams() == Args.size() &&
2833 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00002834 bool ArgsMatch = true;
2835 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
2836 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
2837 ArgsMatch = false;
2838 break;
2839 }
Mike Stump11289f42009-09-09 15:08:12 +00002840
Chris Lattner4ca97c32009-06-13 00:26:38 +00002841 // Strip the cast if we can get away with it. This is a nice cleanup,
2842 // but also allows us to inline the function at -O0 if it is marked
2843 // always_inline.
2844 if (ArgsMatch)
2845 Callee = CalleeF;
2846 }
2847 }
Mike Stump11289f42009-09-09 15:08:12 +00002848
Daniel Dunbar0ef34792009-09-12 00:59:20 +00002849 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00002850 CodeGen::AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00002851 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
2852 CallingConv, true);
Bill Wendling3087d022012-12-07 23:17:26 +00002853 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00002854 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00002855
John McCallbd309292010-07-06 01:34:17 +00002856 llvm::BasicBlock *InvokeDest = 0;
Bill Wendling5e85be42012-12-30 10:32:17 +00002857 if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
2858 llvm::Attribute::NoUnwind))
John McCallbd309292010-07-06 01:34:17 +00002859 InvokeDest = getInvokeDest();
2860
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002861 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00002862 if (!InvokeDest) {
Jay Foad5bd375a2011-07-15 08:37:34 +00002863 CS = Builder.CreateCall(Callee, Args);
Daniel Dunbar12347492009-02-23 17:26:39 +00002864 } else {
2865 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Jay Foad5bd375a2011-07-15 08:37:34 +00002866 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, Args);
Daniel Dunbar12347492009-02-23 17:26:39 +00002867 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00002868 }
Chris Lattnere70a0072010-06-29 16:40:28 +00002869 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00002870 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00002871
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002872 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00002873 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002874
Dan Gohman515a60d2012-02-16 00:57:37 +00002875 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2876 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002877 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00002878 AddObjCARCExceptionMetadata(CS.getInstruction());
2879
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002880 // If the call doesn't return, finish the basic block and clear the
2881 // insertion point; this allows the rest of IRgen to discard
2882 // unreachable code.
2883 if (CS.doesNotReturn()) {
2884 Builder.CreateUnreachable();
2885 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00002886
Mike Stump18bb9282009-05-16 07:57:57 +00002887 // FIXME: For now, emit a dummy basic block because expr emitters in
2888 // generally are not ready to handle emitting expressions at unreachable
2889 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002890 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00002891
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002892 // Return a reasonable RValue.
2893 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00002894 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00002895
2896 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00002897 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00002898 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002899
John McCall31168b02011-06-15 23:02:42 +00002900 // Emit any writebacks immediately. Arguably this should happen
2901 // after any return-value munging.
2902 if (CallArgs.hasWritebacks())
2903 emitWritebacks(*this, CallArgs);
2904
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002905 // The stack cleanup for inalloca arguments has to run out of the normal
2906 // lexical order, so deactivate it and run it manually here.
2907 CallArgs.freeArgumentMemory(*this);
2908
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002909 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002910 case ABIArgInfo::InAlloca:
John McCall47fb9502013-03-07 21:37:08 +00002911 case ABIArgInfo::Indirect:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002912 return convertTempToRValue(SRetPtr, RetTy, SourceLocation());
Daniel Dunbard3674e62008-09-11 01:48:57 +00002913
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002914 case ABIArgInfo::Ignore:
Daniel Dunbar01362822009-02-03 06:30:17 +00002915 // If we are ignoring an argument that had a result, make sure to
2916 // construct the appropriate return value for our caller.
Daniel Dunbarc79407f2009-02-05 07:09:07 +00002917 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002918
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002919 case ABIArgInfo::Extend:
2920 case ABIArgInfo::Direct: {
Chris Lattner3517f142011-07-13 03:59:32 +00002921 llvm::Type *RetIRTy = ConvertType(RetTy);
2922 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
John McCall47fb9502013-03-07 21:37:08 +00002923 switch (getEvaluationKind(RetTy)) {
2924 case TEK_Complex: {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002925 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
2926 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
2927 return RValue::getComplex(std::make_pair(Real, Imag));
2928 }
John McCall47fb9502013-03-07 21:37:08 +00002929 case TEK_Aggregate: {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002930 llvm::Value *DestPtr = ReturnValue.getValue();
2931 bool DestIsVolatile = ReturnValue.isVolatile();
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002932
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002933 if (!DestPtr) {
2934 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
2935 DestIsVolatile = false;
2936 }
Eli Friedmanaf9b3252011-05-17 21:08:01 +00002937 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002938 return RValue::getAggregate(DestPtr);
2939 }
John McCall47fb9502013-03-07 21:37:08 +00002940 case TEK_Scalar: {
2941 // If the argument doesn't match, perform a bitcast to coerce it. This
2942 // can happen due to trivial type mismatches.
2943 llvm::Value *V = CI;
2944 if (V->getType() != RetIRTy)
2945 V = Builder.CreateBitCast(V, RetIRTy);
2946 return RValue::get(V);
2947 }
2948 }
2949 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002950 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002951
Anders Carlsson17490832009-12-24 20:40:36 +00002952 llvm::Value *DestPtr = ReturnValue.getValue();
2953 bool DestIsVolatile = ReturnValue.isVolatile();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002954
Anders Carlsson17490832009-12-24 20:40:36 +00002955 if (!DestPtr) {
Daniel Dunbara7566f12010-02-09 02:48:28 +00002956 DestPtr = CreateMemTemp(RetTy, "coerce");
Anders Carlsson17490832009-12-24 20:40:36 +00002957 DestIsVolatile = false;
2958 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002959
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002960 // If the value is offset in memory, apply the offset now.
2961 llvm::Value *StorePtr = DestPtr;
2962 if (unsigned Offs = RetAI.getDirectOffset()) {
2963 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
2964 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002965 StorePtr = Builder.CreateBitCast(StorePtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002966 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
2967 }
2968 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002969
Nick Lewycky2d84e842013-10-02 02:29:49 +00002970 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Daniel Dunbar573884e2008-09-10 07:04:09 +00002971 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00002972
Daniel Dunbard3674e62008-09-11 01:48:57 +00002973 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002974 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar613855c2008-09-09 23:27:19 +00002975 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002976
David Blaikie83d382b2011-09-23 05:06:16 +00002977 llvm_unreachable("Unhandled ABIArgInfo::Kind");
Daniel Dunbar613855c2008-09-09 23:27:19 +00002978}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00002979
2980/* VarArg handling */
2981
2982llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
2983 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
2984}